Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): add user calendar mutations synced to Google (#5484)
gbirman89393f35ae65
diff --git a/.sqlx/query-0592c52f309fdf95dc4c0dc10dc132f717713056f6f2ff273d387f7dea9f5bfa.json b/.sqlx/query-0592c52f309fdf95dc4c0dc10dc132f717713056f6f2ff273d387f7dea9f5bfa.jsonnew file mode 100644index 0000000000..3322916104--- /dev/null+++ b/.sqlx/query-0592c52f309fdf95dc4c0dc10dc132f717713056f6f2ff273d387f7dea9f5bfa.json@@ -0,0 +1,89 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n event.id AS event_id,\n event.owner_id,\n event.is_read_only,\n source.provider_event_id AS \"provider_event_id!\",\n source.provider_recurring_event_id,\n source.account_id AS \"account_id!\",\n source.calendar_id AS \"calendar_id!\",\n calendar.provider_calendar_id,\n account.email_link_id,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\"\n FROM calendar_events event\n JOIN calendar_event_sources source\n ON source.event_id = event.id\n AND source.source_kind = 'google'\n JOIN calendars calendar ON calendar.id = source.calendar_id\n JOIN calendar_accounts account ON account.id = source.account_id\n JOIN email_links link ON link.id = account.email_link_id\n WHERE event.id = $1\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = event.source_link_id\n AND delegation.primary_macro_id = $2\n )\n )\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.last_seen_at DESC,\n source.id DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "is_read_only",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "provider_event_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "provider_recurring_event_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "account_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 6,+ "name": "calendar_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 7,+ "name": "provider_calendar_id",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "email_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 9,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "email_address",+ "type_info": "Varchar"+ },+ {+ "ordinal": 11,+ "name": "provider!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ true,+ false,+ false,+ false,+ false,+ null+ ]+ },+ "hash": "0592c52f309fdf95dc4c0dc10dc132f717713056f6f2ff273d387f7dea9f5bfa"+}diff --git a/.sqlx/query-2b6dc51b606812522b0b4f3c5b87cd521fdc21459be8d1f4fff0739327109659.json b/.sqlx/query-2b6dc51b606812522b0b4f3c5b87cd521fdc21459be8d1f4fff0739327109659.jsonnew file mode 100644index 0000000000..b485acf797--- /dev/null+++ b/.sqlx/query-2b6dc51b606812522b0b4f3c5b87cd521fdc21459be8d1f4fff0739327109659.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH deleted_sources AS (\n DELETE FROM calendar_event_sources source\n WHERE source.source_kind = 'google'\n AND source.account_id = $1\n AND source.calendar_id = $2\n AND (\n source.provider_event_id = ANY($3::text[])\n OR source.provider_recurring_event_id = ANY($3::text[])\n )\n RETURNING source.event_id\n )\n SELECT DISTINCT event_id AS \"event_id!\"\n FROM deleted_sources\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "2b6dc51b606812522b0b4f3c5b87cd521fdc21459be8d1f4fff0739327109659"+}diff --git a/.sqlx/query-2c404fefbca8ebdfc889228cc84a7033ee35af13cf5fc2381e8a0a38f7a03271.json b/.sqlx/query-2c404fefbca8ebdfc889228cc84a7033ee35af13cf5fc2381e8a0a38f7a03271.jsonnew file mode 100644index 0000000000..e1a1b25fcb--- /dev/null+++ b/.sqlx/query-2c404fefbca8ebdfc889228cc84a7033ee35af13cf5fc2381e8a0a38f7a03271.json@@ -0,0 +1,204 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n occurrence.event_id,\n canonical_source.calendar_id AS \"canonical_calendar_id?\",\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.conference_url,\n event.sequence,\n event.is_read_only,\n event.created_at,\n event.updated_at\n FROM calendar_event_occurrences occurrence\n JOIN calendar_events event ON event.id = occurrence.event_id\n LEFT JOIN LATERAL (\n SELECT source.calendar_id\n FROM calendar_event_sources source\n JOIN calendars calendar ON calendar.id = source.calendar_id\n JOIN calendar_accounts account ON account.id = source.account_id\n WHERE source.event_id = event.id\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.last_seen_at DESC,\n source.id DESC\n LIMIT 1\n ) canonical_source ON true\n WHERE occurrence.owner_id IN (\n SELECT $1::text\n UNION\n SELECT link.child_macro_id\n FROM macro_user_links link\n WHERE link.primary_macro_id = $1\n )\n AND event.status <> 'cancelled'\n AND NOT occurrence.is_cancelled\n AND (\n event.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n AND (\n occurrence.timed_span && tstzrange($2, $3, '[)')\n OR occurrence.day_span && daterange($4, $5, '[)')\n )\n AND (\n $6::timestamptz IS NULL\n OR (\n COALESCE(\n occurrence.starts_at,\n occurrence.start_date::timestamp AT TIME ZONE 'UTC'\n ),\n occurrence.event_id,\n occurrence.occurrence_key\n ) > ($6, $7, $8)\n )\n ORDER BY\n COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),\n occurrence.event_id,\n occurrence.occurrence_key\n LIMIT $9\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "canonical_calendar_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "occurrence_key",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "recurrence_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "occurrence_starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "occurrence_ends_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "occurrence_start_date",+ "type_info": "Date"+ },+ {+ "ordinal": 7,+ "name": "occurrence_end_date",+ "type_info": "Date"+ },+ {+ "ordinal": 8,+ "name": "is_cancelled",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "ical_uid",+ "type_info": "Text"+ },+ {+ "ordinal": 11,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 12,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 13,+ "name": "location",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 15,+ "name": "visibility",+ "type_info": "Text"+ },+ {+ "ordinal": 16,+ "name": "transparency",+ "type_info": "Text"+ },+ {+ "ordinal": 17,+ "name": "starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 18,+ "name": "ends_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 19,+ "name": "start_date",+ "type_info": "Date"+ },+ {+ "ordinal": 20,+ "name": "end_date",+ "type_info": "Date"+ },+ {+ "ordinal": 21,+ "name": "time_zone",+ "type_info": "Text"+ },+ {+ "ordinal": 22,+ "name": "recurrence_lines",+ "type_info": "TextArray"+ },+ {+ "ordinal": 23,+ "name": "organizer_email",+ "type_info": "Text"+ },+ {+ "ordinal": 24,+ "name": "organizer_name",+ "type_info": "Text"+ },+ {+ "ordinal": 25,+ "name": "conference_url",+ "type_info": "Text"+ },+ {+ "ordinal": 26,+ "name": "sequence",+ "type_info": "Int4"+ },+ {+ "ordinal": 27,+ "name": "is_read_only",+ "type_info": "Bool"+ },+ {+ "ordinal": 28,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 29,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Timestamptz",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ false,+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ true,+ true,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "2c404fefbca8ebdfc889228cc84a7033ee35af13cf5fc2381e8a0a38f7a03271"+}diff --git a/.sqlx/query-5af93c244b50cf5d993b2b3d7b20481afd90083ad2613fbe3de701efad4bfd61.json b/.sqlx/query-5af93c244b50cf5d993b2b3d7b20481afd90083ad2613fbe3de701efad4bfd61.jsonnew file mode 100644index 0000000000..2ad7d242d1--- /dev/null+++ b/.sqlx/query-5af93c244b50cf5d993b2b3d7b20481afd90083ad2613fbe3de701efad4bfd61.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n calendar.id,\n link.id AS email_link_id,\n link.email_address,\n calendar.name,\n calendar.color,\n calendar.is_primary,\n calendar.access_role\n FROM email_links link\n JOIN calendar_accounts account ON account.email_link_id = link.id\n JOIN calendars calendar ON calendar.account_id = account.id\n WHERE NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND (\n link.macro_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = link.id\n AND delegation.primary_macro_id = $1\n )\n )\n ORDER BY\n (link.macro_id = $1) DESC,\n link.is_primary DESC,\n link.created_at ASC,\n calendar.is_primary DESC,\n (calendar.access_role IN ('owner', 'writer')) DESC,\n calendar.name ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email_address",+ "type_info": "Varchar"+ },+ {+ "ordinal": 3,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "color",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "is_primary",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "access_role",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ true,+ false,+ true+ ]+ },+ "hash": "5af93c244b50cf5d993b2b3d7b20481afd90083ad2613fbe3de701efad4bfd61"+}diff --git a/.sqlx/query-71f1fb0b913806bbbf860c15c17471049675b45f8227bc4601b4a469ff5676c9.json b/.sqlx/query-71f1fb0b913806bbbf860c15c17471049675b45f8227bc4601b4a469ff5676c9.jsonnew file mode 100644index 0000000000..96471e2ed7--- /dev/null+++ b/.sqlx/query-71f1fb0b913806bbbf860c15c17471049675b45f8227bc4601b4a469ff5676c9.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n link.macro_id AS owner_id,\n link.id AS email_link_id,\n account.id AS account_id,\n calendar.id AS calendar_id,\n calendar.provider_calendar_id,\n calendar.access_role,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\"\n FROM email_links link\n JOIN calendar_accounts account ON account.email_link_id = link.id\n JOIN calendars calendar ON calendar.account_id = account.id\n WHERE NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND (\n ($3::uuid IS NOT NULL AND calendar.id = $3)\n OR ($3::uuid IS NULL AND calendar.is_primary)\n )\n AND ($2::uuid IS NULL OR link.id = $2)\n AND (\n link.macro_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = link.id\n AND delegation.primary_macro_id = $1\n )\n )\n ORDER BY\n (link.macro_id = $1) DESC,\n link.is_primary DESC,\n link.created_at ASC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "account_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "calendar_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "provider_calendar_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "access_role",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "email_address",+ "type_info": "Varchar"+ },+ {+ "ordinal": 8,+ "name": "provider!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true,+ false,+ false,+ null+ ]+ },+ "hash": "71f1fb0b913806bbbf860c15c17471049675b45f8227bc4601b4a469ff5676c9"+}diff --git a/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.json b/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.jsondeleted file mode 100644index 6df3f107a8..0000000000--- a/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.json+++ /dev/null@@ -1,198 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n occurrence.event_id,\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.conference_url,\n event.sequence,\n event.is_read_only,\n event.created_at,\n event.updated_at\n FROM calendar_event_occurrences occurrence\n JOIN calendar_events event ON event.id = occurrence.event_id\n WHERE occurrence.owner_id IN (\n SELECT $1::text\n UNION\n SELECT link.child_macro_id\n FROM macro_user_links link\n WHERE link.primary_macro_id = $1\n )\n AND event.status <> 'cancelled'\n AND NOT occurrence.is_cancelled\n AND (\n event.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n AND (\n occurrence.timed_span && tstzrange($2, $3, '[)')\n OR occurrence.day_span && daterange($4, $5, '[)')\n )\n AND (\n $6::timestamptz IS NULL\n OR (\n COALESCE(\n occurrence.starts_at,\n occurrence.start_date::timestamp AT TIME ZONE 'UTC'\n ),\n occurrence.event_id,\n occurrence.occurrence_key\n ) > ($6, $7, $8)\n )\n ORDER BY\n COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),\n occurrence.event_id,\n occurrence.occurrence_key\n LIMIT $9\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "event_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "occurrence_key",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "recurrence_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "occurrence_starts_at",- "type_info": "Timestamptz"- },- {- "ordinal": 4,- "name": "occurrence_ends_at",- "type_info": "Timestamptz"- },- {- "ordinal": 5,- "name": "occurrence_start_date",- "type_info": "Date"- },- {- "ordinal": 6,- "name": "occurrence_end_date",- "type_info": "Date"- },- {- "ordinal": 7,- "name": "is_cancelled",- "type_info": "Bool"- },- {- "ordinal": 8,- "name": "owner_id",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "ical_uid",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "title",- "type_info": "Text"- },- {- "ordinal": 11,- "name": "description",- "type_info": "Text"- },- {- "ordinal": 12,- "name": "location",- "type_info": "Text"- },- {- "ordinal": 13,- "name": "status",- "type_info": "Text"- },- {- "ordinal": 14,- "name": "visibility",- "type_info": "Text"- },- {- "ordinal": 15,- "name": "transparency",- "type_info": "Text"- },- {- "ordinal": 16,- "name": "starts_at",- "type_info": "Timestamptz"- },- {- "ordinal": 17,- "name": "ends_at",- "type_info": "Timestamptz"- },- {- "ordinal": 18,- "name": "start_date",- "type_info": "Date"- },- {- "ordinal": 19,- "name": "end_date",- "type_info": "Date"- },- {- "ordinal": 20,- "name": "time_zone",- "type_info": "Text"- },- {- "ordinal": 21,- "name": "recurrence_lines",- "type_info": "TextArray"- },- {- "ordinal": 22,- "name": "organizer_email",- "type_info": "Text"- },- {- "ordinal": 23,- "name": "organizer_name",- "type_info": "Text"- },- {- "ordinal": 24,- "name": "conference_url",- "type_info": "Text"- },- {- "ordinal": 25,- "name": "sequence",- "type_info": "Int4"- },- {- "ordinal": 26,- "name": "is_read_only",- "type_info": "Bool"- },- {- "ordinal": 27,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 28,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text",- "Timestamptz",- "Timestamptz",- "Date",- "Date",- "Timestamptz",- "Uuid",- "Text",- "Int8"- ]- },- "nullable": [- false,- false,- true,- true,- true,- true,- true,- false,- false,- false,- false,- true,- true,- false,- false,- false,- true,- true,- true,- true,- true,- false,- true,- true,- true,- false,- false,- false,- false- ]- },- "hash": "d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58"-}diff --git a/apps/web/src/features/calendar/CalendarPage.tsx b/apps/web/src/features/calendar/CalendarPage.tsxindex f616941980..917f65bf09 100644--- a/apps/web/src/features/calendar/CalendarPage.tsx+++ b/apps/web/src/features/calendar/CalendarPage.tsx@@ -257,15 +257,20 @@ function createCalendarPageData(refetchOnWindowFocus: isActive(),}));- const events = createMemo(() =>- isRangeSupported()- ? (occurrencesQuery.data?.items ?? []).map(mapCalendarOccurrence)- : []- );+ const events = createMemo(() => {+ if (!isRangeSupported()) return [];+ const sourceById = calendarView.sourceById();+ return (occurrencesQuery.data?.items ?? []).map((item) =>+ mapCalendarOccurrence(+ item,+ item.event.calendarId != null+ ? sourceById.get(item.event.calendarId)+ : undefined+ )+ );+ });const visibleEvents = createMemo(() =>- events().filter((event) =>- calendarView.eventState.visibleSourceIds.includes(event.calendar.id)- )+ events().filter((event) => calendarView.isSourceVisible(event.calendar.id)));const eventsById = createMemo(() => new Map(events().map((event) => [event.id, event]))diff --git a/apps/web/src/features/calendar/CalendarViewContext.tsx b/apps/web/src/features/calendar/CalendarViewContext.tsxindex 0b39c99ded..f129b4dce9 100644--- a/apps/web/src/features/calendar/CalendarViewContext.tsx+++ b/apps/web/src/features/calendar/CalendarViewContext.tsx@@ -1,12 +1,15 @@import { createAssertedContextProvider } from '@core/context/createContext';import { isMobile } from '@core/mobile/isMobile';+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';import { makePersisted } from '@solid-primitives/storage';-import { batch, createSignal } from 'solid-js';+import { batch, createMemo, createSignal } from 'solid-js';import { createStore } from 'solid-js/store';+import { calendarDisplayLabel, spansMultipleInboxes } from './calendar-label';import { DEFAULT_CALENDAR_SOURCE } from './events/calendar-occurrence-mapper';import type {CalendarEvent,CalendarPeriodView,+ CalendarSource,CalendarTimeFormat,CalendarWeekStart,} from './events/types';@@ -33,7 +36,6 @@ interface CalendarPreferences {}const CALENDAR_PREFERENCES_KEY = 'macro:pref:calendar:settings';-const CALENDAR_SOURCES = [DEFAULT_CALENDAR_SOURCE];export const [CalendarViewContextProvider, useCalendarView] =createAssertedContextProvider('CalendarViewContext', () => {@@ -54,13 +56,34 @@ export const [CalendarViewContextProvider, useCalendarView] =}),});+ const calendarsQuery = useVisibleCalendarsQuery();+ const sources = createMemo<CalendarSource[]>(() => {+ const calendars = calendarsQuery.data;+ if (!calendars || calendars.length === 0) {+ return [DEFAULT_CALENDAR_SOURCE];+ }+ const spansInboxes = spansMultipleInboxes(calendars);+ return calendars.map((calendar) => ({+ id: calendar.id,+ name: calendarDisplayLabel(calendar, spansInboxes),+ color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,+ }));+ });+ const sourceById = createMemo(+ () => new Map(sources().map((source) => [source.id, source]))+ );+ // Sources default to visible, so calendars discovered after a+ // preference was saved (or events whose calendar is still loading)+ // never silently disappear.+ const isSourceVisible = (sourceId: string) =>+ !preferences.hiddenSourceIds.includes(sourceId);+const [selectedEventId, setSelectedEventId] = createSignal<string>();const eventState: CalendarEventState = {get visibleSourceIds() {- const hiddenSourceIds = preferences.hiddenSourceIds;- return CALENDAR_SOURCES.filter(- (source) => !hiddenSourceIds.includes(source.id)- ).map((source) => source.id);+ return sources()+ .filter((source) => isSourceVisible(source.id))+ .map((source) => source.id);},get selectedEventId() {return selectedEventId();@@ -124,9 +147,9 @@ export const [CalendarViewContextProvider, useCalendarView] =return {eventState,displaySettings,- sources: () => CALENDAR_SOURCES,- isSourceVisible: (sourceId: string) =>- eventState.visibleSourceIds.includes(sourceId),+ sources,+ sourceById,+ isSourceVisible,setSourceVisibility,selectedEvent,selectedEventAnchor,diff --git a/apps/web/src/features/calendar/calendar-label.ts b/apps/web/src/features/calendar/calendar-label.tsnew file mode 100644index 0000000000..58de9fb22d--- /dev/null+++ b/apps/web/src/features/calendar/calendar-label.ts@@ -0,0 +1,26 @@+import type { VisibleCalendar } from '@queries/calendar/calendars';++/**+ * Display label for a calendar in pickers and filters. Google names primary+ * calendars after the account email, so primaries collapse to the inbox+ * address; other calendars carry their inbox only when the visible set spans+ * more than one account.+ */+export function calendarDisplayLabel(+ calendar: Pick<VisibleCalendar, 'name' | 'emailAddress' | 'isPrimary'>,+ spansInboxes: boolean+): string {+ if (calendar.isPrimary || calendar.name === calendar.emailAddress) {+ return calendar.emailAddress;+ }+ return spansInboxes+ ? `${calendar.name} — ${calendar.emailAddress}`+ : calendar.name;+}++/** Whether a calendar list spans more than one connected inbox. */+export function spansMultipleInboxes(+ calendars: readonly Pick<VisibleCalendar, 'emailAddress'>[]+): boolean {+ return new Set(calendars.map((calendar) => calendar.emailAddress)).size > 1;+}diff --git a/apps/web/src/features/calendar/calendar-view.tsx b/apps/web/src/features/calendar/calendar-view.tsxindex ed24efe76a..08fa44acc4 100644--- a/apps/web/src/features/calendar/calendar-view.tsx+++ b/apps/web/src/features/calendar/calendar-view.tsx@@ -9,6 +9,7 @@ import { isMobile } from '@core/mobile/isMobile';import CalendarBlankIcon from '@phosphor/calendar-blank.svg';import CaretLeftIcon from '@phosphor/caret-left.svg';import CaretRightIcon from '@phosphor/caret-right.svg';+import PlusIcon from '@phosphor/plus.svg';import { createResizeObserver } from '@solid-primitives/resize-observer';import { Button, Layer } from '@ui';import { Pager, PagerSwipeGestures, usePager } from '@ui/components/Pager';@@ -39,6 +40,7 @@ import {useCalendarView,} from './CalendarViewContext';import { SelectedEventDetails } from './events/EventDetailsPopover';+import { EventEditorDialog } from './events/EventEditorDialog';import './calendar.css';const CALENDAR_SWIPE_EDGE_INSET = 40;@@ -173,6 +175,7 @@ function CalendarWorkspace() {const calendarView = useCalendarView();const initialDate = new Date();const today = createLocalToday();+ const [createEventOpen, setCreateEventOpen] = createSignal(false);const currentDate = createMemo(() => calendarPager.activeDateInfo()?.view.calendar.getDate() ?? initialDate@@ -246,6 +249,16 @@ function CalendarWorkspace() {</Button></Show><Show when={!isMobile()}>+ <Button+ variant="ghost"+ size="sm"+ class="rounded-lg px-2"+ label="New event"+ onClick={() => setCreateEventOpen(true)}+ >+ <PlusIcon class="size-3.5" />+ New event+ </Button><CalendarPeriodSelector /><div class="flex shrink-0 items-center gap-1"><Button@@ -282,6 +295,10 @@ function CalendarWorkspace() {onClose={calendarView.closeEventDetails}/>+ <Show when={createEventOpen()}>+ <EventEditorDialog open onClose={() => setCreateEventOpen(false)} />+ </Show>+<main class="calendar-view flex size-full min-h-0"><div class="calendar-view-content flex min-w-0 min-h-0 flex-1 flex-col"><CalendarPages />diff --git a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx b/apps/web/src/features/calendar/events/EventDetailsPopover.tsxindex d0274b4aa8..cbd42a287b 100644--- a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx+++ b/apps/web/src/features/calendar/events/EventDetailsPopover.tsx@@ -1,10 +1,18 @@import { MobileDrawer } from '@components/app/mobile/MobileDrawer';+import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';import { Popover } from '@kobalte/core/popover';+import PencilSimpleIcon from '@phosphor/pencil-simple.svg';+import SpinnerIcon from '@phosphor/spinner.svg';+import TrashIcon from '@phosphor/trash.svg';import CloseIcon from '@phosphor/x.svg';-import { Button, Layer } from '@ui';-import { type Accessor, createMemo, Show } from 'solid-js';+import { useDeleteCalendarEventMutation } from '@queries/calendar/mutations';+import type { CalendarDeletionScope } from '@service-email/client';+import { Button, Dialog, Layer, Panel } from '@ui';+import { type Accessor, createMemo, createSignal, Show } from 'solid-js';import { EventAttendeesSection, EventDetails } from './EventDetails';+import { EventEditorDialog } from './EventEditorDialog';+import { EventRsvpSection } from './EventRsvpSection';import type { CalendarEvent, CalendarTimeFormat } from './types';interface SelectedEventDetailsProps {@@ -14,13 +22,32 @@ interface SelectedEventDetailsProps {onClose: () => void;}-/** Renders selected event details in a mobile drawer or anchored popover. */+/**+ * Renders selected event details in a mobile drawer or anchored popover.+ *+ * Both are keyed on the stable event id — not the view model's object+ * identity — so optimistic cache writes and refetches update them in place+ * instead of remounting them (which would close their dialogs). When the+ * event leaves the cache entirely (e.g. deleted from another tab) the+ * overlay closes rather than lingering on stale data.+ */export function SelectedEventDetails(props: SelectedEventDetailsProps) {- const popoverSelection = createMemo(() => {- const event = props.event();- const anchor = props.anchor();+ const popoverSelection = createMemo(+ () => {+ const event = props.event();+ const anchor = props.anchor();- return event && anchor ? { anchor, event } : undefined;+ return event && anchor ? { anchor, eventId: event.id } : undefined;+ },+ undefined,+ {+ equals: (previous, next) =>+ previous?.anchor === next?.anchor &&+ previous?.eventId === next?.eventId,+ }+ );+ const drawerSelection = createMemo(() => props.event()?.id, undefined, {+ equals: (previous, next) => previous === next,});return (@@ -29,9 +56,27 @@ export function SelectedEventDetails(props: SelectedEventDetailsProps) {fallback={<Show keyed when={popoverSelection()}>{(selected) => (- <EventDetailsPopover- anchor={selected.anchor}- event={selected.event}+ <Show when={props.event()}>+ {(currentEvent) => (+ <EventDetailsPopover+ anchor={selected.anchor}+ event={currentEvent()}+ timeFormat={props.timeFormat()}+ onOpenChange={(open) => {+ if (!open) props.onClose();+ }}+ />+ )}+ </Show>+ )}+ </Show>+ }+ >+ <Show keyed when={drawerSelection()}>+ <Show when={props.event()}>+ {(currentEvent) => (+ <EventDetailsDrawer+ event={currentEvent()}timeFormat={props.timeFormat()}onOpenChange={(open) => {if (!open) props.onClose();@@ -39,18 +84,6 @@ export function SelectedEventDetails(props: SelectedEventDetailsProps) {/>)}</Show>- }- >- <Show keyed when={props.event()}>- {(event) => (- <EventDetailsDrawer- event={event}- timeFormat={props.timeFormat()}- onOpenChange={(open) => {- if (!open) props.onClose();- }}- />- )}</Show></Show>);@@ -82,6 +115,7 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {<div class="px-3 pb-3"><EventDetails event={props.event} timeFormat={props.timeFormat} /></div>+ <EventRsvpSection event={props.event} /><EventAttendeesSection attendees={props.event.attendees} /></div><MobileDrawer.Close@@ -103,64 +137,241 @@ interface EventDetailsPopoverProps extends EventDetailsOverlayProps {anchor: HTMLElement;}-/** Anchors read-only event details to a rendered calendar event. */-function EventDetailsPopover(props: EventDetailsPopoverProps) {+function DeleteEventDialog(props: {+ open: boolean;+ event: CalendarEvent;+ onClose: () => void;+ onDeleted: () => void;+}) {+ const isRecurring = () =>+ props.event.recurrenceLines.length > 0 ||+ props.event.recurrenceId !== undefined;+ const [scope, setScope] = createSignal<CalendarDeletionScope>('this_event');+ const deleteEvent = useDeleteCalendarEventMutation({+ onSuccess: () => props.onDeleted(),+ onError: (error) => {+ toast.failure('Failed to delete event', { subtext: error.message });+ },+ });+ const confirm = () => {+ const effectiveScope = isRecurring() ? scope() : 'all';+ deleteEvent.mutate({+ eventId: props.event.eventId,+ scope: effectiveScope,+ recurrenceId:+ effectiveScope === 'all'+ ? undefined+ : (props.event.recurrenceId ?? props.event.occurrenceKey),+ occurrenceKey:+ effectiveScope === 'all' ? undefined : props.event.occurrenceKey,+ });+ };+return (- <Popover- anchorRef={() => props.anchor}- open- onOpenChange={props.onOpenChange}- placement="right-start"- gutter={8}- flip- slide+ <Dialog+ open={props.open}+ onOpenChange={(open) =>+ !open && !deleteEvent.isPending && props.onClose()+ }>- <Popover.Portal>- <Layer depth={3}>- <Popover.Content- class="z-modal max-w-[calc(100vw-2rem)] outline-none"- onInteractOutside={(event) => {- // FullCalendar selects on click (pointer release), so dismissing on- // pointer down would briefly close the popover before reopening it.- const target = event.detail.originalEvent.target;- if (- target instanceof Element &&- target.closest('.fc-event') !== null- ) {- event.preventDefault();- }- }}- onCloseAutoFocus={(event) => {- const shouldRestoreFocus = !event.defaultPrevented;- event.preventDefault();- if (shouldRestoreFocus && props.anchor.isConnected) {- props.anchor.focus();- }- }}+ <Panel depth={2} class="max-w-[calc(100vw-2rem)] rounded-xl text-ink">+ <Panel.Header class="gap-1 px-2">+ <Dialog.CloseButton+ as={Button}+ variant="ghost"+ size="icon-sm"+ disabled={deleteEvent.isPending}+ >+ <CloseIcon />+ </Dialog.CloseButton>+ <Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">+ Delete event+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="flex flex-col gap-3 p-3">+ <Show+ when={isRecurring()}+ fallback={+ <p class="max-w-80 text-sm text-ink-muted">+ Delete “{props.event.title || 'Untitled event'}”? Guests will be+ notified.+ </p>+ }>- <Popover.Arrow class="fill-surface" />- <div class="relative w-fit min-w-[min(20rem,calc(100vw-2rem))] max-w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted">- <Popover.Title class="sr-only">{props.event.title}</Popover.Title>- <div class="p-3">- <EventDetails- event={props.event}- timeFormat={props.timeFormat}+ <div class="flex max-w-80 flex-col gap-2 text-sm text-ink-muted">+ <p>+ Remove “{props.event.title || 'Untitled event'}”? Guests will be+ notified.+ </p>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="delete-scope"+ checked={scope() === 'this_event'}+ onChange={() => setScope('this_event')}/>- </div>- <EventAttendeesSection attendees={props.event.attendees} />- <Popover.CloseButton- as={Button}- aria-label="Close event details"- variant="ghost"- size="icon-sm"- class="absolute right-2 top-2 rounded-md text-ink-muted"- >- <CloseIcon class="size-3" />- </Popover.CloseButton>+ This event+ </label>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="delete-scope"+ checked={scope() === 'this_and_following'}+ onChange={() => setScope('this_and_following')}+ />+ This and following events+ </label>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="delete-scope"+ checked={scope() === 'all'}+ onChange={() => setScope('all')}+ />+ All events+ </label></div>- </Popover.Content>- </Layer>- </Popover.Portal>- </Popover>+ </Show>+ <div class="flex justify-end gap-1 pt-2">+ <Button+ variant="ghost"+ class="rounded-lg"+ disabled={deleteEvent.isPending}+ label="Cancel"+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ variant="active"+ class="rounded-lg"+ disabled={deleteEvent.isPending}+ label="Delete"+ onClick={confirm}+ >+ <Show when={deleteEvent.isPending} fallback="Delete">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}++/** Anchors event details and actions to a rendered calendar event. */+function EventDetailsPopover(props: EventDetailsPopoverProps) {+ const [deleteOpen, setDeleteOpen] = createSignal(false);+ const [editorOpen, setEditorOpen] = createSignal(false);+ const canModify = () => !props.event.isReadOnly && !props.event.isCancelled;++ return (+ <>+ <Popover+ anchorRef={() => props.anchor}+ open+ onOpenChange={(open) => {+ // Keep the popover mounted while one of its dialogs is up; the+ // dialog's own close path decides what happens next.+ if (!open && (deleteOpen() || editorOpen())) return;+ props.onOpenChange(open);+ }}+ placement="right-start"+ gutter={8}+ flip+ slide+ >+ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content+ class="z-modal max-w-[calc(100vw-2rem)] outline-none"+ onInteractOutside={(event) => {+ // FullCalendar selects on click (pointer release), so dismissing on+ // pointer down would briefly close the popover before reopening it.+ const target = event.detail.originalEvent.target;+ if (+ target instanceof Element &&+ target.closest('.fc-event') !== null+ ) {+ event.preventDefault();+ }+ }}+ onCloseAutoFocus={(event) => {+ const shouldRestoreFocus = !event.defaultPrevented;+ event.preventDefault();+ if (shouldRestoreFocus && props.anchor.isConnected) {+ props.anchor.focus();+ }+ }}+ >+ <Popover.Arrow class="fill-surface" />+ <div class="relative w-fit min-w-[min(20rem,calc(100vw-2rem))] max-w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted">+ <Popover.Title class="sr-only">+ {props.event.title}+ </Popover.Title>+ <div class="p-3">+ <EventDetails+ event={props.event}+ timeFormat={props.timeFormat}+ />+ </div>+ <EventRsvpSection event={props.event} />+ <EventAttendeesSection attendees={props.event.attendees} />+ <div class="absolute right-2 top-2 flex items-center gap-0.5">+ <Show when={canModify()}>+ <Button+ aria-label="Edit event"+ variant="ghost"+ size="icon-sm"+ class="rounded-md text-ink-muted"+ onClick={() => setEditorOpen(true)}+ >+ <PencilSimpleIcon class="size-3" />+ </Button>+ <Button+ aria-label="Delete event"+ variant="ghost"+ size="icon-sm"+ class="rounded-md text-ink-muted"+ onClick={() => setDeleteOpen(true)}+ >+ <TrashIcon class="size-3" />+ </Button>+ </Show>+ <Popover.CloseButton+ as={Button}+ aria-label="Close event details"+ variant="ghost"+ size="icon-sm"+ class="rounded-md text-ink-muted"+ >+ <CloseIcon class="size-3" />+ </Popover.CloseButton>+ </div>+ </div>+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ <Show when={deleteOpen()}>+ <DeleteEventDialog+ open+ event={props.event}+ onClose={() => setDeleteOpen(false)}+ onDeleted={() => {+ setDeleteOpen(false);+ props.onOpenChange(false);+ }}+ />+ </Show>+ <Show when={editorOpen()}>+ <EventEditorDialog+ open+ event={props.event}+ onClose={() => setEditorOpen(false)}+ />+ </Show>+ </>);}diff --git a/apps/web/src/features/calendar/events/EventEditorDialog.tsx b/apps/web/src/features/calendar/events/EventEditorDialog.tsxnew file mode 100644index 0000000000..d0eb761e94--- /dev/null+++ b/apps/web/src/features/calendar/events/EventEditorDialog.tsx@@ -0,0 +1,630 @@+import { toast } from '@core/component/Toast/Toast';+import SpinnerIcon from '@phosphor/spinner.svg';+import XIcon from '@phosphor/x.svg';+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';+import {+ useCreateCalendarEventMutation,+ useUpdateCalendarEventMutation,+} from '@queries/calendar/mutations';+import type { EventTime } from '@service-email/generated/schemas/eventTime';+import { Button, Dialog, Panel, ToggleSwitch } from '@ui';+import {+ addDays,+ addHours,+ addMonths,+ format,+ isMatch,+ parseISO,+ startOfHour,+} from 'date-fns';+import { createMemo, createSignal, For, Show } from 'solid-js';+import { calendarDisplayLabel, spansMultipleInboxes } from '../calendar-label';+import { formatRecurrenceDescription } from './recurrence-description';+import {+ buildRecurrenceLines,+ defaultCustomConfig,+ parseRecurrenceConfig,+ type RecurrenceConfig,+ recurrenceConfigsEqual,+ recurrencePresetsFor,+ WEEKDAY_CODES,+ type WeekdayCode,+} from './recurrence-editor';+import type { CalendarEvent } from './types';++/** `<input type="date">` value. */+const DATE_VALUE = 'yyyy-MM-dd';+/** `<input type="datetime-local">` value. */+const DATETIME_VALUE = "yyyy-MM-dd'T'HH:mm";++const isDateOnly = (value: string) => isMatch(value, DATE_VALUE);++function shiftDateValue(value: string, days: number) {+ return format(addDays(parseISO(value), days), DATE_VALUE);+}++/** Default editor slot: the next full hour, one hour long. */+function defaultEditorTimes(reference: Date) {+ const start = addHours(startOfHour(reference), 1);+ return { start, end: addHours(start, 1) };+}++interface EditorState {+ title: string;+ allDay: boolean;+ /** `datetime-local` value, or `date` value in all-day mode. */+ start: string;+ /** Inclusive end shown to the user; all-day submissions add the exclusive day. */+ end: string;+ location: string;+ description: string;+ guests: string;+}++function initialEditorState(event: CalendarEvent | undefined): EditorState {+ if (!event) {+ const { start, end } = defaultEditorTimes(new Date());+ return {+ title: '',+ allDay: false,+ start: format(start, DATETIME_VALUE),+ end: format(end, DATETIME_VALUE),+ location: '',+ description: '',+ guests: '',+ };+ }+ if (event.allDay) {+ const start = isDateOnly(event.start)+ ? event.start+ : format(new Date(event.start), DATE_VALUE);+ const exclusiveEnd = isDateOnly(event.end)+ ? event.end+ : format(new Date(event.end), DATE_VALUE);+ return {+ title: event.title,+ allDay: true,+ start,+ end: shiftDateValue(exclusiveEnd, -1),+ location: event.location ?? '',+ description: event.description ?? '',+ guests: '',+ };+ }+ return {+ title: event.title,+ allDay: false,+ start: format(new Date(event.start), DATETIME_VALUE),+ end: format(new Date(event.end), DATETIME_VALUE),+ location: event.location ?? '',+ description: event.description ?? '',+ guests: '',+ };+}++function buildEventTime(state: EditorState): EventTime | undefined {+ if (state.allDay) {+ if (!state.start || !state.end || state.end < state.start) {+ return undefined;+ }+ return {+ kind: 'allDay',+ startDate: state.start,+ endDate: shiftDateValue(state.end, 1),+ };+ }+ const start = new Date(state.start);+ const end = new Date(state.end);+ if (+ Number.isNaN(start.getTime()) ||+ Number.isNaN(end.getTime()) ||+ end <= start+ ) {+ return undefined;+ }+ return {+ kind: 'timed',+ startsAt: start.toISOString(),+ endsAt: end.toISOString(),+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ };+}++function parseGuestEmails(value: string) {+ return [...new Set(value.split(/[\s,;]+/).filter((email) => email !== ''))];+}++/** Both editor times switch representation when all-day toggles. */+function convertTimesForAllDay(state: EditorState, allDay: boolean) {+ if (allDay === state.allDay) return state;+ if (allDay) {+ return {+ ...state,+ allDay,+ start: state.start.slice(0, 10),+ end: state.end.slice(0, 10),+ };+ }+ const { start, end } = defaultEditorTimes(parseISO(state.start));+ return {+ ...state,+ allDay,+ start: format(start, DATETIME_VALUE),+ end: format(end, DATETIME_VALUE),+ };+}++/**+ * Create/edit form for a calendar event. Editing a recurring event changes+ * the entire series; guests can only be invited at creation, because a+ * patch replaces the whole attendee list and would reset RSVPs.+ */+export function EventEditorDialog(props: {+ open: boolean;+ /** Present when editing; absent when creating. */+ event?: CalendarEvent;+ onClose: () => void;+}) {+ const [state, setState] = createSignal(initialEditorState(props.event));+ const isEdit = () => props.event !== undefined;+ const [calendarId, setCalendarId] = createSignal<string>();+ const calendarsQuery = useVisibleCalendarsQuery(() => ({+ enabled: !isEdit(),+ }));+ const writableCalendars = createMemo(+ () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []+ );+ // The select displays the first writable calendar until touched, so submit+ // must resolve the same fallback rather than let the server pick its own.+ const effectiveCalendarId = () => calendarId() ?? writableCalendars()[0]?.id;+ const spansInboxes = createMemo(() =>+ spansMultipleInboxes(writableCalendars())+ );+ const calendarLabel = (calendar: {+ name: string;+ emailAddress: string;+ isPrimary: boolean;+ }) => calendarDisplayLabel(calendar, spansInboxes());++ const initialLines = props.event?.recurrenceLines ?? [];+ const initialConfig =+ initialLines.length > 0 ? parseRecurrenceConfig(initialLines) : undefined;+ const hasUnrepresentableRule = initialLines.length > 0 && !initialConfig;+ const startForRecurrence = createMemo(() => {+ const start = state().start;+ const parsed = state().allDay ? parseISO(start) : new Date(start);+ return Number.isNaN(parsed.getTime()) ? new Date() : parsed;+ });+ const presets = createMemo(() => recurrencePresetsFor(startForRecurrence()));+ const initialChoice = () => {+ if (initialLines.length === 0) return 'none';+ if (!initialConfig) return 'existing';+ const preset = recurrencePresetsFor(+ props.event?.allDay+ ? parseISO(props.event.start)+ : new Date(props.event?.start ?? Date.now())+ ).find((candidate) =>+ recurrenceConfigsEqual(candidate.config, initialConfig)+ );+ return preset?.id ?? 'custom';+ };+ const [recurrenceChoice, setRecurrenceChoice] = createSignal(initialChoice());+ const [customConfig, setCustomConfig] = createSignal<RecurrenceConfig>(+ initialConfig ?? defaultCustomConfig(startForRecurrence())+ );+ const customValid = createMemo(() => {+ if (recurrenceChoice() !== 'custom') return true;+ const config = customConfig();+ if (!Number.isInteger(config.interval) || config.interval < 1) {+ return false;+ }+ if (config.frequency === 'WEEKLY' && config.byDay.length === 0) {+ return false;+ }+ if (config.ends.kind === 'on') return config.ends.date !== '';+ if (config.ends.kind === 'after') {+ return Number.isInteger(config.ends.count) && config.ends.count >= 1;+ }+ return true;+ });+ /** `undefined` leaves the stored rule untouched. */+ const recurrenceLines = (): string[] | undefined => {+ const choice = recurrenceChoice();+ if (choice === 'existing') return undefined;+ if (choice === 'none') return [];+ if (choice === 'custom') {+ return buildRecurrenceLines(customConfig(), state().allDay);+ }+ const preset = presets().find((candidate) => candidate.id === choice);+ return preset+ ? buildRecurrenceLines(preset.config, state().allDay)+ : undefined;+ };+ const toggleWeekday = (code: WeekdayCode) => {+ setCustomConfig((config) => ({+ ...config,+ byDay: config.byDay.includes(code)+ ? config.byDay.filter((day) => day !== code)+ : [...config.byDay, code],+ }));+ };+ const setEnds = (ends: RecurrenceConfig['ends']) =>+ setCustomConfig((config) => ({ ...config, ends }));+ const isRecurring = () =>+ (props.event?.recurrenceLines.length ?? 0) > 0 ||+ props.event?.recurrenceId !== undefined;++ const invalidGuests = createMemo(() =>+ parseGuestEmails(state().guests).filter((email) => !email.includes('@'))+ );+ const eventTime = createMemo(() => buildEventTime(state()));+ const canSave = () =>+ eventTime() !== undefined && invalidGuests().length === 0 && customValid();++ const create = useCreateCalendarEventMutation({+ onSuccess: () => props.onClose(),+ onError: (error) => {+ toast.failure('Failed to create event', { subtext: error.message });+ },+ });+ const update = useUpdateCalendarEventMutation({+ onSuccess: () => props.onClose(),+ onError: (error) => {+ toast.failure('Failed to update event', { subtext: error.message });+ },+ });+ const pending = () => create.isPending || update.isPending;++ const save = () => {+ const time = eventTime();+ if (!time || pending()) return;++ const current = state();+ const event = props.event;+ const lines = recurrenceLines();+ if (event) {+ const recurrenceChanged =+ lines !== undefined && lines.join('\n') !== initialLines.join('\n');+ update.mutate({+ eventId: event.eventId,+ patch: {+ title: current.title,+ time,+ location: current.location,+ description: current.description,+ ...(recurrenceChanged ? { recurrenceLines: lines } : {}),+ },+ });+ return;+ }+ create.mutate({+ title: current.title,+ time,+ calendarId: effectiveCalendarId(),+ recurrenceLines: lines ?? [],+ location: current.location === '' ? undefined : current.location,+ description: current.description === '' ? undefined : current.description,+ attendees: parseGuestEmails(current.guests).map((email) => ({ email })),+ });+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => !open && !pending() && props.onClose()}+ >+ <Panel+ depth={2}+ class="w-[26rem] max-w-[calc(100vw-2rem)] rounded-xl text-ink"+ >+ <Panel.Header class="gap-1 px-2">+ <Dialog.CloseButton+ as={Button}+ variant="ghost"+ size="icon-sm"+ disabled={pending()}+ >+ <XIcon />+ </Dialog.CloseButton>+ <Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">+ {isEdit() ? 'Edit event' : 'New event'}+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="flex flex-col gap-3 p-3">+ <input+ type="text"+ value={state().title}+ onInput={(e) =>+ setState({ ...state(), title: e.currentTarget.value })+ }+ placeholder="Add title"+ class="settings-input w-full"+ />+ <div class="flex items-center justify-between gap-2 text-xs text-ink-muted">+ <ToggleSwitch+ label="All day"+ checked={state().allDay}+ onChange={(allDay) =>+ setState(convertTimesForAllDay(state(), allDay))+ }+ />+ <Show when={isRecurring()}>+ <span class="text-ink-extra-muted">+ Changes apply to all occurrences+ </span>+ </Show>+ </div>+ <div class="flex items-center gap-2">+ <input+ type={state().allDay ? 'date' : 'datetime-local'}+ value={state().start}+ onInput={(e) =>+ setState({ ...state(), start: e.currentTarget.value })+ }+ aria-label="Start"+ class="settings-input min-w-0 flex-1"+ />+ <span class="shrink-0 text-xs text-ink-extra-muted">to</span>+ <input+ type={state().allDay ? 'date' : 'datetime-local'}+ value={state().end}+ onInput={(e) =>+ setState({ ...state(), end: e.currentTarget.value })+ }+ aria-label="End"+ class="settings-input min-w-0 flex-1"+ />+ </div>+ <div class="flex flex-col gap-2">+ <select+ value={recurrenceChoice()}+ onChange={(e) => {+ const choice = e.currentTarget.value;+ if (choice === 'custom') {+ const seed =+ presets().find((preset) => preset.id === recurrenceChoice())+ ?.config ??+ initialConfig ??+ defaultCustomConfig(startForRecurrence());+ setCustomConfig(seed);+ }+ setRecurrenceChoice(choice);+ }}+ aria-label="Repeats"+ class="settings-input w-full"+ >+ <option value="none">Does not repeat</option>+ <For each={presets()}>+ {(preset) => <option value={preset.id}>{preset.label}</option>}+ </For>+ <Show when={hasUnrepresentableRule}>+ <option value="existing">+ {`Custom: ${+ formatRecurrenceDescription(initialLines) ?? 'existing rule'+ } (unchanged)`}+ </option>+ </Show>+ <option value="custom">Custom…</option>+ </select>+ <Show when={recurrenceChoice() === 'custom'}>+ <div class="border-edge-muted flex flex-col gap-2.5 rounded-lg border p-2.5 text-xs text-ink-muted">+ <div class="flex items-center gap-2">+ <span>Repeat every</span>+ <input+ type="number"+ min="1"+ value={customConfig().interval}+ onInput={(e) =>+ setCustomConfig((config) => ({+ ...config,+ interval: e.currentTarget.valueAsNumber,+ }))+ }+ aria-label="Repeat interval"+ class="settings-input w-16"+ />+ <select+ value={customConfig().frequency}+ onChange={(e) =>+ setCustomConfig((config) => ({+ ...config,+ frequency: e.currentTarget+ .value as RecurrenceConfig['frequency'],+ }))+ }+ aria-label="Repeat unit"+ class="settings-input"+ >+ <option value="DAILY">day</option>+ <option value="WEEKLY">week</option>+ <option value="MONTHLY">month</option>+ <option value="YEARLY">year</option>+ </select>+ </div>+ <Show when={customConfig().frequency === 'WEEKLY'}>+ <div class="flex items-center gap-1.5">+ <span class="mr-1">Repeat on</span>+ <For each={WEEKDAY_CODES}>+ {(code) => (+ <Button+ variant={+ customConfig().byDay.includes(code)+ ? 'active'+ : 'ghost'+ }+ size="icon-sm"+ class="rounded-full text-xxs"+ aria-label={code}+ aria-pressed={customConfig().byDay.includes(code)}+ onClick={() => toggleWeekday(code)}+ >+ {code[0]}+ </Button>+ )}+ </For>+ </div>+ </Show>+ <div class="flex flex-col gap-1.5">+ <span>Ends</span>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="recurrence-ends"+ checked={customConfig().ends.kind === 'never'}+ onChange={() => setEnds({ kind: 'never' })}+ />+ Never+ </label>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="recurrence-ends"+ checked={customConfig().ends.kind === 'on'}+ onChange={() =>+ setEnds({+ kind: 'on',+ date: format(+ addMonths(startForRecurrence(), 3),+ 'yyyy-MM-dd'+ ),+ })+ }+ />+ On+ <Show when={customConfig().ends.kind === 'on'}>+ <input+ type="date"+ value={+ customConfig().ends.kind === 'on'+ ? (+ customConfig().ends as {+ kind: 'on';+ date: string;+ }+ ).date+ : ''+ }+ onInput={(e) =>+ setEnds({ kind: 'on', date: e.currentTarget.value })+ }+ aria-label="Ends on date"+ class="settings-input"+ />+ </Show>+ </label>+ <label class="flex items-center gap-2">+ <input+ type="radio"+ name="recurrence-ends"+ checked={customConfig().ends.kind === 'after'}+ onChange={() => setEnds({ kind: 'after', count: 13 })}+ />+ After+ <Show when={customConfig().ends.kind === 'after'}>+ <input+ type="number"+ min="1"+ value={+ customConfig().ends.kind === 'after'+ ? (+ customConfig().ends as {+ kind: 'after';+ count: number;+ }+ ).count+ : 13+ }+ onInput={(e) =>+ setEnds({+ kind: 'after',+ count: e.currentTarget.valueAsNumber,+ })+ }+ aria-label="Ends after occurrences"+ class="settings-input w-20"+ />+ occurrences+ </Show>+ </label>+ </div>+ </div>+ </Show>+ </div>+ <Show when={!isEdit() && writableCalendars().length > 1}>+ <select+ value={effectiveCalendarId()}+ onChange={(e) => setCalendarId(e.currentTarget.value)}+ aria-label="Calendar"+ class="settings-input w-full"+ >+ <For each={writableCalendars()}>+ {(calendar) => (+ <option value={calendar.id}>{calendarLabel(calendar)}</option>+ )}+ </For>+ </select>+ </Show>+ <Show when={!isEdit()}>+ <div class="flex flex-col gap-1">+ <input+ type="text"+ value={state().guests}+ onInput={(e) =>+ setState({ ...state(), guests: e.currentTarget.value })+ }+ placeholder="Add guests (comma-separated emails)"+ class="settings-input w-full"+ aria-invalid={invalidGuests().length > 0}+ />+ <Show when={invalidGuests().length > 0}>+ <span class="text-xs text-failure">+ Invalid email: {invalidGuests().join(', ')}+ </span>+ </Show>+ </div>+ </Show>+ <input+ type="text"+ value={state().location}+ onInput={(e) =>+ setState({ ...state(), location: e.currentTarget.value })+ }+ placeholder="Add location"+ class="settings-input w-full"+ />+ <textarea+ value={state().description}+ onInput={(e) =>+ setState({ ...state(), description: e.currentTarget.value })+ }+ placeholder="Add description"+ rows={3}+ class="settings-input min-h-20 w-full resize-y py-2"+ />+ <div class="flex justify-end gap-1 pt-1">+ <Button+ variant="ghost"+ class="rounded-lg"+ disabled={pending()}+ label="Cancel"+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ variant="cta"+ class="rounded-lg"+ disabled={!canSave() || pending()}+ label="Save"+ onClick={save}+ >+ <Show when={pending()} fallback="Save">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/calendar/events/EventRsvpSection.tsx b/apps/web/src/features/calendar/events/EventRsvpSection.tsxnew file mode 100644index 0000000000..aeeef9ac6c--- /dev/null+++ b/apps/web/src/features/calendar/events/EventRsvpSection.tsx@@ -0,0 +1,68 @@+import { toast } from '@core/component/Toast/Toast';+import { useRsvpCalendarEventMutation } from '@queries/calendar/mutations';+import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';+import { Button } from '@ui';+import { createMemo, For, Show } from 'solid-js';+import type { CalendarEvent } from './types';++const RSVP_OPTIONS = [+ { response: 'accepted', label: 'Yes' },+ { response: 'tentative', label: 'Maybe' },+ { response: 'declined', label: 'No' },+] as const satisfies readonly {+ response: Exclude<AttendeeResponseStatus, 'needs_action'>;+ label: string;+}[];++/**+ * RSVP controls for the connected account's own attendance. Recurring+ * events respond for the entire series, matching the backend semantics.+ */+export function EventRsvpSection(props: { event: CalendarEvent }) {+ const selfAttendee = createMemo(() =>+ props.event.attendees.find((attendee) => attendee.isSelf)+ );+ const canRespond = () =>+ selfAttendee() !== undefined &&+ !props.event.isReadOnly &&+ !props.event.isCancelled;++ const rsvp = useRsvpCalendarEventMutation({+ onError: (error) => {+ toast.failure('Failed to update RSVP', { subtext: error.message });+ },+ });++ return (+ <Show when={canRespond()}>+ <div class="border-edge-muted flex items-center gap-3 border-t px-4 py-2.5 text-xs text-ink-muted">+ <span>Going?</span>+ <div class="ml-auto flex shrink-0 gap-1">+ <For each={RSVP_OPTIONS}>+ {(option) => (+ <Button+ variant={+ selfAttendee()?.responseStatus === option.response+ ? 'active'+ : 'ghost'+ }+ size="sm"+ class="rounded-lg px-2.5"+ disabled={rsvp.isPending}+ label={option.label}+ onClick={() =>+ rsvp.mutate({+ eventId: props.event.eventId,+ response: option.response,+ })+ }+ >+ {option.label}+ </Button>+ )}+ </For>+ </div>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts b/apps/web/src/features/calendar/events/calendar-occurrence-mapper.tsindex d36d67777b..f252959369 100644--- a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts+++ b/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts@@ -10,7 +10,8 @@ export const DEFAULT_CALENDAR_SOURCE: CalendarSource = {/** Maps one backend occurrence projection into the calendar view model. */export function mapCalendarOccurrence(- item: CalendarOccurrenceItem+ item: CalendarOccurrenceItem,+ source: CalendarSource = DEFAULT_CALENDAR_SOURCE): CalendarEvent {const { event, occurrence } = item;const time = occurrence.time;@@ -34,7 +35,7 @@ export function mapCalendarOccurrence(attendees: event.attendees ?? [],timeZone: time.kind === 'timed' ? (time.timeZone ?? undefined) : undefined,title: event.title,- calendar: DEFAULT_CALENDAR_SOURCE,+ calendar: source,location: event.location ?? undefined,description: event.description ?? undefined,};diff --git a/apps/web/src/features/calendar/events/recurrence-editor.test.ts b/apps/web/src/features/calendar/events/recurrence-editor.test.tsnew file mode 100644index 0000000000..6bd57b7e7f--- /dev/null+++ b/apps/web/src/features/calendar/events/recurrence-editor.test.ts@@ -0,0 +1,179 @@+import { format } from 'date-fns';+import { describe, expect, it } from 'vitest';+import {+ buildRecurrenceLines,+ defaultCustomConfig,+ monthlyOrdinalFor,+ parseRecurrenceConfig,+ type RecurrenceConfig,+ recurrenceConfigsEqual,+ recurrencePresetsFor,+} from './recurrence-editor';++// Friday, August 7 2026 (local).+const friday = new Date(2026, 7, 7, 14, 0, 0);++// Timed rules end at local end-of-day rendered in UTC, so the expected+// UNTIL depends on the zone the tests run in.+const timedUntil = (date: string) =>+ `${new Date(`${date}T23:59:59`)+ .toISOString()+ .slice(0, 19)+ .replaceAll(/[-:]/g, '')}Z`;++describe('buildRecurrenceLines', () => {+ it('serializes the shapes the custom editor produces', () => {+ expect(+ buildRecurrenceLines(+ { frequency: 'DAILY', interval: 1, byDay: [], ends: { kind: 'never' } },+ false+ )+ ).toEqual(['RRULE:FREQ=DAILY']);+ expect(+ buildRecurrenceLines(+ {+ frequency: 'WEEKLY',+ interval: 2,+ byDay: ['FR', 'MO'],+ ends: { kind: 'after', count: 13 },+ },+ false+ )+ ).toEqual(['RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,FR;COUNT=13']);+ expect(+ buildRecurrenceLines(+ {+ frequency: 'MONTHLY',+ interval: 1,+ byDay: [],+ monthlyByDay: { ordinal: 1, weekday: 'FR' },+ ends: { kind: 'on', date: '2026-11-06' },+ },+ false+ )+ ).toEqual([+ `RRULE:FREQ=MONTHLY;BYDAY=1FR;UNTIL=${timedUntil('2026-11-06')}`,+ ]);+ });++ it('uses a date-valued UNTIL for all-day events', () => {+ expect(+ buildRecurrenceLines(+ {+ frequency: 'DAILY',+ interval: 1,+ byDay: [],+ ends: { kind: 'on', date: '2026-11-06' },+ },+ true+ )+ ).toEqual(['RRULE:FREQ=DAILY;UNTIL=20261106']);+ });+});++describe('parseRecurrenceConfig', () => {+ it('round-trips everything the editor can build', () => {+ const configs: RecurrenceConfig[] = [+ { frequency: 'DAILY', interval: 3, byDay: [], ends: { kind: 'never' } },+ {+ frequency: 'WEEKLY',+ interval: 1,+ byDay: ['MO', 'WE', 'FR'],+ ends: { kind: 'after', count: 5 },+ },+ {+ frequency: 'MONTHLY',+ interval: 2,+ byDay: [],+ monthlyByDay: { ordinal: -1, weekday: 'SU' },+ ends: { kind: 'on', date: '2027-01-31' },+ },+ { frequency: 'YEARLY', interval: 1, byDay: [], ends: { kind: 'never' } },+ ];+ for (const config of configs) {+ const parsed = parseRecurrenceConfig(buildRecurrenceLines(config, false));+ expect(parsed).toBeDefined();+ expect(recurrenceConfigsEqual(parsed as RecurrenceConfig, config)).toBe(+ true+ );+ }+ });++ it('parses UNTIL values Google emits as the local end date', () => {+ const parsed = parseRecurrenceConfig([+ 'RRULE:FREQ=WEEKLY;UNTIL=20261106T045959Z;BYDAY=FR',+ ]);+ // 2026-11-06T04:59:59Z is 23:59:59 the previous evening in US Eastern;+ // the config surfaces whatever calendar date that instant falls on here.+ const localDate = format(+ new Date(Date.UTC(2026, 10, 6, 4, 59, 59)),+ 'yyyy-MM-dd'+ );+ expect(parsed?.ends).toEqual({ kind: 'on', date: localDate });+ });++ it('declines rules it cannot round-trip', () => {+ expect(parseRecurrenceConfig([])).toBeUndefined();+ expect(+ parseRecurrenceConfig(['RRULE:FREQ=MONTHLY;BYMONTHDAY=15'])+ ).toBeUndefined();+ expect(+ parseRecurrenceConfig([+ 'RRULE:FREQ=DAILY',+ 'EXDATE;TZID=UTC:20260810T140000',+ ])+ ).toBeUndefined();+ expect(parseRecurrenceConfig(['RRULE:FREQ=HOURLY'])).toBeUndefined();+ expect(+ parseRecurrenceConfig(['RRULE:FREQ=WEEKLY;BYDAY=2FR'])+ ).toBeUndefined();+ });+});++describe('recurrencePresetsFor', () => {+ it('phrases presets from the start date like Google', () => {+ const labels = recurrencePresetsFor(friday).map((preset) => preset.label);+ expect(labels).toEqual([+ 'Daily',+ 'Weekly on Friday',+ 'Monthly on the first Friday',+ 'Annually on August 7',+ 'Every weekday (Monday to Friday)',+ ]);+ });++ it('uses "last" for a fifth weekday of the month', () => {+ // Friday, July 31 2026 is the fifth Friday.+ expect(monthlyOrdinalFor(new Date(2026, 6, 31))).toEqual({+ ordinal: -1,+ weekday: 'FR',+ });+ const monthly = recurrencePresetsFor(new Date(2026, 6, 31)).find(+ (preset) => preset.id === 'monthly'+ );+ expect(monthly?.label).toBe('Monthly on the last Friday');+ });++ it('matches parsed configs back to presets', () => {+ for (const preset of recurrencePresetsFor(friday)) {+ const parsed = parseRecurrenceConfig(+ buildRecurrenceLines(preset.config, false)+ );+ expect(parsed).toBeDefined();+ expect(+ recurrenceConfigsEqual(parsed as RecurrenceConfig, preset.config)+ ).toBe(true);+ }+ });+});++describe('defaultCustomConfig', () => {+ it('starts weekly on the event weekday', () => {+ expect(defaultCustomConfig(friday)).toEqual({+ frequency: 'WEEKLY',+ interval: 1,+ byDay: ['FR'],+ ends: { kind: 'never' },+ });+ });+});diff --git a/apps/web/src/features/calendar/events/recurrence-editor.ts b/apps/web/src/features/calendar/events/recurrence-editor.tsnew file mode 100644index 0000000000..0a2457292c--- /dev/null+++ b/apps/web/src/features/calendar/events/recurrence-editor.ts@@ -0,0 +1,263 @@+import { format } from 'date-fns';+import { parseRecurrenceLines } from './recurrence-description';++/** Weekday codes in RFC 5545 order for a Sunday-first chip row. */+export const WEEKDAY_CODES = [+ 'SU',+ 'MO',+ 'TU',+ 'WE',+ 'TH',+ 'FR',+ 'SA',+] as const;++export type WeekdayCode = (typeof WEEKDAY_CODES)[number];++const WORKWEEK: readonly WeekdayCode[] = ['MO', 'TU', 'WE', 'TH', 'FR'];++export type RecurrenceFrequency = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY';++/** How a recurrence ends. */+export type RecurrenceEnds =+ | { kind: 'never' }+ | { kind: 'on'; date: string }+ | { kind: 'after'; count: number };++/** The recurrence shapes the editor can express and round-trip. */+export interface RecurrenceConfig {+ frequency: RecurrenceFrequency;+ /** Every N frequency units; 1 is omitted from the rule. */+ interval: number;+ /** Weekly-only weekday selectors. */+ byDay: WeekdayCode[];+ /** Monthly-only positional weekday, e.g. first Friday = `{ 1, FR }`. */+ monthlyByDay?: { ordinal: number; weekday: WeekdayCode };+ ends: RecurrenceEnds;+}++const NEVER: RecurrenceEnds = { kind: 'never' };++/**+ * RFC 5545 `UNTIL` closing an inclusive local end date, Google-style:+ * all-day rules carry the plain date, timed rules the local end-of-day+ * instant rendered in UTC.+ */+function untilValue(date: string, allDay: boolean) {+ if (allDay) return date.replaceAll('-', '');+ const endOfDay = new Date(`${date}T23:59:59`);+ return `${endOfDay.toISOString().slice(0, 19).replaceAll(/[-:]/g, '')}Z`;+}++/** The local calendar date a stored `UNTIL` value ends on (inclusive). */+function untilDate(value: string): string | undefined {+ const match = value.match(+ /^(\d{4})-?(\d{2})-?(\d{2})(?:T(\d{2}):?(\d{2}):?(\d{2})Z)?$/+ );+ if (!match) return undefined;+ if (match[4] === undefined) return `${match[1]}-${match[2]}-${match[3]}`;+ const instant = new Date(+ Date.UTC(+ Number(match[1]),+ Number(match[2]) - 1,+ Number(match[3]),+ Number(match[4]),+ Number(match[5]),+ Number(match[6])+ )+ );+ return format(instant, 'yyyy-MM-dd');+}++/** Serialize a config into a single-`RRULE` recurrence property list. */+export function buildRecurrenceLines(+ config: RecurrenceConfig,+ allDay: boolean+): string[] {+ const parts = [`FREQ=${config.frequency}`];+ if (config.interval > 1) {+ parts.push(`INTERVAL=${config.interval}`);+ }+ if (config.frequency === 'WEEKLY' && config.byDay.length > 0) {+ const ordered = WEEKDAY_CODES.filter((code) => config.byDay.includes(code));+ parts.push(`BYDAY=${ordered.join(',')}`);+ }+ if (config.frequency === 'MONTHLY' && config.monthlyByDay) {+ parts.push(+ `BYDAY=${config.monthlyByDay.ordinal}${config.monthlyByDay.weekday}`+ );+ }+ if (config.ends.kind === 'on') {+ parts.push(`UNTIL=${untilValue(config.ends.date, allDay)}`);+ } else if (config.ends.kind === 'after') {+ parts.push(`COUNT=${config.ends.count}`);+ }+ return [`RRULE:${parts.join(';')}`];+}++/**+ * Parse recurrence properties into an editable config. Returns `undefined`+ * for rules the editor cannot round-trip (extra dates, exclusions, or+ * selectors beyond its vocabulary), which the UI keeps untouched instead.+ */+export function parseRecurrenceConfig(+ lines: string[]+): RecurrenceConfig | undefined {+ if (lines.length === 0) return undefined;+ const parsed = parseRecurrenceLines(lines);+ const rule = parsed.rule;+ if (+ !rule ||+ parsed.additionalDates.length > 0 ||+ parsed.excludedDates.length > 0 ||+ lines.length > 1+ ) {+ return undefined;+ }+ if (+ rule.frequency !== 'DAILY' &&+ rule.frequency !== 'WEEKLY' &&+ rule.frequency !== 'MONTHLY' &&+ rule.frequency !== 'YEARLY'+ ) {+ return undefined;+ }+ if (rule.byMonthDay.length > 0 || rule.byMonth.length > 0) {+ return undefined;+ }+ if (rule.count !== undefined && rule.until !== undefined) {+ return undefined;+ }++ let byDay: WeekdayCode[] = [];+ let monthlyByDay: RecurrenceConfig['monthlyByDay'];+ if (rule.byDay.length > 0) {+ if (rule.frequency === 'WEEKLY') {+ if (rule.byDay.some((day) => day.ordinal !== undefined)) {+ return undefined;+ }+ byDay = rule.byDay.map((day) => day.weekday);+ } else if (rule.frequency === 'MONTHLY' && rule.byDay.length === 1) {+ const [day] = rule.byDay;+ if (day?.ordinal === undefined) return undefined;+ monthlyByDay = { ordinal: day.ordinal, weekday: day.weekday };+ } else {+ return undefined;+ }+ }++ let ends: RecurrenceEnds = NEVER;+ if (rule.count !== undefined) {+ ends = { kind: 'after', count: rule.count };+ } else if (rule.until !== undefined) {+ const date = untilDate(rule.until);+ if (date === undefined) return undefined;+ ends = { kind: 'on', date };+ }++ return {+ frequency: rule.frequency,+ interval: rule.interval,+ byDay,+ monthlyByDay,+ ends,+ };+}++/** The positional weekday Google's monthly preset uses: 1st–4th, else last. */+export function monthlyOrdinalFor(start: Date): {+ ordinal: number;+ weekday: WeekdayCode;+} {+ const nth = Math.ceil(start.getDate() / 7);+ return {+ ordinal: nth === 5 ? -1 : nth,+ weekday: WEEKDAY_CODES[start.getDay()] as WeekdayCode,+ };+}++/** One entry in the recurrence preset dropdown. */+export interface RecurrencePreset {+ id: string;+ label: string;+ config: RecurrenceConfig;+}++const ORDINAL_LABELS: Record<number, string> = {+ 1: 'first',+ 2: 'second',+ 3: 'third',+ 4: 'fourth',+ [-1]: 'last',+};++/** Google Calendar's preset list, phrased from the event's start date. */+export function recurrencePresetsFor(start: Date): RecurrencePreset[] {+ const weekday = WEEKDAY_CODES[start.getDay()] as WeekdayCode;+ const weekdayName = format(start, 'EEEE');+ const monthly = monthlyOrdinalFor(start);+ return [+ {+ id: 'daily',+ label: 'Daily',+ config: { frequency: 'DAILY', interval: 1, byDay: [], ends: NEVER },+ },+ {+ id: 'weekly',+ label: `Weekly on ${weekdayName}`,+ config: {+ frequency: 'WEEKLY',+ interval: 1,+ byDay: [weekday],+ ends: NEVER,+ },+ },+ {+ id: 'monthly',+ label: `Monthly on the ${ORDINAL_LABELS[monthly.ordinal]} ${weekdayName}`,+ config: {+ frequency: 'MONTHLY',+ interval: 1,+ byDay: [],+ monthlyByDay: monthly,+ ends: NEVER,+ },+ },+ {+ id: 'annually',+ label: `Annually on ${format(start, 'MMMM d')}`,+ config: { frequency: 'YEARLY', interval: 1, byDay: [], ends: NEVER },+ },+ {+ id: 'weekdays',+ label: 'Every weekday (Monday to Friday)',+ config: {+ frequency: 'WEEKLY',+ interval: 1,+ byDay: [...WORKWEEK],+ ends: NEVER,+ },+ },+ ];+}++/** Whether two configs produce the same rule. */+export function recurrenceConfigsEqual(+ first: RecurrenceConfig,+ second: RecurrenceConfig+): boolean {+ return (+ buildRecurrenceLines(first, false).join('\n') ===+ buildRecurrenceLines(second, false).join('\n')+ );+}++/** A sensible starting point for the custom editor. */+export function defaultCustomConfig(start: Date): RecurrenceConfig {+ return {+ frequency: 'WEEKLY',+ interval: 1,+ byDay: [WEEKDAY_CODES[start.getDay()] as WeekdayCode],+ ends: NEVER,+ };+}diff --git a/apps/web/src/lib/queries/calendar/calendars.ts b/apps/web/src/lib/queries/calendar/calendars.tsnew file mode 100644index 0000000000..ffba48e6b9--- /dev/null+++ b/apps/web/src/lib/queries/calendar/calendars.ts@@ -0,0 +1,25 @@+import { throwOnErr } from '@core/util/result';+import { emailClient } from '@service-email/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { calendarKeys } from './keys';++export type { VisibleCalendar } from '@service-email/generated/schemas/visibleCalendar';++const CALENDAR_LIST_STALE_TIME = 5 * 60_000;++/**+ * Calendars visible to the viewer across connected and delegated inboxes,+ * primaries and writable calendars first — the order pickers present them in.+ */+export function useVisibleCalendarsQuery(+ options?: Accessor<{ enabled?: boolean }>+) {+ return useQuery(() => ({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ queryFn: async () =>+ (await throwOnErr(() => emailClient.listCalendars())).calendars,+ staleTime: CALENDAR_LIST_STALE_TIME,+ enabled: options?.().enabled !== false,+ }));+}diff --git a/apps/web/src/lib/queries/calendar/keys.ts b/apps/web/src/lib/queries/calendar/keys.tsindex 5d495df290..4862abd3ad 100644--- a/apps/web/src/lib/queries/calendar/keys.ts+++ b/apps/web/src/lib/queries/calendar/keys.ts@@ -8,6 +8,7 @@ export interface CalendarOccurrenceQueryRange {}export const calendarKeys = createQueryKeys('calendar', {+ visibleCalendars: null,occurrences: (userId: string,range: CalendarOccurrenceQueryRange | undefineddiff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.tsnew file mode 100644index 0000000000..3c40e1601f--- /dev/null+++ b/apps/web/src/lib/queries/calendar/mutations.ts@@ -0,0 +1,270 @@+import { throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';+import { type MutationCallbacks, withCallbacks } from '@queries/utils';+import { type CalendarDeletionScope, emailClient } from '@service-email/client';+import type { CalendarEvent as CalendarEventEntity } from '@service-email/generated/schemas/calendarEvent';+import type { CreateCalendarEventRequest } from '@service-email/generated/schemas/createCalendarEventRequest';+import type { UpdateCalendarEventRequest } from '@service-email/generated/schemas/updateCalendarEventRequest';+import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';+import type { EventTime } from '@service-storage/generated/schemas/eventTime';+import { useMutation } from '@tanstack/solid-query';+import { calendarKeys } from './keys';+import {+ type CalendarOccurrencesData,+ invalidateCalendarOccurrences,+} from './occurrences';++export type {+ CreateCalendarEventRequest,+ UpdateCalendarEventRequest,+} from '@service-email/generated/schemas';++type CalendarMutationContext = { rollback: () => void };++/**+ * Optimistically rewrite every cached occurrence viewport (each visible+ * range is its own cache entry) and return a rollback that restores the+ * exact snapshots.+ */+async function patchOccurrenceCaches(+ update: (items: CalendarOccurrenceItem[]) => CalendarOccurrenceItem[]+): Promise<CalendarMutationContext> {+ await queryClient.cancelQueries({+ queryKey: calendarKeys.occurrences._def,+ });+ const previous = queryClient.getQueriesData<CalendarOccurrencesData>({+ queryKey: calendarKeys.occurrences._def,+ });+ queryClient.setQueriesData<CalendarOccurrencesData>(+ { queryKey: calendarKeys.occurrences._def },+ (old) => old && { ...old, items: update(old.items) }+ );+ return {+ rollback: () => {+ for (const [queryKey, data] of previous) {+ queryClient.setQueryData(queryKey, data);+ }+ },+ };+}++function patchEventItems(+ eventId: string,+ patch: (item: CalendarOccurrenceItem) => CalendarOccurrenceItem+) {+ return (items: CalendarOccurrenceItem[]) =>+ items.map((item) => (item.event.id === eventId ? patch(item) : item));+}++export interface RsvpCalendarEventArgs {+ eventId: string;+ response: Exclude<AttendeeResponseStatus, 'needs_action'>;+}++type RsvpCallbacks = MutationCallbacks<+ CalendarEventEntity,+ Error,+ RsvpCalendarEventArgs,+ CalendarMutationContext+>;++/** Sets the viewer's RSVP; recurring events respond for the whole series. */+export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {+ return useMutation(() => ({+ mutationFn: async (args: RsvpCalendarEventArgs) =>+ await throwOnErr(() =>+ emailClient.rsvpCalendarEvent(args.eventId, {+ response: args.response,+ })+ ),+ ...withCallbacks<+ CalendarEventEntity,+ Error,+ RsvpCalendarEventArgs,+ CalendarMutationContext+ >(+ {+ onMutate: (args) =>+ patchOccurrenceCaches(+ patchEventItems(args.eventId, (item) => ({+ ...item,+ event: {+ ...item.event,+ attendees: item.event.attendees.map((attendee) =>+ attendee.isSelf+ ? { ...attendee, responseStatus: args.response }+ : attendee+ ),+ },+ }))+ ),+ onError: (_error, _args, context) => context?.rollback(),+ onSettled: () => invalidateCalendarOccurrences(),+ },+ callbacks+ ),+ }));+}++export interface DeleteCalendarEventArgs {+ eventId: string;+ /** How much of a recurring series to remove; defaults to all of it. */+ scope?: CalendarDeletionScope;+ /** Original-start key of the occurrence a scoped deletion targets. */+ recurrenceId?: string;+ /** Cache key of the occurrence, for the optimistic update. */+ occurrenceKey?: string;+}++function survivesDeletion(+ item: CalendarOccurrenceItem,+ args: DeleteCalendarEventArgs+): boolean {+ if (item.event.id !== args.eventId) return true;+ if (args.scope === 'this_event') {+ return item.occurrence.occurrenceKey !== args.occurrenceKey;+ }+ if (args.scope === 'this_and_following' && args.occurrenceKey !== undefined) {+ // Occurrence keys within one event share a format, so ordering is+ // lexicographic.+ return item.occurrence.occurrenceKey < args.occurrenceKey;+ }+ return false;+}++type DeleteCallbacks = MutationCallbacks<+ unknown,+ Error,+ DeleteCalendarEventArgs,+ CalendarMutationContext+>;++/** Deletes an event (a recurring event's entire series) at the provider. */+export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {+ return useMutation(() => ({+ mutationFn: async (args: DeleteCalendarEventArgs) =>+ await throwOnErr(() =>+ emailClient.deleteCalendarEvent(args.eventId, {+ scope: args.scope,+ recurrenceId: args.recurrenceId,+ })+ ),+ ...withCallbacks<+ unknown,+ Error,+ DeleteCalendarEventArgs,+ CalendarMutationContext+ >(+ {+ onMutate: (args) =>+ patchOccurrenceCaches((items) =>+ items.filter((item) => survivesDeletion(item, args))+ ),+ onError: (_error, _args, context) => context?.rollback(),+ onSettled: () => invalidateCalendarOccurrences(),+ },+ callbacks+ ),+ }));+}++export interface UpdateCalendarEventArgs {+ eventId: string;+ patch: UpdateCalendarEventRequest;+}++type UpdateCallbacks = MutationCallbacks<+ CalendarEventEntity,+ Error,+ UpdateCalendarEventArgs,+ CalendarMutationContext+>;++/**+ * Applies the field patch to a cached item. Times are only patched through+ * to standalone occurrences — recurring expansion is the provider's job, so+ * recurring series keep their cached instances until the refetch lands.+ */+function applyEventPatch(+ item: CalendarOccurrenceItem,+ patch: UpdateCalendarEventRequest+): CalendarOccurrenceItem {+ const event = { ...item.event };+ if (patch.title !== undefined && patch.title !== null) {+ event.title = patch.title;+ }+ if (patch.description !== undefined) {+ event.description = patch.description;+ }+ if (patch.location !== undefined) {+ event.location = patch.location;+ }+ const time = patch.time ?? undefined;+ const isStandalone =+ event.recurrenceLines.length === 0 &&+ (item.occurrence.recurrenceId === undefined ||+ item.occurrence.recurrenceId === null);+ let occurrence = item.occurrence;+ if (time) {+ event.time = time as EventTime;+ if (isStandalone) {+ occurrence = { ...occurrence, time: time as EventTime };+ }+ }+ return { ...item, event, occurrence };+}++/** Patches event fields; recurring events update the whole series. */+export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {+ return useMutation(() => ({+ mutationFn: async (args: UpdateCalendarEventArgs) =>+ await throwOnErr(() =>+ emailClient.updateCalendarEvent(args.eventId, args.patch)+ ),+ ...withCallbacks<+ CalendarEventEntity,+ Error,+ UpdateCalendarEventArgs,+ CalendarMutationContext+ >(+ {+ onMutate: (args) =>+ patchOccurrenceCaches(+ patchEventItems(args.eventId, (item) =>+ applyEventPatch(item, args.patch)+ )+ ),+ onError: (_error, _args, context) => context?.rollback(),+ onSettled: () => invalidateCalendarOccurrences(),+ },+ callbacks+ ),+ }));+}++type CreateCallbacks = MutationCallbacks<+ CalendarEventEntity,+ Error,+ CreateCalendarEventRequest,+ unknown+>;++/**+ * Creates an event on the selected calendar, defaulting to the requester's+ * primary calendar when no `calendarId` is given. There is no optimistic+ * insert — the entity id is only known once the provider echo lands — so+ * the viewport refetches on settle.+ */+export function useCreateCalendarEventMutation(callbacks?: CreateCallbacks) {+ return useMutation(() => ({+ mutationFn: async (args: CreateCalendarEventRequest) =>+ await throwOnErr(() => emailClient.createCalendarEvent(args)),+ ...withCallbacks<CalendarEventEntity, Error, CreateCalendarEventRequest>(+ {+ onSettled: () => invalidateCalendarOccurrences(),+ },+ callbacks+ ),+ }));+}diff --git a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsxnew file mode 100644index 0000000000..b999de89bb--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx@@ -0,0 +1,290 @@+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { calendarKeys } from '../keys';+import {+ useDeleteCalendarEventMutation,+ useRsvpCalendarEventMutation,+ useUpdateCalendarEventMutation,+} from '../mutations';+import type { CalendarOccurrencesData } from '../occurrences';++const rsvpCalendarEventMock = vi.hoisted(() => vi.fn());+const deleteCalendarEventMock = vi.hoisted(() => vi.fn());+const updateCalendarEventMock = vi.hoisted(() => vi.fn());++vi.mock('@service-email/client', () => ({+ emailClient: {+ rsvpCalendarEvent: rsvpCalendarEventMock,+ deleteCalendarEvent: deleteCalendarEventMock,+ updateCalendarEvent: updateCalendarEventMock,+ },+}));++let testQueryClient: QueryClient;++vi.mock('../../client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++const viewportA = {+ start: '2026-08-01T04:00:00.000Z',+ end: '2026-09-01T04:00:00.000Z',+ startDate: '2026-08-01',+ endDate: '2026-09-01',+};+const viewportB = {+ start: '2026-08-03T04:00:00.000Z',+ end: '2026-08-10T04:00:00.000Z',+ startDate: '2026-08-03',+ endDate: '2026-08-10',+};++const standaloneItem = (): CalendarOccurrenceItem =>+ ({+ event: {+ id: 'event-1',+ title: 'Standalone',+ recurrenceLines: [],+ time: {+ kind: 'timed',+ startsAt: '2026-08-06T14:00:00Z',+ endsAt: '2026-08-06T15:00:00Z',+ },+ attendees: [+ {+ email: '[email protected]',+ isSelf: true,+ responseStatus: 'needs_action',+ },+ {+ email: '[email protected]',+ isSelf: false,+ responseStatus: 'declined',+ },+ ],+ },+ occurrence: {+ eventId: 'event-1',+ occurrenceKey: '2026-08-06T14:00:00Z',+ time: {+ kind: 'timed',+ startsAt: '2026-08-06T14:00:00Z',+ endsAt: '2026-08-06T15:00:00Z',+ },+ },+ }) as unknown as CalendarOccurrenceItem;++const recurringItem = (): CalendarOccurrenceItem =>+ ({+ event: {+ id: 'event-2',+ title: 'Recurring',+ recurrenceLines: ['RRULE:FREQ=DAILY'],+ time: {+ kind: 'timed',+ startsAt: '2026-08-04T09:00:00Z',+ endsAt: '2026-08-04T09:30:00Z',+ },+ attendees: [],+ },+ occurrence: {+ eventId: 'event-2',+ occurrenceKey: '2026-08-05T09:00:00Z',+ recurrenceId: '2026-08-05T09:00:00Z',+ time: {+ kind: 'timed',+ startsAt: '2026-08-05T09:00:00Z',+ endsAt: '2026-08-05T09:30:00Z',+ },+ },+ }) as unknown as CalendarOccurrenceItem;++const seedViewports = () => {+ const data = (): CalendarOccurrencesData => ({+ items: [standaloneItem(), recurringItem()],+ syncStatus: 'ready',+ });+ testQueryClient.setQueryData(+ calendarKeys.occurrences('user', viewportA).queryKey,+ data()+ );+ testQueryClient.setQueryData(+ calendarKeys.occurrences('user', viewportB).queryKey,+ data()+ );+};++const viewportData = (range: typeof viewportA) =>+ testQueryClient.getQueryData<CalendarOccurrencesData>(+ calendarKeys.occurrences('user', range).queryKey+ );++let dispose: (() => void) | undefined;++function renderHook<T>(factory: () => T): T {+ let hook!: T;+ dispose = render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ hook = factory();+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ );+ return hook;+}++const failure = () =>+ err([{ code: 'HTTP_ERROR' as const, message: 'provider says no' }]);++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ seedViewports();+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ testQueryClient.clear();+});++describe('useRsvpCalendarEventMutation', () => {+ it('optimistically updates the self attendee across every cached viewport', async () => {+ rsvpCalendarEventMock.mockResolvedValue(ok({ id: 'event-1' }));+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());++ await rsvp.mutateAsync({ eventId: 'event-1', response: 'accepted' });++ for (const range of [viewportA, viewportB]) {+ const items = viewportData(range)?.items ?? [];+ const event = items.find((item) => item.event.id === 'event-1')?.event;+ expect(+ event?.attendees.find((attendee) => attendee.isSelf)?.responseStatus+ ).toBe('accepted');+ expect(+ event?.attendees.find((attendee) => !attendee.isSelf)?.responseStatus+ ).toBe('declined');+ }+ expect(rsvpCalendarEventMock).toHaveBeenCalledWith('event-1', {+ response: 'accepted',+ });+ });++ it('rolls back every viewport when the request fails', async () => {+ rsvpCalendarEventMock.mockResolvedValue(failure());+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());++ await expect(+ rsvp.mutateAsync({ eventId: 'event-1', response: 'declined' })+ ).rejects.toThrow();++ for (const range of [viewportA, viewportB]) {+ const items = viewportData(range)?.items ?? [];+ const event = items.find((item) => item.event.id === 'event-1')?.event;+ expect(+ event?.attendees.find((attendee) => attendee.isSelf)?.responseStatus+ ).toBe('needs_action');+ }+ });+});++describe('useDeleteCalendarEventMutation', () => {+ it('optimistically removes the event and keeps the removal on success', async () => {+ deleteCalendarEventMock.mockResolvedValue(ok({}));+ const remove = renderHook(() => useDeleteCalendarEventMutation());++ await remove.mutateAsync({ eventId: 'event-1' });++ for (const range of [viewportA, viewportB]) {+ const items = viewportData(range)?.items ?? [];+ expect(items.map((item) => item.event.id)).toEqual(['event-2']);+ }+ });++ it('scopes optimistic removal to one occurrence or a suffix', async () => {+ deleteCalendarEventMock.mockResolvedValue(ok({}));+ const remove = renderHook(() => useDeleteCalendarEventMutation());++ await remove.mutateAsync({+ eventId: 'event-2',+ scope: 'this_event',+ recurrenceId: '2026-08-05T09:00:00Z',+ occurrenceKey: '2026-08-05T09:00:00Z',+ });+ expect(deleteCalendarEventMock).toHaveBeenCalledWith('event-2', {+ scope: 'this_event',+ recurrenceId: '2026-08-05T09:00:00Z',+ });+ let items = viewportData(viewportA)?.items ?? [];+ expect(items.map((item) => item.occurrence.occurrenceKey)).toEqual([+ '2026-08-06T14:00:00Z',+ ]);++ seedViewports();+ await remove.mutateAsync({+ eventId: 'event-2',+ scope: 'this_and_following',+ recurrenceId: '2026-08-05T09:00:00Z',+ occurrenceKey: '2026-08-05T09:00:00Z',+ });+ items = viewportData(viewportA)?.items ?? [];+ expect(items.map((item) => item.event.id)).toEqual(['event-1']);+ });++ it('restores removed items when the request fails', async () => {+ deleteCalendarEventMock.mockResolvedValue(failure());+ const remove = renderHook(() => useDeleteCalendarEventMutation());++ await expect(remove.mutateAsync({ eventId: 'event-1' })).rejects.toThrow();++ for (const range of [viewportA, viewportB]) {+ const items = viewportData(range)?.items ?? [];+ expect(items).toHaveLength(2);+ }+ });+});++describe('useUpdateCalendarEventMutation', () => {+ it('patches fields and only rewrites standalone occurrence times', async () => {+ updateCalendarEventMock.mockResolvedValue(ok({ id: 'event-1' }));+ const update = renderHook(() => useUpdateCalendarEventMutation());+ const time = {+ kind: 'timed',+ startsAt: '2026-08-06T16:00:00Z',+ endsAt: '2026-08-06T17:00:00Z',+ } as const;++ await update.mutateAsync({+ eventId: 'event-1',+ patch: { title: 'Renamed', time },+ });+ await update.mutateAsync({+ eventId: 'event-2',+ patch: { time },+ });++ const items = viewportData(viewportA)?.items ?? [];+ const standalone = items.find((item) => item.event.id === 'event-1');+ expect(standalone?.event.title).toBe('Renamed');+ expect(standalone?.occurrence.time).toEqual(time);++ const recurring = items.find((item) => item.event.id === 'event-2');+ expect(recurring?.event.time).toEqual(time);+ expect(recurring?.occurrence.time.kind === 'timed').toBe(true);+ expect(recurring?.occurrence.time).toMatchObject({+ startsAt: '2026-08-05T09:00:00Z',+ });+ });+});diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.tsindex 06386998d9..eb124d58bd 100644--- a/apps/web/src/lib/service-clients/service-email/client.ts+++ b/apps/web/src/lib/service-clients/service-email/client.ts@@ -10,12 +10,15 @@ import type {AddDraftAttachmentRequest,AddDraftAttachmentResponse,ApiPaginatedThreadCursor,+ CalendarEvent,+ CreateCalendarEventRequest,CreateDraftRequest,CreateDraftResponse,GetAttachmentDocumentIDResponse,GetAttachmentResponse,GetThreadResponse,ListBackfillJobsResponse,+ ListCalendarsResponse,ListContactsResponse,ListEmailFiltersResponse,ListLabelsResponse,@@ -23,9 +26,11 @@ import type {PatchSettingsRequest,PatchSettingsResponse,ResyncResponse,+ RsvpCalendarEventRequest,SendMessageRequest,SendMessageResponse,SharedInboxConflictResponse,+ UpdateCalendarEventRequest,UpdateLabelBatchRequest,UpdateLabelBatchResponse,UpdateThreadLabelRequest,@@ -35,6 +40,7 @@ import type {UpsertScheduledRequest,UpsertScheduledResponse,} from './generated/schemas';+import { CalendarMutationErrorCode } from './generated/schemas/calendarMutationErrorCode';import type { EmptyResponse } from './generated/schemas/emptyResponse';const emailHost: string = SERVER_HOSTS['email-service'];@@ -45,10 +51,35 @@ const emailHost: string = SERVER_HOSTS['email-service'];*/const EMAIL_LINK_ID_HEADER = 'X-Email-Link-Id';+/** How much of a recurring series a calendar deletion removes. */+export type CalendarDeletionScope = 'all' | 'this_event' | 'this_and_following';+function emailLinkHeaders(linkId?: string): Record<string, string> | undefined {return linkId ? { [EMAIL_LINK_ID_HEADER]: linkId } : undefined;}+/**+ * Calendar mutation failures carry a machine-readable `{ code, message }`+ * body; surface it so callers can branch on the code and show the message.+ */+async function calendarMutationErrorHandler(response: Response) {+ const body = (await response.json().catch(() => null)) as {+ code?: string;+ message?: string;+ } | null;+ const code =+ body?.code && body.code in CalendarMutationErrorCode+ ? (body.code as CalendarMutationErrorCode)+ : undefined;+ if (code) {+ return { code, message: body?.message ?? '' };+ }+ return {+ code: 'HTTP_ERROR' as const,+ message: `HTTP error! status: ${response.status}`,+ };+}+function emailFetch(url: string,init?: SafeFetchInit@@ -526,4 +557,62 @@ export const emailClient = {method: 'DELETE',});},+ async listCalendars() {+ return fetchWithToken<ListCalendarsResponse>(+ `${emailHost}/calendar/calendars`,+ {+ method: 'GET',+ }+ );+ },+ async createCalendarEvent(args: CreateCalendarEventRequest) {+ return fetchWithToken<CalendarEvent, CalendarMutationErrorCode>(+ `${emailHost}/calendar/events`,+ {+ method: 'POST',+ body: JSON.stringify(args),+ errorResponseHandler: calendarMutationErrorHandler,+ }+ );+ },+ async updateCalendarEvent(eventId: string, args: UpdateCalendarEventRequest) {+ return fetchWithToken<CalendarEvent, CalendarMutationErrorCode>(+ `${emailHost}/calendar/events/${eventId}`,+ {+ method: 'PATCH',+ body: JSON.stringify(args),+ errorResponseHandler: calendarMutationErrorHandler,+ }+ );+ },+ async deleteCalendarEvent(+ eventId: string,+ options?: { scope?: CalendarDeletionScope; recurrenceId?: string }+ ) {+ const params = new URLSearchParams();+ if (options?.scope && options.scope !== 'all') {+ params.set('scope', options.scope);+ }+ if (options?.recurrenceId) {+ params.set('recurrenceId', options.recurrenceId);+ }+ const query = params.toString();+ return fetchWithToken<EmptyResponse, CalendarMutationErrorCode>(+ `${emailHost}/calendar/events/${eventId}${query ? `?${query}` : ''}`,+ {+ method: 'DELETE',+ errorResponseHandler: calendarMutationErrorHandler,+ }+ );+ },+ async rsvpCalendarEvent(eventId: string, args: RsvpCalendarEventRequest) {+ return fetchWithToken<CalendarEvent, CalendarMutationErrorCode>(+ `${emailHost}/calendar/events/${eventId}/rsvp`,+ {+ method: 'PUT',+ body: JSON.stringify(args),+ errorResponseHandler: calendarMutationErrorHandler,+ }+ );+ },};diff --git a/apps/web/src/lib/service-clients/service-email/generated/client.ts b/apps/web/src/lib/service-clients/service-email/generated/client.tsindex d6bc950296..406e1ef0a3 100644--- a/apps/web/src/lib/service-clients/service-email/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/client.ts@@ -12,11 +12,15 @@ import type {ApiPaginatedThreadCursor,ArchiveThreadRequest,BlockSenderRequest,+ CalendarEvent,+ CalendarMutationApiError,CancelBackfillParams,+ CreateCalendarEventRequest,CreateDraftRequest,CreateDraftResponse,CreateLabelRequest,CreateLabelResponse,+ DeleteCalendarEventParams,EmptyResponse,ErrorResponse,GetActiveBackfillJobResponse,@@ -33,6 +37,7 @@ import type {InitUserParams,ListBackfillJobsResponse,ListBlockedResponse,+ ListCalendarsResponse,ListContactsResponse,ListEmailFiltersResponse,ListLabelsResponse,@@ -42,11 +47,13 @@ import type {PatchSettingsResponse,PreviewsInboxCursorParams,ResyncResponse,+ RsvpCalendarEventRequest,SendMessageRequest,SendMessageResponse,SharedInboxConflictResponse,UnblockSenderRequest,UnresolvedSignatureImagesError,+ UpdateCalendarEventRequest,UpdateLabelBatchRequest,UpdateLabelBatchResponse,UpdateThreadLabelRequest,@@ -59,6 +66,391 @@ import type {UpsertScheduledResponse,} from './schemas';+/**+ * @summary List the requester's visible calendars for pickers and filters.+ */+export type listCalendarsResponse200 = {+ data: ListCalendarsResponse;+ status: 200;+};++export type listCalendarsResponse401 = {+ data: void;+ status: 401;+};++export type listCalendarsResponse503 = {+ data: CalendarMutationApiError;+ status: 503;+};++export type listCalendarsResponseSuccess = listCalendarsResponse200 & {+ headers: Headers;+};+export type listCalendarsResponseError = (+ | listCalendarsResponse401+ | listCalendarsResponse503+) & {+ headers: Headers;+};++export type listCalendarsResponse =+ | listCalendarsResponseSuccess+ | listCalendarsResponseError;++export const getListCalendarsUrl = () => {+ return `/calendar/calendars`;+};++export const listCalendars = async (+ options?: RequestInit+): Promise<listCalendarsResponse> => {+ const res = await fetch(getListCalendarsUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listCalendarsResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listCalendarsResponse;+};++/**+ * @summary Create a calendar event and return its synced entity.+ */+export type createCalendarEventResponse201 = {+ data: CalendarEvent;+ status: 201;+};++export type createCalendarEventResponse400 = {+ data: CalendarMutationApiError;+ status: 400;+};++export type createCalendarEventResponse401 = {+ data: void;+ status: 401;+};++export type createCalendarEventResponse403 = {+ data: CalendarMutationApiError;+ status: 403;+};++export type createCalendarEventResponse409 = {+ data: CalendarMutationApiError;+ status: 409;+};++export type createCalendarEventResponse503 = {+ data: CalendarMutationApiError;+ status: 503;+};++export type createCalendarEventResponseSuccess =+ createCalendarEventResponse201 & {+ headers: Headers;+ };+export type createCalendarEventResponseError = (+ | createCalendarEventResponse400+ | createCalendarEventResponse401+ | createCalendarEventResponse403+ | createCalendarEventResponse409+ | createCalendarEventResponse503+) & {+ headers: Headers;+};++export type createCalendarEventResponse =+ | createCalendarEventResponseSuccess+ | createCalendarEventResponseError;++export const getCreateCalendarEventUrl = () => {+ return `/calendar/events`;+};++export const createCalendarEvent = async (+ createCalendarEventRequest: CreateCalendarEventRequest,+ options?: RequestInit+): Promise<createCalendarEventResponse> => {+ const res = await fetch(getCreateCalendarEventUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createCalendarEventRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: createCalendarEventResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as createCalendarEventResponse;+};++/**+ * @summary Delete a calendar event at its provider.+ */+export type deleteCalendarEventResponse204 = {+ data: void;+ status: 204;+};++export type deleteCalendarEventResponse401 = {+ data: void;+ status: 401;+};++export type deleteCalendarEventResponse403 = {+ data: CalendarMutationApiError;+ status: 403;+};++export type deleteCalendarEventResponse404 = {+ data: CalendarMutationApiError;+ status: 404;+};++export type deleteCalendarEventResponse409 = {+ data: CalendarMutationApiError;+ status: 409;+};++export type deleteCalendarEventResponse503 = {+ data: CalendarMutationApiError;+ status: 503;+};++export type deleteCalendarEventResponseSuccess =+ deleteCalendarEventResponse204 & {+ headers: Headers;+ };+export type deleteCalendarEventResponseError = (+ | deleteCalendarEventResponse401+ | deleteCalendarEventResponse403+ | deleteCalendarEventResponse404+ | deleteCalendarEventResponse409+ | deleteCalendarEventResponse503+) & {+ headers: Headers;+};++export type deleteCalendarEventResponse =+ | deleteCalendarEventResponseSuccess+ | deleteCalendarEventResponseError;++export const getDeleteCalendarEventUrl = (+ eventId: string,+ params?: DeleteCalendarEventParams+) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });++ const stringifiedParams = normalizedParams.toString();++ return stringifiedParams.length > 0+ ? `/calendar/events/${eventId}?${stringifiedParams}`+ : `/calendar/events/${eventId}`;+};++export const deleteCalendarEvent = async (+ eventId: string,+ params?: DeleteCalendarEventParams,+ options?: RequestInit+): Promise<deleteCalendarEventResponse> => {+ const res = await fetch(getDeleteCalendarEventUrl(eventId, params), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: deleteCalendarEventResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as deleteCalendarEventResponse;+};++/**+ * @summary Update fields of a calendar event and return its synced entity.+ */+export type updateCalendarEventResponse200 = {+ data: CalendarEvent;+ status: 200;+};++export type updateCalendarEventResponse400 = {+ data: CalendarMutationApiError;+ status: 400;+};++export type updateCalendarEventResponse401 = {+ data: void;+ status: 401;+};++export type updateCalendarEventResponse403 = {+ data: CalendarMutationApiError;+ status: 403;+};++export type updateCalendarEventResponse404 = {+ data: CalendarMutationApiError;+ status: 404;+};++export type updateCalendarEventResponse409 = {+ data: CalendarMutationApiError;+ status: 409;+};++export type updateCalendarEventResponse503 = {+ data: CalendarMutationApiError;+ status: 503;+};++export type updateCalendarEventResponseSuccess =+ updateCalendarEventResponse200 & {+ headers: Headers;+ };+export type updateCalendarEventResponseError = (+ | updateCalendarEventResponse400+ | updateCalendarEventResponse401+ | updateCalendarEventResponse403+ | updateCalendarEventResponse404+ | updateCalendarEventResponse409+ | updateCalendarEventResponse503+) & {+ headers: Headers;+};++export type updateCalendarEventResponse =+ | updateCalendarEventResponseSuccess+ | updateCalendarEventResponseError;++export const getUpdateCalendarEventUrl = (eventId: string) => {+ return `/calendar/events/${eventId}`;+};++export const updateCalendarEvent = async (+ eventId: string,+ updateCalendarEventRequest: UpdateCalendarEventRequest,+ options?: RequestInit+): Promise<updateCalendarEventResponse> => {+ const res = await fetch(getUpdateCalendarEventUrl(eventId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(updateCalendarEventRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: updateCalendarEventResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as updateCalendarEventResponse;+};++/**+ * @summary Set the requester's RSVP on a calendar event and return its synced entity.+ */+export type rsvpCalendarEventResponse200 = {+ data: CalendarEvent;+ status: 200;+};++export type rsvpCalendarEventResponse401 = {+ data: void;+ status: 401;+};++export type rsvpCalendarEventResponse403 = {+ data: CalendarMutationApiError;+ status: 403;+};++export type rsvpCalendarEventResponse404 = {+ data: CalendarMutationApiError;+ status: 404;+};++export type rsvpCalendarEventResponse409 = {+ data: CalendarMutationApiError;+ status: 409;+};++export type rsvpCalendarEventResponse503 = {+ data: CalendarMutationApiError;+ status: 503;+};++export type rsvpCalendarEventResponseSuccess = rsvpCalendarEventResponse200 & {+ headers: Headers;+};+export type rsvpCalendarEventResponseError = (+ | rsvpCalendarEventResponse401+ | rsvpCalendarEventResponse403+ | rsvpCalendarEventResponse404+ | rsvpCalendarEventResponse409+ | rsvpCalendarEventResponse503+) & {+ headers: Headers;+};++export type rsvpCalendarEventResponse =+ | rsvpCalendarEventResponseSuccess+ | rsvpCalendarEventResponseError;++export const getRsvpCalendarEventUrl = (eventId: string) => {+ return `/calendar/events/${eventId}/rsvp`;+};++export const rsvpCalendarEvent = async (+ eventId: string,+ rsvpCalendarEventRequest: RsvpCalendarEventRequest,+ options?: RequestInit+): Promise<rsvpCalendarEventResponse> => {+ const res = await fetch(getRsvpCalendarEventUrl(eventId), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(rsvpCalendarEventRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: rsvpCalendarEventResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as rsvpCalendarEventResponse;+};+/*** @summary Get an attachment by ID.*/diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/attendeeResponseStatus.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/attendeeResponseStatus.tsnew file mode 100644index 0000000000..d36e291b9b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/attendeeResponseStatus.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * RSVP state for an attendee.+ */+export type AttendeeResponseStatus =+ (typeof AttendeeResponseStatus)[keyof typeof AttendeeResponseStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const AttendeeResponseStatus = {+ needs_action: 'needs_action',+ accepted: 'accepted',+ declined: 'declined',+ tentative: 'tentative',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.tsnew file mode 100644index 0000000000..fc5e5fd442--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++import type { AttendeeResponseStatus } from './attendeeResponseStatus';+import type { CalendarAttendeeComment } from './calendarAttendeeComment';+import type { CalendarAttendeeDisplayName } from './calendarAttendeeDisplayName';++/**+ * An attendee on a calendar event.+ */+export interface CalendarAttendee {+ /** Optional attendee comment. */+ comment?: CalendarAttendeeComment;+ /** Provider display name. */+ displayName?: CalendarAttendeeDisplayName;+ /** Normalized email address. */+ email: string;+ /** Whether attendance is optional. */+ isOptional: boolean;+ /** Whether this attendee is the organizer. */+ isOrganizer: boolean;+ /** Whether this attendee represents the connected account. */+ isSelf: boolean;+ /** RSVP state. */+ responseStatus: AttendeeResponseStatus;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeComment.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeComment.tsnew file mode 100644index 0000000000..da541671ba--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeComment.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional attendee comment.+ */+export type CalendarAttendeeComment = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeDisplayName.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeDisplayName.tsnew file mode 100644index 0000000000..ef424c0c2b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeDisplayName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider display name.+ */+export type CalendarAttendeeDisplayName = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeInputBody.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeInputBody.tsnew file mode 100644index 0000000000..0f6603e70b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendeeInputBody.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * An attendee supplied to a calendar mutation.+ */+export interface CalendarAttendeeInputBody {+ /** Attendee email address. */+ email: string;+ /** Whether attendance is optional. */+ isOptional?: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarDeletionScopeParam.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarDeletionScopeParam.tsnew file mode 100644index 0000000000..b08a4650ee--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarDeletionScopeParam.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * How much of a recurring series a deletion removes.+ */+export type CalendarDeletionScopeParam =+ (typeof CalendarDeletionScopeParam)[keyof typeof CalendarDeletionScopeParam];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CalendarDeletionScopeParam = {+ all: 'all',+ this_event: 'this_event',+ this_and_following: 'this_and_following',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEvent.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEvent.tsnew file mode 100644index 0000000000..f05389284e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEvent.ts@@ -0,0 +1,67 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarAttendee } from './calendarAttendee';+import type { CalendarEventCalendarId } from './calendarEventCalendarId';+import type { CalendarEventConferenceUrl } from './calendarEventConferenceUrl';+import type { CalendarEventDescription } from './calendarEventDescription';+import type { CalendarEventLocation } from './calendarEventLocation';+import type { CalendarEventOrganizerEmail } from './calendarEventOrganizerEmail';+import type { CalendarEventOrganizerName } from './calendarEventOrganizerName';+import type { EventStatus } from './eventStatus';+import type { EventTime } from './eventTime';+import type { EventTransparency } from './eventTransparency';+import type { EventVisibility } from './eventVisibility';++/**+ * A stable, first-class Macro calendar event entity.+ */+export interface CalendarEvent {+ /** Attendees, keyed by email during persistence. */+ attendees: CalendarAttendee[];+ /** Calendar the canonical source belongs to, when known. Absent only in+projections stored before calendars were attributed. */+ calendarId?: CalendarEventCalendarId;+ /** Direct join URL when known. */+ conferenceUrl?: CalendarEventConferenceUrl;+ /** Entity creation time. */+ createdAt: string;+ /** Optional event body. */+ description?: CalendarEventDescription;+ /** RFC 5545 UID used to reconcile provider and email sources. */+ icalUid: string;+ /** Macro entity identifier. */+ id: string;+ /** Whether the current user can edit the canonical source. */+ isReadOnly: boolean;+ /** Optional physical or virtual location label. */+ location?: CalendarEventLocation;+ /** Organizer email. */+ organizerEmail?: CalendarEventOrganizerEmail;+ /** Organizer display name. */+ organizerName?: CalendarEventOrganizerName;+ /** Macro user who owns this event entity. */+ ownerId: string;+ /** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */+ recurrenceLines: string[];+ /**+ * Provider/iCalendar sequence number.+ * @minimum 0+ */+ sequence: number;+ /** Event status. */+ status: EventStatus;+ /** Timed or all-day shape. */+ time: EventTime;+ /** Display title. */+ title: string;+ /** Availability behavior. */+ transparency: EventTransparency;+ /** Entity update time. */+ updatedAt: string;+ /** Event visibility. */+ visibility: EventVisibility;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventCalendarId.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventCalendarId.tsnew file mode 100644index 0000000000..b1e90c282f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventCalendarId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Calendar the canonical source belongs to, when known. Absent only in+projections stored before calendars were attributed.+ */+export type CalendarEventCalendarId = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventConferenceUrl.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventConferenceUrl.tsnew file mode 100644index 0000000000..6a7a1ed627--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventConferenceUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Direct join URL when known.+ */+export type CalendarEventConferenceUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventDescription.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventDescription.tsnew file mode 100644index 0000000000..50704f93cb--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional event body.+ */+export type CalendarEventDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventLocation.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventLocation.tsnew file mode 100644index 0000000000..b346a39707--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventLocation.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional physical or virtual location label.+ */+export type CalendarEventLocation = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerEmail.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerEmail.tsnew file mode 100644index 0000000000..565a77763c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerEmail.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer email.+ */+export type CalendarEventOrganizerEmail = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerName.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerName.tsnew file mode 100644index 0000000000..48fa69e780--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarEventOrganizerName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer display name.+ */+export type CalendarEventOrganizerName = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationApiError.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationApiError.tsnew file mode 100644index 0000000000..279f25ff53--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationApiError.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarMutationErrorCode } from './calendarMutationErrorCode';++/**+ * HTTP error body returned by calendar mutation endpoints.+ */+export interface CalendarMutationApiError {+ /** Machine-readable failure category. */+ code: CalendarMutationErrorCode;+ /** Human-readable failure description. */+ message: string;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationErrorCode.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationErrorCode.tsnew file mode 100644index 0000000000..27b75af8ca--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarMutationErrorCode.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Machine-readable failure category for calendar mutations.+ */+export type CalendarMutationErrorCode =+ (typeof CalendarMutationErrorCode)[keyof typeof CalendarMutationErrorCode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CalendarMutationErrorCode = {+ not_found: 'not_found',+ read_only: 'read_only',+ no_writable_calendar: 'no_writable_calendar',+ not_attendee: 'not_attendee',+ invalid_input: 'invalid_input',+ reauth_required: 'reauth_required',+ provider_rejected: 'provider_rejected',+ retryable: 'retryable',+ persist_failed: 'persist_failed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequest.tsnew file mode 100644index 0000000000..c1ab83540f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequest.ts@@ -0,0 +1,40 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarAttendeeInputBody } from './calendarAttendeeInputBody';+import type { CreateCalendarEventRequestCalendarId } from './createCalendarEventRequestCalendarId';+import type { CreateCalendarEventRequestDescription } from './createCalendarEventRequestDescription';+import type { CreateCalendarEventRequestEmailLinkId } from './createCalendarEventRequestEmailLinkId';+import type { CreateCalendarEventRequestLocation } from './createCalendarEventRequestLocation';+import type { CreateCalendarEventRequestTransparency } from './createCalendarEventRequestTransparency';+import type { CreateCalendarEventRequestVisibility } from './createCalendarEventRequestVisibility';+import type { EventTime } from './eventTime';++/**+ * Request body creating a calendar event on the requester's calendar.+ */+export interface CreateCalendarEventRequest {+ /** Invited attendees. */+ attendees?: CalendarAttendeeInputBody[];+ /** Exact calendar to create the event on; takes precedence over the+inbox default. */+ calendarId?: CreateCalendarEventRequestCalendarId;+ /** Optional event body. */+ description?: CreateCalendarEventRequestDescription;+ /** Connected inbox whose primary calendar receives the event; defaults+to the requester's primary inbox. */+ emailLinkId?: CreateCalendarEventRequestEmailLinkId;+ /** Optional location label. */+ location?: CreateCalendarEventRequestLocation;+ /** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */+ recurrenceLines?: string[];+ /** Timed or all-day shape. */+ time: EventTime;+ /** Display title. */+ title: string;+ transparency?: CreateCalendarEventRequestTransparency;+ visibility?: CreateCalendarEventRequestVisibility;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestCalendarId.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestCalendarId.tsnew file mode 100644index 0000000000..ed9e8656b3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestCalendarId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Exact calendar to create the event on; takes precedence over the+inbox default.+ */+export type CreateCalendarEventRequestCalendarId = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestDescription.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestDescription.tsnew file mode 100644index 0000000000..e2959fc961--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional event body.+ */+export type CreateCalendarEventRequestDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestEmailLinkId.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestEmailLinkId.tsnew file mode 100644index 0000000000..0a87105d7e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestEmailLinkId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Connected inbox whose primary calendar receives the event; defaults+to the requester's primary inbox.+ */+export type CreateCalendarEventRequestEmailLinkId = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestLocation.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestLocation.tsnew file mode 100644index 0000000000..cfca0f26bc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestLocation.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional location label.+ */+export type CreateCalendarEventRequestLocation = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestTransparency.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestTransparency.tsnew file mode 100644index 0000000000..d57e28eedc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestTransparency.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTransparency } from './eventTransparency';++export type CreateCalendarEventRequestTransparency = null | EventTransparency;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestVisibility.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestVisibility.tsnew file mode 100644index 0000000000..7c8f142a65--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/createCalendarEventRequestVisibility.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventVisibility } from './eventVisibility';++export type CreateCalendarEventRequestVisibility = null | EventVisibility;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/deleteCalendarEventParams.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/deleteCalendarEventParams.tsnew file mode 100644index 0000000000..c014a40e12--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/deleteCalendarEventParams.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarDeletionScopeParam } from './calendarDeletionScopeParam';++export type DeleteCalendarEventParams = {+ /**+ * Deletion scope; defaults to the entire event or series.+ */+ scope?: CalendarDeletionScopeParam;+ /**+ * Original-start key of the occurrence a scoped deletion targets.+ */+ recurrenceId?: string;+};diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventStatus.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventStatus.tsnew file mode 100644index 0000000000..a5e423b0e8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventStatus.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Canonical event status.+ */+export type EventStatus = (typeof EventStatus)[keyof typeof EventStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventStatus = {+ confirmed: 'confirmed',+ tentative: 'tentative',+ cancelled: 'cancelled',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTime.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTime.tsnew file mode 100644index 0000000000..20dbe369a8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTime.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOf } from './eventTimeOneOf';+import type { EventTimeOneOfFour } from './eventTimeOneOfFour';++/**+ * The mutually exclusive time shape of a calendar event.++Fields are renamed per variant rather than with `rename_all_fields`+because utoipa only honors variant-level serde renames when it+derives the OpenAPI schema.+ */+export type EventTime = EventTimeOneOf | EventTimeOneOfFour;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOf.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOf.tsnew file mode 100644index 0000000000..8058d16278--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOf.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOfKind } from './eventTimeOneOfKind';+import type { EventTimeOneOfTimeZone } from './eventTimeOneOfTimeZone';++/**+ * An event with absolute instants.+ */+export type EventTimeOneOf = {+ /** Exclusive end instant. */+ endsAt: string;+ kind: EventTimeOneOfKind;+ /** Inclusive start instant. */+ startsAt: string;+ /** Original IANA time-zone identifier, when supplied. */+ timeZone?: EventTimeOneOfTimeZone;+};diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFour.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFour.tsnew file mode 100644index 0000000000..af3c5710d6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFour.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOfFourKind } from './eventTimeOneOfFourKind';++/**+ * An all-day event using RFC 5545's exclusive end date.+ */+export type EventTimeOneOfFour = {+ /** Exclusive local end date. */+ endDate: string;+ kind: EventTimeOneOfFourKind;+ /** Inclusive local start date. */+ startDate: string;+};diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFourKind.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFourKind.tsnew file mode 100644index 0000000000..1378cbe193--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfFourKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export type EventTimeOneOfFourKind =+ (typeof EventTimeOneOfFourKind)[keyof typeof EventTimeOneOfFourKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTimeOneOfFourKind = {+ allDay: 'allDay',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfKind.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfKind.tsnew file mode 100644index 0000000000..44ff8828ac--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export type EventTimeOneOfKind =+ (typeof EventTimeOneOfKind)[keyof typeof EventTimeOneOfKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTimeOneOfKind = {+ timed: 'timed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfTimeZone.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfTimeZone.tsnew file mode 100644index 0000000000..689decf704--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTimeOneOfTimeZone.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Original IANA time-zone identifier, when supplied.+ */+export type EventTimeOneOfTimeZone = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTransparency.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTransparency.tsnew file mode 100644index 0000000000..2e56bc579e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventTransparency.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether an event blocks availability.+ */+export type EventTransparency =+ (typeof EventTransparency)[keyof typeof EventTransparency];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTransparency = {+ opaque: 'opaque',+ transparent: 'transparent',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/eventVisibility.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventVisibility.tsnew file mode 100644index 0000000000..484bfaa051--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/eventVisibility.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Visibility of event details.+ */+export type EventVisibility =+ (typeof EventVisibility)[keyof typeof EventVisibility];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventVisibility = {+ default: 'default',+ public: 'public',+ private: 'private',+ confidential: 'confidential',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.tsindex eeac0afe76..8f53cc78b0 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts@@ -136,12 +136,27 @@ export * from './attachmentMimeType';export * from './attachmentProviderId';export * from './attachmentSfsId';export * from './attachmentSizeBytes';+export * from './attendeeResponseStatus';export * from './backfillJob';export * from './backfillJobLinkId';export * from './backfillJobStatus';export * from './backfillJobThreadsRequestedLimit';export * from './backfillStatus';export * from './blockSenderRequest';+export * from './calendarAttendee';+export * from './calendarAttendeeComment';+export * from './calendarAttendeeDisplayName';+export * from './calendarAttendeeInputBody';+export * from './calendarDeletionScopeParam';+export * from './calendarEvent';+export * from './calendarEventCalendarId';+export * from './calendarEventConferenceUrl';+export * from './calendarEventDescription';+export * from './calendarEventLocation';+export * from './calendarEventOrganizerEmail';+export * from './calendarEventOrganizerName';+export * from './calendarMutationApiError';+export * from './calendarMutationErrorCode';export * from './cancelBackfillParams';export * from './contact';export * from './contactEmailAddress';@@ -156,13 +171,30 @@ export * from './contactInfoWithInteractionAllOf';export * from './contactName';export * from './contactOriginalPhotoUrl';export * from './contactSfsPhotoUrl';+export * from './createCalendarEventRequest';+export * from './createCalendarEventRequestCalendarId';+export * from './createCalendarEventRequestDescription';+export * from './createCalendarEventRequestEmailLinkId';+export * from './createCalendarEventRequestLocation';+export * from './createCalendarEventRequestTransparency';+export * from './createCalendarEventRequestVisibility';export * from './createDraftRequest';export * from './createDraftRequestSendTime';export * from './createDraftResponse';export * from './createLabelRequest';export * from './createLabelResponse';+export * from './deleteCalendarEventParams';export * from './emptyResponse';export * from './errorResponse';+export * from './eventStatus';+export * from './eventTime';+export * from './eventTimeOneOf';+export * from './eventTimeOneOfFour';+export * from './eventTimeOneOfFourKind';+export * from './eventTimeOneOfKind';+export * from './eventTimeOneOfTimeZone';+export * from './eventTransparency';+export * from './eventVisibility';export * from './getActiveBackfillJobResponse';export * from './getAttachmentDocumentIDResponse';export * from './getAttachmentResponse';@@ -192,6 +224,7 @@ export * from './link';export * from './linkPhotoUrl';export * from './listBackfillJobsResponse';export * from './listBlockedResponse';+export * from './listCalendarsResponse';export * from './listContactsResponse';export * from './listContactsResponseContacts';export * from './listEmailFiltersResponse';@@ -241,6 +274,7 @@ export * from './refreshEmailEventOneOfSevenEvent';export * from './refreshEmailEventOneOfThree';export * from './refreshEmailEventOneOfThreeEvent';export * from './resyncResponse';+export * from './rsvpCalendarEventRequest';export * from './sendMessageRequest';export * from './sendMessageResponse';export * from './settings';@@ -266,6 +300,15 @@ export * from './threadProviderId';export * from './threadSummary';export * from './unblockSenderRequest';export * from './unresolvedSignatureImagesError';+export * from './updateCalendarEventRequest';+export * from './updateCalendarEventRequestAttendees';+export * from './updateCalendarEventRequestDescription';+export * from './updateCalendarEventRequestLocation';+export * from './updateCalendarEventRequestRecurrenceLines';+export * from './updateCalendarEventRequestTime';+export * from './updateCalendarEventRequestTitle';+export * from './updateCalendarEventRequestTransparency';+export * from './updateCalendarEventRequestVisibility';export * from './updateLabelBatchRequest';export * from './updateLabelBatchResponse';export * from './updateThreadLabelRequest';@@ -282,3 +325,5 @@ export * from './upsertScheduledRequest';export * from './upsertScheduledResponse';export * from './userProvider';export * from './value';+export * from './visibleCalendar';+export * from './visibleCalendarColor';diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/listCalendarsResponse.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/listCalendarsResponse.tsnew file mode 100644index 0000000000..3de414a77a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/listCalendarsResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { VisibleCalendar } from './visibleCalendar';++/**+ * Calendars visible to the requester across connected and delegated inboxes.+ */+export interface ListCalendarsResponse {+ /** Primaries and writable calendars first. */+ calendars: VisibleCalendar[];+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/rsvpCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/rsvpCalendarEventRequest.tsnew file mode 100644index 0000000000..da233e5cc6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/rsvpCalendarEventRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { AttendeeResponseStatus } from './attendeeResponseStatus';++/**+ * Request body setting the requester's RSVP on an event.+ */+export interface RsvpCalendarEventRequest {+ /** The response to record for the connected account. */+ response: AttendeeResponseStatus;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequest.tsnew file mode 100644index 0000000000..4b41f02427--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequest.ts@@ -0,0 +1,33 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateCalendarEventRequestAttendees } from './updateCalendarEventRequestAttendees';+import type { UpdateCalendarEventRequestDescription } from './updateCalendarEventRequestDescription';+import type { UpdateCalendarEventRequestLocation } from './updateCalendarEventRequestLocation';+import type { UpdateCalendarEventRequestRecurrenceLines } from './updateCalendarEventRequestRecurrenceLines';+import type { UpdateCalendarEventRequestTime } from './updateCalendarEventRequestTime';+import type { UpdateCalendarEventRequestTitle } from './updateCalendarEventRequestTitle';+import type { UpdateCalendarEventRequestTransparency } from './updateCalendarEventRequestTransparency';+import type { UpdateCalendarEventRequestVisibility } from './updateCalendarEventRequestVisibility';++/**+ * Request body patching an event; omitted fields are left untouched.+ */+export interface UpdateCalendarEventRequest {+ /** Replacement attendee list. */+ attendees?: UpdateCalendarEventRequestAttendees;+ /** Replacement description; an empty string clears it. */+ description?: UpdateCalendarEventRequestDescription;+ /** Replacement location; an empty string clears it. */+ location?: UpdateCalendarEventRequestLocation;+ /** Replacement recurrence properties; an empty list clears them. */+ recurrenceLines?: UpdateCalendarEventRequestRecurrenceLines;+ time?: UpdateCalendarEventRequestTime;+ /** Replacement title; an empty string clears it. */+ title?: UpdateCalendarEventRequestTitle;+ transparency?: UpdateCalendarEventRequestTransparency;+ visibility?: UpdateCalendarEventRequestVisibility;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestAttendees.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestAttendees.tsnew file mode 100644index 0000000000..b2f7407fa2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestAttendees.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarAttendeeInputBody } from './calendarAttendeeInputBody';++/**+ * Replacement attendee list.+ */+export type UpdateCalendarEventRequestAttendees =+ | CalendarAttendeeInputBody[]+ | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestDescription.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestDescription.tsnew file mode 100644index 0000000000..27b0309243--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Replacement description; an empty string clears it.+ */+export type UpdateCalendarEventRequestDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestLocation.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestLocation.tsnew file mode 100644index 0000000000..533041e3d7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestLocation.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Replacement location; an empty string clears it.+ */+export type UpdateCalendarEventRequestLocation = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestRecurrenceLines.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestRecurrenceLines.tsnew file mode 100644index 0000000000..4ab45282b3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestRecurrenceLines.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Replacement recurrence properties; an empty list clears them.+ */+export type UpdateCalendarEventRequestRecurrenceLines = string[] | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTime.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTime.tsnew file mode 100644index 0000000000..a28ef9af9b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTime.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTime } from './eventTime';++export type UpdateCalendarEventRequestTime = null | EventTime;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTitle.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTitle.tsnew file mode 100644index 0000000000..45bfc518b7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTitle.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Replacement title; an empty string clears it.+ */+export type UpdateCalendarEventRequestTitle = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTransparency.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTransparency.tsnew file mode 100644index 0000000000..6f3e0f5f05--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestTransparency.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTransparency } from './eventTransparency';++export type UpdateCalendarEventRequestTransparency = null | EventTransparency;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestVisibility.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestVisibility.tsnew file mode 100644index 0000000000..9fed15c341--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/updateCalendarEventRequestVisibility.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventVisibility } from './eventVisibility';++export type UpdateCalendarEventRequestVisibility = null | EventVisibility;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendar.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendar.tsnew file mode 100644index 0000000000..cc4ea1b802--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendar.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { VisibleCalendarColor } from './visibleCalendarColor';++/**+ * A calendar visible to a requester, listed for pickers and filters.+ */+export interface VisibleCalendar {+ /** Provider color. */+ color?: VisibleCalendarColor;+ /** Connected inbox address, for grouping in multi-inbox pickers. */+ emailAddress: string;+ /** Connected inbox that syncs this calendar. */+ emailLinkId: string;+ /** Persisted Macro calendar identifier. */+ id: string;+ /** Whether this is its account's primary calendar. */+ isPrimary: boolean;+ /** Whether the grant can create and modify events on this calendar. */+ isWritable: boolean;+ /** Provider display name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendarColor.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendarColor.tsnew file mode 100644index 0000000000..ea74a9b6bf--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/visibleCalendarColor.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider color.+ */+export type VisibleCalendarColor = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex 8825787b02..f3320ff972 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -10,6 +10,371 @@"version": "0.1.0"},"paths": {+ "/calendar/calendars": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "List the requester's visible calendars for pickers and filters.",+ "operationId": "list_calendars",+ "responses": {+ "200": {+ "description": "Calendars visible to the requester",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListCalendarsResponse"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "503": {+ "description": "Transient failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events": {+ "post": {+ "tags": ["calendar_events"],+ "summary": "Create a calendar event and return its synced entity.",+ "operationId": "create_calendar_event",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "The created calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "400": {+ "description": "Invalid event fields",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "No writable calendar or the provider rejected the event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events/{event_id}": {+ "delete": {+ "tags": ["calendar_events"],+ "summary": "Delete a calendar event at its provider.",+ "operationId": "delete_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "scope",+ "in": "query",+ "description": "Deletion scope; defaults to the entire event or series.",+ "required": false,+ "schema": {+ "$ref": "#/components/schemas/CalendarDeletionScopeParam"+ }+ },+ {+ "name": "recurrenceId",+ "in": "query",+ "description": "Original-start key of the occurrence a scoped deletion targets.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "The event was deleted"+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The provider rejected the deletion",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["calendar_events"],+ "summary": "Update fields of a calendar event and return its synced entity.",+ "operationId": "update_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The updated calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "400": {+ "description": "Invalid event fields",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The provider rejected the update",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events/{event_id}/rsvp": {+ "put": {+ "tags": ["calendar_events"],+ "summary": "Set the requester's RSVP on a calendar event and return its synced entity.",+ "operationId": "rsvp_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RsvpCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The updated calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The connected account is not an attendee",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },"/email/attachments/{id}": {"get": {"tags": ["Attachments"],@@ -3825,81 +4190,291 @@"type": ["string", "null"],"description": "The Gmail attachment ID for fetching data from Gmail API."},- "size_bytes": {- "type": ["integer", "null"],- "format": "int64",- "description": "File size in bytes."+ "size_bytes": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "File size in bytes."+ }+ }+ },+ "AttendeeResponseStatus": {+ "type": "string",+ "description": "RSVP state for an attendee.",+ "enum": ["needs_action", "accepted", "declined", "tentative"]+ },+ "BackfillJob": {+ "type": "object",+ "required": [+ "id",+ "fusionauth_user_id",+ "total_threads",+ "status",+ "threads_retrieved_count",+ "created_at",+ "updated_at"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "format": "date-time"+ },+ "fusionauth_user_id": {+ "type": "string"+ },+ "id": {+ "type": "string",+ "format": "uuid"+ },+ "link_id": {+ "type": ["string", "null"],+ "format": "uuid"+ },+ "status": {+ "$ref": "#/components/schemas/BackfillJobStatus"+ },+ "threads_requested_limit": {+ "type": ["integer", "null"],+ "format": "int32"+ },+ "threads_retrieved_count": {+ "type": "integer",+ "format": "int32"+ },+ "total_threads": {+ "type": "integer",+ "format": "int32"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time"+ }+ }+ },+ "BackfillJobStatus": {+ "type": "string",+ "enum": ["Init", "InProgress", "Complete", "Cancelled", "Failed"]+ },+ "BackfillStatus": {+ "type": "string",+ "description": "Progress/terminal state of a backfill job for [`RefreshEmailEvent::Backfill`].",+ "enum": ["progress", "complete", "failed"]+ },+ "BlockSenderRequest": {+ "type": "object",+ "description": "Request to block a sender.",+ "required": ["email_address"],+ "properties": {+ "email_address": {+ "type": "string",+ "description": "The email address of the sender to block."+ }+ }+ },+ "CalendarAttendee": {+ "type": "object",+ "description": "An attendee on a calendar event.",+ "required": [+ "email",+ "responseStatus",+ "isOrganizer",+ "isOptional",+ "isSelf"+ ],+ "properties": {+ "comment": {+ "type": ["string", "null"],+ "description": "Optional attendee comment."+ },+ "displayName": {+ "type": ["string", "null"],+ "description": "Provider display name."+ },+ "email": {+ "type": "string",+ "description": "Normalized email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."+ },+ "isOrganizer": {+ "type": "boolean",+ "description": "Whether this attendee is the organizer."+ },+ "isSelf": {+ "type": "boolean",+ "description": "Whether this attendee represents the connected account."+ },+ "responseStatus": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "RSVP state."+ }+ }+ },+ "CalendarAttendeeInputBody": {+ "type": "object",+ "description": "An attendee supplied to a calendar mutation.",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "Attendee email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."}}},- "BackfillJob": {+ "CalendarDeletionScopeParam": {+ "type": "string",+ "description": "How much of a recurring series a deletion removes.",+ "enum": ["all", "this_event", "this_and_following"]+ },+ "CalendarEvent": {"type": "object",+ "description": "A stable, first-class Macro calendar event entity.","required": ["id",- "fusionauth_user_id",- "total_threads",+ "ownerId",+ "icalUid",+ "title","status",- "threads_retrieved_count",- "created_at",- "updated_at"+ "visibility",+ "transparency",+ "time",+ "recurrenceLines",+ "sequence",+ "isReadOnly",+ "attendees",+ "createdAt",+ "updatedAt"],"properties": {- "created_at": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees, keyed by email during persistence."+ },+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Direct join URL when known."+ },+ "createdAt": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "Entity creation time."},- "fusionauth_user_id": {- "type": "string"+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "icalUid": {+ "type": "string",+ "description": "RFC 5545 UID used to reconcile provider and email sources."},"id": {"type": "string",- "format": "uuid"+ "format": "uuid",+ "description": "Macro entity identifier."},- "link_id": {+ "isReadOnly": {+ "type": "boolean",+ "description": "Whether the current user can edit the canonical source."+ },+ "location": {"type": ["string", "null"],- "format": "uuid"+ "description": "Optional physical or virtual location label."},- "status": {- "$ref": "#/components/schemas/BackfillJobStatus"+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer email."},- "threads_requested_limit": {- "type": ["integer", "null"],- "format": "int32"+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer display name."},- "threads_retrieved_count": {- "type": "integer",- "format": "int32"+ "ownerId": {+ "type": "string",+ "description": "Macro user who owns this event entity."},- "total_threads": {+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "sequence": {"type": "integer",- "format": "int32"+ "format": "int32",+ "description": "Provider/iCalendar sequence number.",+ "minimum": 0},- "updated_at": {+ "status": {+ "$ref": "#/components/schemas/EventStatus",+ "description": "Event status."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {"type": "string",- "format": "date-time"+ "description": "Display title."+ },+ "transparency": {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity update time."+ },+ "visibility": {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."}}},- "BackfillJobStatus": {- "type": "string",- "enum": ["Init", "InProgress", "Complete", "Cancelled", "Failed"]- },- "BackfillStatus": {- "type": "string",- "description": "Progress/terminal state of a backfill job for [`RefreshEmailEvent::Backfill`].",- "enum": ["progress", "complete", "failed"]- },- "BlockSenderRequest": {+ "CalendarMutationApiError": {"type": "object",- "description": "Request to block a sender.",- "required": ["email_address"],+ "description": "HTTP error body returned by calendar mutation endpoints.",+ "required": ["code", "message"],"properties": {- "email_address": {+ "code": {+ "$ref": "#/components/schemas/CalendarMutationErrorCode",+ "description": "Machine-readable failure category."+ },+ "message": {"type": "string",- "description": "The email address of the sender to block."+ "description": "Human-readable failure description."}}},+ "CalendarMutationErrorCode": {+ "type": "string",+ "description": "Machine-readable failure category for calendar mutations.",+ "enum": [+ "not_found",+ "read_only",+ "no_writable_calendar",+ "not_attendee",+ "invalid_input",+ "reauth_required",+ "provider_rejected",+ "retryable",+ "persist_failed"+ ]+ },"CancelBackfillParams": {"type": "object","required": ["job_id"],@@ -3986,6 +4561,75 @@}]},+ "CreateCalendarEventRequest": {+ "type": "object",+ "description": "Request body creating a calendar event on the requester's calendar.",+ "required": ["title", "time"],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"+ },+ "description": "Invited attendees."+ },+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Exact calendar to create the event on; takes precedence over the\ninbox default."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "emailLinkId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Connected inbox whose primary calendar receives the event; defaults\nto the requester's primary inbox."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Optional location label."+ },+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ },+ "transparency": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ }+ ]+ },+ "visibility": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."+ }+ ]+ }+ }+ },"CreateDraftRequest": {"type": "object","description": "Request body for creating a draft.",@@ -4048,6 +4692,72 @@}}},+ "EventStatus": {+ "type": "string",+ "description": "Canonical event status.",+ "enum": ["confirmed", "tentative", "cancelled"]+ },+ "EventTime": {+ "oneOf": [+ {+ "type": "object",+ "description": "An event with absolute instants.",+ "required": ["startsAt", "endsAt", "kind"],+ "properties": {+ "endsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Exclusive end instant."+ },+ "kind": {+ "type": "string",+ "enum": ["timed"]+ },+ "startsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Inclusive start instant."+ },+ "timeZone": {+ "type": ["string", "null"],+ "description": "Original IANA time-zone identifier, when supplied."+ }+ }+ },+ {+ "type": "object",+ "description": "An all-day event using RFC 5545's exclusive end date.",+ "required": ["startDate", "endDate", "kind"],+ "properties": {+ "endDate": {+ "type": "string",+ "format": "date",+ "description": "Exclusive local end date."+ },+ "kind": {+ "type": "string",+ "enum": ["allDay"]+ },+ "startDate": {+ "type": "string",+ "format": "date",+ "description": "Inclusive local start date."+ }+ }+ }+ ],+ "description": "The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema."+ },+ "EventTransparency": {+ "type": "string",+ "description": "Whether an event blocks availability.",+ "enum": ["opaque", "transparent"]+ },+ "EventVisibility": {+ "type": "string",+ "description": "Visibility of event details.",+ "enum": ["default", "public", "private", "confidential"]+ },"GetActiveBackfillJobResponse": {"type": "object","description": "The response returned from the get backfill job endpoint",@@ -4337,6 +5047,20 @@}}},+ "ListCalendarsResponse": {+ "type": "object",+ "description": "Calendars visible to the requester across connected and delegated inboxes.",+ "required": ["calendars"],+ "properties": {+ "calendars": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/VisibleCalendar"+ },+ "description": "Primaries and writable calendars first."+ }+ }+ },"ListContactsResponse": {"type": "object","required": ["contacts"],@@ -4839,6 +5563,17 @@}}},+ "RsvpCalendarEventRequest": {+ "type": "object",+ "description": "Request body setting the requester's RSVP on an event.",+ "required": ["response"],+ "properties": {+ "response": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "The response to record for the connected account."+ }+ }+ },"SendMessageRequest": {"type": "object","description": "Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).",@@ -5090,6 +5825,71 @@}}},+ "UpdateCalendarEventRequest": {+ "type": "object",+ "description": "Request body patching an event; omitted fields are left untouched.",+ "properties": {+ "attendees": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"+ },+ "description": "Replacement attendee list."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Replacement description; an empty string clears it."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Replacement location; an empty string clears it."+ },+ "recurrenceLines": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Replacement recurrence properties; an empty list clears them."+ },+ "time": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTime",+ "description": "Replacement time."+ }+ ]+ },+ "title": {+ "type": ["string", "null"],+ "description": "Replacement title; an empty string clears it."+ },+ "transparency": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Replacement transparency."+ }+ ]+ },+ "visibility": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Replacement visibility."+ }+ ]+ }+ }+ },"UpdateLabelBatchRequest": {"type": "object","required": ["message_ids", "label_id", "value"],@@ -5250,7 +6050,51 @@"type": "string","enum": ["GMAIL"]},- "Value": {}+ "Value": {},+ "VisibleCalendar": {+ "type": "object",+ "description": "A calendar visible to a requester, listed for pickers and filters.",+ "required": [+ "id",+ "emailLinkId",+ "emailAddress",+ "name",+ "isPrimary",+ "isWritable"+ ],+ "properties": {+ "color": {+ "type": ["string", "null"],+ "description": "Provider color."+ },+ "emailAddress": {+ "type": "string",+ "description": "Connected inbox address, for grouping in multi-inbox pickers."+ },+ "emailLinkId": {+ "type": "string",+ "format": "uuid",+ "description": "Connected inbox that syncs this calendar."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Persisted Macro calendar identifier."+ },+ "isPrimary": {+ "type": "boolean",+ "description": "Whether this is its account's primary calendar."+ },+ "isWritable": {+ "type": "boolean",+ "description": "Whether the grant can create and modify events on this calendar."+ },+ "name": {+ "type": "string",+ "description": "Provider display name."+ }+ }+ }}},"tags": [diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.tsindex 6f5ac4a17d..e385589940 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { CalendarAttendee } from './calendarAttendee';+import type { CalendarEventCalendarId } from './calendarEventCalendarId';import type { CalendarEventConferenceUrl } from './calendarEventConferenceUrl';import type { CalendarEventDescription } from './calendarEventDescription';import type { CalendarEventLocation } from './calendarEventLocation';@@ -21,6 +22,9 @@ import type { EventVisibility } from './eventVisibility';export interface CalendarEvent {/** Attendees, keyed by email during persistence. */attendees: CalendarAttendee[];+ /** Calendar the canonical source belongs to, when known. Absent only in+projections stored before calendars were attributed. */+ calendarId?: CalendarEventCalendarId;/** Direct join URL when known. */conferenceUrl?: CalendarEventConferenceUrl;/** Entity creation time. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventCalendarId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventCalendarId.tsnew file mode 100644index 0000000000..fe32309cea--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventCalendarId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Calendar the canonical source belongs to, when known. Absent only in+projections stored before calendars were attributed.+ */+export type CalendarEventCalendarId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 0984c781b4..610a7cbfe5 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -166,6 +166,7 @@ export * from './calendarAttendee';export * from './calendarAttendeeComment';export * from './calendarAttendeeDisplayName';export * from './calendarEvent';+export * from './calendarEventCalendarId';export * from './calendarEventConferenceUrl';export * from './calendarEventDescription';export * from './calendarEventFilters';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 8bd2a63531..5293e44c8e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -967,6 +967,12 @@ export const listOccurrencesResponse = zod.describe('An attendee on a calendar event.')).describe('Attendees, keyed by email during persistence.'),+ calendarId: zod+ .uuid()+ .nullish()+ .describe(+ 'Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed.'+ ),conferenceUrl: zod.string().nullish()diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 3d6b191fa9..c586734d05 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -12766,6 +12766,11 @@},"description": "Attendees, keyed by email during persistence."},+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed."+ },"conferenceUrl": {"type": ["string", "null"],"description": "Direct join URL when known."diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rsindex 810bb6ecda..b7bde29f85 100644--- a/crates/calendar_events/src/domain/mod.rs+++ b/crates/calendar_events/src/domain/mod.rs@@ -2,6 +2,8 @@/// Domain models.pub mod models;+/// User-initiated calendar mutation policy.+pub mod mutations;/// Domain ports.pub mod ports;/// Calendar business policy.diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex cd66bb6c81..242aef1081 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -255,6 +255,10 @@ pub struct CalendarEvent {pub owner_id: String,/// RFC 5545 UID used to reconcile provider and email sources.pub ical_uid: String,+ /// Calendar the canonical source belongs to, when known. Absent only in+ /// projections stored before calendars were attributed.+ #[serde(default)]+ pub calendar_id: Option<Uuid>,/// Display title.pub title: String,/// Optional event body.@@ -518,6 +522,198 @@ pub struct CalendarEventUpsert {pub occurrences: Vec<CalendarOccurrence>,}+/// Stable identity of one provider calendar targeted by a sync or mutation.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GoogleCalendarTarget {+ /// Macro user who owns the resulting entities.+ pub owner_id: String,+ /// Connected inbox whose grant authorizes the request.+ pub email_link_id: Uuid,+ /// Calendar account persisted for the connected inbox.+ pub account_id: Uuid,+ /// Persisted Macro calendar identifier.+ pub calendar_id: Uuid,+ /// Provider calendar identifier used in Google API paths.+ pub provider_calendar_id: String,+ /// Whether the provider role prohibits event mutation.+ pub is_read_only: bool,+ /// Occurrence window to materialize.+ pub range: OccurrenceRange,+}++/// An attendee supplied to a user-initiated event mutation.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarAttendeeInput {+ /// Attendee email address.+ pub email: String,+ /// Whether attendance is optional.+ pub is_optional: bool,+}++/// User-supplied fields for a new provider event.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarEventDraft {+ /// Display title.+ pub title: String,+ /// Optional event body.+ pub description: Option<String>,+ /// Optional location label.+ pub location: Option<String>,+ /// Timed or all-day shape.+ pub time: EventTime,+ /// Invited attendees.+ pub attendees: Vec<CalendarAttendeeInput>,+ /// Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ pub recurrence_lines: Vec<String>,+ /// Event visibility.+ pub visibility: Option<EventVisibility>,+ /// Availability behavior.+ pub transparency: Option<EventTransparency>,+}++/// User-supplied changes to an existing provider event. `None` fields are+/// left untouched at the provider; `Some` fields replace the stored value.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct CalendarEventPatch {+ /// Replacement title.+ pub title: Option<String>,+ /// Replacement description; an empty string clears it.+ pub description: Option<String>,+ /// Replacement location; an empty string clears it.+ pub location: Option<String>,+ /// Replacement time.+ pub time: Option<EventTime>,+ /// Replacement attendee list.+ pub attendees: Option<Vec<CalendarAttendeeInput>>,+ /// Replacement recurrence properties; an empty list clears them.+ pub recurrence_lines: Option<Vec<String>>,+ /// Replacement visibility.+ pub visibility: Option<EventVisibility>,+ /// Replacement transparency.+ pub transparency: Option<EventTransparency>,+}++impl CalendarEventPatch {+ /// Whether the patch changes anything at all.+ pub fn is_empty(&self) -> bool {+ self == &Self::default()+ }+}++/// OAuth identity used to mint an access token for a connected inbox.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarLinkTokenIdentity {+ /// FusionAuth user holding the refresh token.+ pub fusionauth_user_id: String,+ /// Connected inbox address.+ pub email_address: String,+ /// Provider discriminator stored on the link.+ pub provider: String,+}++/// Everything a user mutation needs to address an event at its provider.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarEventMutationTarget {+ /// Macro entity identifier.+ pub event_id: Uuid,+ /// Whether the canonical source prohibits mutation.+ pub is_read_only: bool,+ /// Google event identifier of the best-ranked provider source.+ pub provider_event_id: String,+ /// Recurring master identifier when the stored source is an instance.+ pub provider_recurring_event_id: Option<String>,+ /// Provider calendar identity for the mutation request.+ pub owner_id: String,+ /// Connected inbox whose grant authorizes the request.+ pub email_link_id: Uuid,+ /// Calendar account persisted for the connected inbox.+ pub account_id: Uuid,+ /// Persisted Macro calendar identifier.+ pub calendar_id: Uuid,+ /// Provider calendar identifier used in Google API paths.+ pub provider_calendar_id: String,+ /// Token identity of the connected inbox.+ pub token_identity: CalendarLinkTokenIdentity,+}++impl CalendarEventMutationTarget {+ /// Provider identifier the mutation must address: the recurring master+ /// when the stored source is an expanded instance acting as canonical.+ pub fn master_provider_event_id(&self) -> &str {+ self.provider_recurring_event_id+ .as_deref()+ .unwrap_or(&self.provider_event_id)+ }++ /// Build the provider target for a mutation over the supplied window.+ pub fn google_target(&self, range: OccurrenceRange) -> GoogleCalendarTarget {+ GoogleCalendarTarget {+ owner_id: self.owner_id.clone(),+ email_link_id: self.email_link_id,+ account_id: self.account_id,+ calendar_id: self.calendar_id,+ provider_calendar_id: self.provider_calendar_id.clone(),+ is_read_only: self.is_read_only,+ range,+ }+ }+}++/// A calendar visible to a requester, listed for pickers and filters.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct VisibleCalendar {+ /// Persisted Macro calendar identifier.+ pub id: Uuid,+ /// Connected inbox that syncs this calendar.+ pub email_link_id: Uuid,+ /// Connected inbox address, for grouping in multi-inbox pickers.+ pub email_address: String,+ /// Provider display name.+ pub name: String,+ /// Provider color.+ pub color: Option<String>,+ /// Whether this is its account's primary calendar.+ pub is_primary: bool,+ /// Whether the grant can create and modify events on this calendar.+ pub is_writable: bool,+}++/// The writable calendar a new user-created event lands in.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarCreationTarget {+ /// Macro user who will own the created entity.+ pub owner_id: String,+ /// Connected inbox whose grant authorizes the request.+ pub email_link_id: Uuid,+ /// Calendar account persisted for the connected inbox.+ pub account_id: Uuid,+ /// Persisted Macro calendar identifier.+ pub calendar_id: Uuid,+ /// Provider calendar identifier used in Google API paths.+ pub provider_calendar_id: String,+ /// Whether the provider role prohibits event creation.+ pub is_read_only: bool,+ /// Token identity of the connected inbox.+ pub token_identity: CalendarLinkTokenIdentity,+}++impl CalendarCreationTarget {+ /// Build the provider target for a creation over the supplied window.+ pub fn google_target(&self, range: OccurrenceRange) -> GoogleCalendarTarget {+ GoogleCalendarTarget {+ owner_id: self.owner_id.clone(),+ email_link_id: self.email_link_id,+ account_id: self.account_id,+ calendar_id: self.calendar_id,+ provider_calendar_id: self.provider_calendar_id.clone(),+ is_read_only: self.is_read_only,+ range,+ }+ }+}+/// Persisted state needed to choose an incremental or full provider sync.#[derive(Clone, Debug, PartialEq, Eq)]pub struct StoredGoogleCalendar {diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rsnew file mode 100644index 0000000000..42c3741a31--- /dev/null+++ b/crates/calendar_events/src/domain/mutations.rs@@ -0,0 +1,350 @@+//! User-initiated calendar mutation policy.+//!+//! Mutations write through to the provider first — Google stays the write+//! authority, exactly as ingestion assumes — and then persist the provider's+//! normalized echo through the same upsert path sync uses, so the local+//! projection is read-your-writes fresh and the next incremental sync+//! no-ops on the idempotency short-circuit.++use chrono::Utc;+use uuid::Uuid;++use super::{+ models::{+ AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventMutationTarget,+ CalendarEventPatch, CalendarEventUpsert, EventTime, OccurrenceRange,+ },+ ports::{+ CalendarAccessTokenProvider, CalendarDeletionScope, CalendarEventWrite,+ CalendarMutationError, CalendarMutationService, CalendarRepository, CalendarTokenError,+ GoogleCalendarMutationProvider, GoogleProviderError, GoogleProviderErrorKind,+ GoogleRsvpOutcome, GoogleSeriesMutationOutcome,+ },+};++/// Calendar mutation use cases with provider, token, and persistence+/// details behind ports.+pub struct CalendarMutationServiceImpl<R, G, T> {+ repository: R,+ provider: G,+ tokens: T,+}++impl<R, G, T> CalendarMutationServiceImpl<R, G, T>+where+ R: CalendarRepository,+ G: GoogleCalendarMutationProvider,+ T: CalendarAccessTokenProvider,+{+ /// Construct the service from its ports.+ pub fn new(repository: R, provider: G, tokens: T) -> Self {+ Self {+ repository,+ provider,+ tokens,+ }+ }++ async fn resolve_mutation_target(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<CalendarEventMutationTarget, CalendarMutationError> {+ self.repository+ .get_event_mutation_target(requester_id, event_id)+ .await+ .map_err(internal)?+ .ok_or(CalendarMutationError::NotFound)+ }++ async fn fetch_token(+ &self,+ target_identity: &super::models::CalendarLinkTokenIdentity,+ ) -> Result<String, CalendarMutationError> {+ self.tokens+ .fetch_access_token(target_identity)+ .await+ .map_err(|error| match error {+ CalendarTokenError::ReauthRequired(message) => {+ CalendarMutationError::ReauthRequired(message)+ }+ CalendarTokenError::Transient(message) => CalendarMutationError::Retryable(message),+ })+ }++ /// Persist the provider echo and return the canonical event with its+ /// applied entity id.+ async fn persist_echo(+ &self,+ upsert: CalendarEventUpsert,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ let mut event = upsert.event.clone();+ let event_id = self+ .repository+ .upsert_event(CalendarEventWrite::UserMutation(upsert))+ .await+ .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;+ event.id = event_id;+ Ok(event)+ }+}++impl<R, G, T> CalendarMutationService for CalendarMutationServiceImpl<R, G, T>+where+ R: CalendarRepository,+ G: GoogleCalendarMutationProvider,+ T: CalendarAccessTokenProvider,+{+ #[tracing::instrument(skip(self, requester_id, draft), err)]+ async fn create_event(+ &self,+ requester_id: &str,+ email_link_id: Option<Uuid>,+ calendar_id: Option<Uuid>,+ draft: CalendarEventDraft,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ validate_time(&draft.time)?;+ validate_attendee_emails(draft.attendees.iter().map(|attendee| &attendee.email))?;+ let target = self+ .repository+ .get_creation_target(requester_id, email_link_id, calendar_id)+ .await+ .map_err(internal)?+ .ok_or(CalendarMutationError::NoWritableCalendar)?;+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ let access_token = self.fetch_token(&target.token_identity).await?;+ let upsert = self+ .provider+ .create_event(+ &access_token,+ &target.google_target(OccurrenceRange::maintenance_horizon(Utc::now())),+ &draft,+ )+ .await+ .map_err(provider_error)?;+ self.persist_echo(upsert).await+ }++ #[tracing::instrument(skip(self, requester_id, patch), err)]+ async fn update_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ patch: CalendarEventPatch,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ if patch.is_empty() {+ return Err(CalendarMutationError::InvalidInput(+ "the patch changes nothing".to_string(),+ ));+ }+ if let Some(time) = &patch.time {+ validate_time(time)?;+ }+ if let Some(attendees) = &patch.attendees {+ validate_attendee_emails(attendees.iter().map(|attendee| &attendee.email))?;+ }+ let target = self.resolve_mutation_target(requester_id, event_id).await?;+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ let access_token = self.fetch_token(&target.token_identity).await?;+ let updated = self+ .provider+ .update_event(+ &access_token,+ &target.google_target(OccurrenceRange::maintenance_horizon(Utc::now())),+ target.master_provider_event_id(),+ &patch,+ )+ .await+ .map_err(provider_error)?;+ let Some(upsert) = updated else {+ // The provider no longer has the event; retire the stale local+ // source the same way a feed tombstone would.+ self.retire_gone_source(&target).await;+ return Err(CalendarMutationError::NotFound);+ };+ self.persist_echo(upsert).await+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn delete_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ scope: CalendarDeletionScope,+ ) -> Result<(), CalendarMutationError> {+ let target = self.resolve_mutation_target(requester_id, event_id).await?;+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ let access_token = self.fetch_token(&target.token_identity).await?;+ let google_target = target.google_target(OccurrenceRange::maintenance_horizon(Utc::now()));+ let outcome = match &scope {+ CalendarDeletionScope::All => {+ self.provider+ .delete_event(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ )+ .await+ .map_err(provider_error)?;+ GoogleSeriesMutationOutcome::SeriesDeleted+ }+ CalendarDeletionScope::ThisEvent { recurrence_id } => self+ .provider+ .delete_event_instance(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ recurrence_id,+ )+ .await+ .map_err(provider_error)?,+ CalendarDeletionScope::ThisAndFollowing { recurrence_id } => self+ .provider+ .truncate_recurring_event(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ recurrence_id,+ )+ .await+ .map_err(provider_error)?,+ };+ match outcome {+ GoogleSeriesMutationOutcome::Applied(upsert) => {+ self.persist_echo(*upsert).await.map(|_| ())+ }+ // Either the deletion removed the series or it was already+ // gone; retiring the local source converges both.+ GoogleSeriesMutationOutcome::SeriesDeleted | GoogleSeriesMutationOutcome::Gone => self+ .repository+ .remove_google_source(+ target.account_id,+ target.calendar_id,+ target.master_provider_event_id(),+ )+ .await+ .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}"))),+ }+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn respond_to_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ response: AttendeeResponseStatus,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ let target = self.resolve_mutation_target(requester_id, event_id).await?;+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ let access_token = self.fetch_token(&target.token_identity).await?;+ let outcome = self+ .provider+ .rsvp_event(+ &access_token,+ &target.google_target(OccurrenceRange::maintenance_horizon(Utc::now())),+ target.master_provider_event_id(),+ &target.token_identity.email_address,+ response,+ )+ .await+ .map_err(provider_error)?;+ match outcome {+ GoogleRsvpOutcome::Applied(upsert) => self.persist_echo(*upsert).await,+ GoogleRsvpOutcome::NotAttendee => Err(CalendarMutationError::NotAttendee),+ GoogleRsvpOutcome::Gone => {+ self.retire_gone_source(&target).await;+ Err(CalendarMutationError::NotFound)+ }+ }+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn list_visible_calendars(+ &self,+ requester_id: &str,+ ) -> Result<Vec<super::models::VisibleCalendar>, CalendarMutationError> {+ self.repository+ .list_visible_calendars(requester_id)+ .await+ .map_err(internal)+ }+}++impl<R, G, T> CalendarMutationServiceImpl<R, G, T>+where+ R: CalendarRepository,+ G: GoogleCalendarMutationProvider,+ T: CalendarAccessTokenProvider,+{+ /// Best-effort cleanup when the provider reports the event gone: the+ /// regular sync converges the projection either way.+ async fn retire_gone_source(&self, target: &CalendarEventMutationTarget) {+ self.repository+ .remove_google_source(+ target.account_id,+ target.calendar_id,+ target.master_provider_event_id(),+ )+ .await+ .inspect_err(|error| {+ tracing::warn!(+ error=?error,+ event_id=%target.event_id,+ "failed to retire a provider-deleted calendar event source"+ );+ })+ .ok();+ }+}++fn validate_time(time: &EventTime) -> Result<(), CalendarMutationError> {+ if !time.is_valid() {+ return Err(CalendarMutationError::InvalidInput(+ "event end must be after its start".to_string(),+ ));+ }+ Ok(())+}++fn validate_attendee_emails<'a>(+ emails: impl Iterator<Item = &'a String>,+) -> Result<(), CalendarMutationError> {+ for email in emails {+ let trimmed = email.trim();+ if trimmed.is_empty() || !trimmed.contains('@') {+ return Err(CalendarMutationError::InvalidInput(format!(+ "invalid attendee email: {email:?}"+ )));+ }+ }+ Ok(())+}++fn provider_error(error: GoogleProviderError) -> CalendarMutationError {+ match error.kind() {+ GoogleProviderErrorKind::ReauthRequired => {+ CalendarMutationError::ReauthRequired(error.to_string())+ }+ GoogleProviderErrorKind::Transient | GoogleProviderErrorKind::SyncTokenExpired => {+ CalendarMutationError::Retryable(error.to_string())+ }+ GoogleProviderErrorKind::Permanent => {+ CalendarMutationError::ProviderRejected(error.to_string())+ }+ }+}++fn internal(error: rootcause::Report) -> CalendarMutationError {+ CalendarMutationError::Retryable(format!("{error:?}"))+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsnew file mode 100644index 0000000000..cfc12714bc--- /dev/null+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -0,0 +1,805 @@+use super::*;+use crate::domain::models::{+ AppliedGoogleGrant, CalendarAttendeeInput, CalendarBackfillJobKey, CalendarCreationTarget,+ CalendarEventSource, CalendarLinkTokenIdentity, CalendarOccurrence, CalendarOccurrenceCursor,+ CalendarSyncStatus, EventStatus, EventTransparency, EventVisibility,+ GoogleCalendarSyncSnapshot, GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel,+ ProviderCalendar, StoredGoogleCalendar,+};+use chrono::{Duration, TimeZone};+use std::sync::{Arc, Mutex};++fn token_identity() -> CalendarLinkTokenIdentity {+ CalendarLinkTokenIdentity {+ fusionauth_user_id: "fusion-user".to_string(),+ email_address: "[email protected]".to_string(),+ provider: "GMAIL".to_string(),+ }+}++fn mutation_target(is_read_only: bool) -> CalendarEventMutationTarget {+ CalendarEventMutationTarget {+ event_id: Uuid::now_v7(),+ is_read_only,+ provider_event_id: "instance-id".to_string(),+ provider_recurring_event_id: Some("master-id".to_string()),+ owner_id: "macro|[email protected]".to_string(),+ email_link_id: Uuid::now_v7(),+ account_id: Uuid::now_v7(),+ calendar_id: Uuid::now_v7(),+ provider_calendar_id: "primary".to_string(),+ token_identity: token_identity(),+ }+}++fn creation_target(is_read_only: bool) -> CalendarCreationTarget {+ CalendarCreationTarget {+ owner_id: "macro|[email protected]".to_string(),+ email_link_id: Uuid::now_v7(),+ account_id: Uuid::now_v7(),+ calendar_id: Uuid::now_v7(),+ provider_calendar_id: "primary".to_string(),+ is_read_only,+ token_identity: token_identity(),+ }+}++fn timed_time() -> EventTime {+ let starts_at = Utc.with_ymd_and_hms(2026, 8, 6, 14, 0, 0).unwrap();+ EventTime::Timed {+ starts_at,+ ends_at: starts_at + Duration::hours(1),+ time_zone: Some("UTC".to_string()),+ }+}++fn echo_upsert(target_owner: &str) -> CalendarEventUpsert {+ let id = Uuid::now_v7();+ CalendarEventUpsert {+ event: CalendarEvent {+ id,+ owner_id: target_owner.to_string(),+ ical_uid: "[email protected]".to_string(),+ calendar_id: Some(Uuid::now_v7()),+ title: "Echo".to_string(),+ description: None,+ location: None,+ status: EventStatus::Confirmed,+ visibility: EventVisibility::Default,+ transparency: EventTransparency::Opaque,+ time: timed_time(),+ recurrence_lines: Vec::new(),+ organizer_email: None,+ organizer_name: None,+ conference_url: None,+ sequence: 0,+ is_read_only: false,+ attendees: Vec::new(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ },+ source: CalendarEventSource::Google(GoogleEventSource {+ email_link_id: Uuid::now_v7(),+ account_id: Uuid::now_v7(),+ calendar_id: Uuid::now_v7(),+ provider_event_id: "echo-id".to_string(),+ provider_recurring_event_id: None,+ provider_etag: None,+ raw_payload: serde_json::json!({}),+ }),+ overrides: Vec::new(),+ occurrences: Vec::new(),+ }+}++fn draft() -> CalendarEventDraft {+ CalendarEventDraft {+ title: "New event".to_string(),+ description: None,+ location: None,+ time: timed_time(),+ attendees: vec![CalendarAttendeeInput {+ email: "[email protected]".to_string(),+ is_optional: false,+ }],+ recurrence_lines: Vec::new(),+ visibility: None,+ transparency: None,+ }+}++#[derive(Clone, Default)]+struct FakeRepo {+ mutation_target: Option<CalendarEventMutationTarget>,+ creation_target: Option<CalendarCreationTarget>,+ persisted_event_id: Option<Uuid>,+ upserts: Arc<Mutex<Vec<CalendarEventUpsert>>>,+ removed_sources: Arc<Mutex<Vec<(Uuid, Uuid, String)>>>,+}++impl CalendarRepository for FakeRepo {+ async fn apply_google_grant(+ &self,+ _email_link_id: Uuid,+ _scopes: crate::domain::models::GoogleScopeSet,+ ) -> Result<AppliedGoogleGrant, rootcause::Report> {+ unreachable!()+ }++ async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, rootcause::Report> {+ let CalendarEventWrite::UserMutation(upsert) = write else {+ panic!("mutations must persist through the UserMutation authority");+ };+ self.upserts.lock().unwrap().push(upsert);+ Ok(self.persisted_event_id.unwrap_or_else(Uuid::now_v7))+ }++ async fn list_occurrences(+ &self,+ _requester_id: &str,+ _range: OccurrenceRange,+ _cursor: Option<CalendarOccurrenceCursor>,+ _limit: u16,+ ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, rootcause::Report> {+ unreachable!()+ }++ async fn sync_status(+ &self,+ _requester_id: &str,+ ) -> Result<CalendarSyncStatus, rootcause::Report> {+ unreachable!()+ }++ async fn upsert_google_calendar(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _calendar: ProviderCalendar,+ ) -> Result<StoredGoogleCalendar, rootcause::Report> {+ unreachable!()+ }++ async fn commit_google_calendar_sync(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _sync: GoogleCalendarSyncSnapshot,+ _events_upserted: usize,+ ) -> Result<(), rootcause::Report> {+ unreachable!()+ }++ async fn record_watch_channel(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _calendar_id: Uuid,+ _channel: GoogleWatchChannel,+ ) -> Result<(), rootcause::Report> {+ unreachable!()+ }++ async fn find_watch_target(+ &self,+ _channel_id: &str,+ _resource_id: &str,+ ) -> Result<Option<Uuid>, rootcause::Report> {+ unreachable!()+ }++ async fn schedule_google_sync_for_link(+ &self,+ _email_link_id: Uuid,+ ) -> Result<bool, rootcause::Report> {+ Ok(true)+ }++ async fn reconcile_google_calendar_list(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _calendar_ids: Vec<Uuid>,+ ) -> Result<(), rootcause::Report> {+ unreachable!()+ }++ async fn get_event_mutation_target(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Option<CalendarEventMutationTarget>, rootcause::Report> {+ Ok(self.mutation_target.clone())+ }++ async fn get_creation_target(+ &self,+ _requester_id: &str,+ _email_link_id: Option<Uuid>,+ _calendar_id: Option<Uuid>,+ ) -> Result<Option<CalendarCreationTarget>, rootcause::Report> {+ Ok(self.creation_target.clone())+ }++ async fn list_visible_calendars(+ &self,+ _requester_id: &str,+ ) -> Result<Vec<crate::domain::models::VisibleCalendar>, rootcause::Report> {+ Ok(Vec::new())+ }++ async fn remove_google_source(+ &self,+ account_id: Uuid,+ calendar_id: Uuid,+ provider_event_id: &str,+ ) -> Result<(), rootcause::Report> {+ self.removed_sources.lock().unwrap().push((+ account_id,+ calendar_id,+ provider_event_id.to_string(),+ ));+ Ok(())+ }+}++#[derive(Clone)]+enum FakeProviderBehavior {+ Echo,+ Gone,+ NotAttendee,+ Fail(GoogleProviderErrorKind),+}++#[derive(Clone)]+struct FakeProvider {+ behavior: FakeProviderBehavior,+ calls: Arc<Mutex<Vec<String>>>,+}++impl FakeProvider {+ fn new(behavior: FakeProviderBehavior) -> Self {+ Self {+ behavior,+ calls: Arc::new(Mutex::new(Vec::new())),+ }+ }++ fn fail(&self) -> Option<GoogleProviderError> {+ match &self.behavior {+ FakeProviderBehavior::Fail(kind) => {+ Some(GoogleProviderError::new(*kind, "provider says no"))+ }+ _ => None,+ }+ }+}++impl GoogleCalendarMutationProvider for FakeProvider {+ async fn create_event(+ &self,+ _access_token: &str,+ target: &GoogleCalendarTarget,+ _draft: &CalendarEventDraft,+ ) -> Result<CalendarEventUpsert, GoogleProviderError> {+ self.calls.lock().unwrap().push("create".to_string());+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(echo_upsert(&target.owner_id))+ }++ async fn update_event(+ &self,+ _access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ _patch: &CalendarEventPatch,+ ) -> Result<Option<CalendarEventUpsert>, GoogleProviderError> {+ self.calls+ .lock()+ .unwrap()+ .push(format!("update:{provider_event_id}"));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ if matches!(self.behavior, FakeProviderBehavior::Gone) {+ return Ok(None);+ }+ Ok(Some(echo_upsert(&target.owner_id)))+ }++ async fn delete_event(+ &self,+ _access_token: &str,+ _target: &GoogleCalendarTarget,+ provider_event_id: &str,+ ) -> Result<(), GoogleProviderError> {+ self.calls+ .lock()+ .unwrap()+ .push(format!("delete:{provider_event_id}"));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(())+ }++ async fn delete_event_instance(+ &self,+ _access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> Result<GoogleSeriesMutationOutcome, GoogleProviderError> {+ self.calls.lock().unwrap().push(format!(+ "instance:{master_provider_event_id}:{original_start}"+ ));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(match self.behavior {+ FakeProviderBehavior::Gone => GoogleSeriesMutationOutcome::Gone,+ _ => GoogleSeriesMutationOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),+ })+ }++ async fn truncate_recurring_event(+ &self,+ _access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> Result<GoogleSeriesMutationOutcome, GoogleProviderError> {+ self.calls.lock().unwrap().push(format!(+ "truncate:{master_provider_event_id}:{original_start}"+ ));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(match self.behavior {+ FakeProviderBehavior::Gone => GoogleSeriesMutationOutcome::SeriesDeleted,+ _ => GoogleSeriesMutationOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),+ })+ }++ async fn rsvp_event(+ &self,+ _access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ _self_email: &str,+ _response: AttendeeResponseStatus,+ ) -> Result<GoogleRsvpOutcome, GoogleProviderError> {+ self.calls+ .lock()+ .unwrap()+ .push(format!("rsvp:{provider_event_id}"));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(match self.behavior {+ FakeProviderBehavior::Gone => GoogleRsvpOutcome::Gone,+ FakeProviderBehavior::NotAttendee => GoogleRsvpOutcome::NotAttendee,+ _ => GoogleRsvpOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),+ })+ }+}++#[derive(Clone)]+struct FakeTokens {+ error: Option<fn() -> CalendarTokenError>,+}++impl FakeTokens {+ fn ok() -> Self {+ Self { error: None }+ }++ fn reauth() -> Self {+ Self {+ error: Some(|| CalendarTokenError::ReauthRequired("grant revoked".to_string())),+ }+ }+}++impl CalendarAccessTokenProvider for FakeTokens {+ async fn fetch_access_token(+ &self,+ _identity: &CalendarLinkTokenIdentity,+ ) -> Result<String, CalendarTokenError> {+ match self.error {+ Some(make_error) => Err(make_error()),+ None => Ok("access-token".to_string()),+ }+ }+}++fn service(+ repo: FakeRepo,+ provider: FakeProvider,+ tokens: FakeTokens,+) -> CalendarMutationServiceImpl<FakeRepo, FakeProvider, FakeTokens> {+ CalendarMutationServiceImpl::new(repo, provider, tokens)+}++#[tokio::test]+async fn create_requires_a_writable_calendar() {+ let missing = service(+ FakeRepo::default(),+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ );+ assert!(matches!(+ missing+ .create_event("macro|user", None, None, draft())+ .await,+ Err(CalendarMutationError::NoWritableCalendar)+ ));++ let read_only = service(+ FakeRepo {+ creation_target: Some(creation_target(true)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ );+ assert!(matches!(+ read_only+ .create_event("macro|user", None, None, draft())+ .await,+ Err(CalendarMutationError::ReadOnly)+ ));+}++#[tokio::test]+async fn create_persists_the_provider_echo_and_returns_the_applied_id() {+ let applied_id = Uuid::now_v7();+ let repo = FakeRepo {+ creation_target: Some(creation_target(false)),+ persisted_event_id: Some(applied_id),+ ..FakeRepo::default()+ };+ let upserts = repo.upserts.clone();+ let created = service(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ )+ .create_event("macro|user", None, None, draft())+ .await+ .unwrap();++ assert_eq!(created.id, applied_id);+ assert_eq!(upserts.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn create_rejects_invalid_input_before_reaching_the_provider() {+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ let svc = service(+ FakeRepo {+ creation_target: Some(creation_target(false)),+ ..FakeRepo::default()+ },+ provider,+ FakeTokens::ok(),+ );++ let mut inverted = draft();+ let starts_at = Utc.with_ymd_and_hms(2026, 8, 6, 14, 0, 0).unwrap();+ inverted.time = EventTime::Timed {+ starts_at,+ ends_at: starts_at - Duration::hours(1),+ time_zone: None,+ };+ assert!(matches!(+ svc.create_event("macro|user", None, None, inverted).await,+ Err(CalendarMutationError::InvalidInput(_))+ ));++ let mut bad_email = draft();+ bad_email.attendees[0].email = "not-an-email".to_string();+ assert!(matches!(+ svc.create_event("macro|user", None, None, bad_email).await,+ Err(CalendarMutationError::InvalidInput(_))+ ));+ assert!(calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn update_validates_lookup_policy_and_addresses_the_series_master() {+ let empty_patch = service(+ FakeRepo::default(),+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ );+ assert!(matches!(+ empty_patch+ .update_event("macro|user", Uuid::now_v7(), CalendarEventPatch::default())+ .await,+ Err(CalendarMutationError::InvalidInput(_))+ ));++ let patch = CalendarEventPatch {+ title: Some("Renamed".to_string()),+ ..CalendarEventPatch::default()+ };++ let not_found = service(+ FakeRepo::default(),+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ );+ assert!(matches!(+ not_found+ .update_event("macro|user", Uuid::now_v7(), patch.clone())+ .await,+ Err(CalendarMutationError::NotFound)+ ));++ let read_only = service(+ FakeRepo {+ mutation_target: Some(mutation_target(true)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ );+ assert!(matches!(+ read_only+ .update_event("macro|user", Uuid::now_v7(), patch.clone())+ .await,+ Err(CalendarMutationError::ReadOnly)+ ));++ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ service(+ FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ },+ provider,+ FakeTokens::ok(),+ )+ .update_event("macro|user", Uuid::now_v7(), patch)+ .await+ .unwrap();+ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["update:master-id"],+ "instance-backed targets patch their recurring master"+ );+}++#[tokio::test]+async fn update_on_a_provider_deleted_event_retires_the_stale_source() {+ let repo = FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ };+ let removed = repo.removed_sources.clone();+ let result = service(+ repo,+ FakeProvider::new(FakeProviderBehavior::Gone),+ FakeTokens::ok(),+ )+ .update_event(+ "macro|user",+ Uuid::now_v7(),+ CalendarEventPatch {+ title: Some("Renamed".to_string()),+ ..CalendarEventPatch::default()+ },+ )+ .await;++ assert!(matches!(result, Err(CalendarMutationError::NotFound)));+ let removed = removed.lock().unwrap();+ assert_eq!(removed.len(), 1);+ assert_eq!(removed[0].2, "master-id");+}++#[tokio::test]+async fn delete_pushes_to_the_provider_then_retires_the_local_source() {+ let repo = FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ };+ let removed = repo.removed_sources.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .delete_event("macro|user", Uuid::now_v7(), CalendarDeletionScope::All)+ .await+ .unwrap();++ assert_eq!(calls.lock().unwrap().as_slice(), ["delete:master-id"]);+ assert_eq!(removed.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn rsvp_surfaces_attendance_and_persists_the_echo() {+ let not_attendee = service(+ FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::NotAttendee),+ FakeTokens::ok(),+ );+ assert!(matches!(+ not_attendee+ .respond_to_event(+ "macro|user",+ Uuid::now_v7(),+ AttendeeResponseStatus::Accepted+ )+ .await,+ Err(CalendarMutationError::NotAttendee)+ ));++ let repo = FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ };+ let upserts = repo.upserts.clone();+ service(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ )+ .respond_to_event(+ "macro|user",+ Uuid::now_v7(),+ AttendeeResponseStatus::Declined,+ )+ .await+ .unwrap();+ assert_eq!(upserts.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn token_and_provider_failures_map_to_typed_errors() {+ let reauth = service(+ FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::reauth(),+ );+ assert!(matches!(+ reauth+ .delete_event("macro|user", Uuid::now_v7(), CalendarDeletionScope::All)+ .await,+ Err(CalendarMutationError::ReauthRequired(_))+ ));++ let transient = service(+ FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::Fail(+ GoogleProviderErrorKind::Transient,+ )),+ FakeTokens::ok(),+ );+ assert!(matches!(+ transient+ .delete_event("macro|user", Uuid::now_v7(), CalendarDeletionScope::All)+ .await,+ Err(CalendarMutationError::Retryable(_))+ ));++ let permanent = service(+ FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ },+ FakeProvider::new(FakeProviderBehavior::Fail(+ GoogleProviderErrorKind::Permanent,+ )),+ FakeTokens::ok(),+ );+ assert!(matches!(+ permanent+ .delete_event("macro|user", Uuid::now_v7(), CalendarDeletionScope::All)+ .await,+ Err(CalendarMutationError::ProviderRejected(_))+ ));+}++#[test]+fn empty_patch_is_detected() {+ assert!(CalendarEventPatch::default().is_empty());+ assert!(+ !CalendarEventPatch {+ title: Some("t".to_string()),+ ..CalendarEventPatch::default()+ }+ .is_empty()+ );+}++#[tokio::test]+async fn scoped_deletions_reshape_or_retire_the_series() {+ let repo = FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ };+ let upserts = repo.upserts.clone();+ let removed = repo.removed_sources.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ let svc = service(repo, provider, FakeTokens::ok());++ svc.delete_event(+ "macro|user",+ Uuid::now_v7(),+ CalendarDeletionScope::ThisEvent {+ recurrence_id: "2026-08-10T09:00:00+00:00".to_string(),+ },+ )+ .await+ .unwrap();+ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["instance:master-id:2026-08-10T09:00:00+00:00"],+ "single-occurrence deletions address the recurring master"+ );+ assert_eq!(+ upserts.lock().unwrap().len(),+ 1,+ "the surviving series echo is persisted"+ );+ assert!(removed.lock().unwrap().is_empty());++ svc.delete_event(+ "macro|user",+ Uuid::now_v7(),+ CalendarDeletionScope::ThisAndFollowing {+ recurrence_id: "2026-08-12T09:00:00+00:00".to_string(),+ },+ )+ .await+ .unwrap();+ assert_eq!(upserts.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn truncation_that_empties_the_series_retires_the_local_source() {+ let repo = FakeRepo {+ mutation_target: Some(mutation_target(false)),+ ..FakeRepo::default()+ };+ let upserts = repo.upserts.clone();+ let removed = repo.removed_sources.clone();+ let svc = service(+ repo,+ FakeProvider::new(FakeProviderBehavior::Gone),+ FakeTokens::ok(),+ );++ svc.delete_event(+ "macro|user",+ Uuid::now_v7(),+ CalendarDeletionScope::ThisAndFollowing {+ recurrence_id: "2026-08-04T09:00:00+00:00".to_string(),+ },+ )+ .await+ .unwrap();++ assert!(upserts.lock().unwrap().is_empty());+ assert_eq!(removed.lock().unwrap().len(), 1);+}diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex c18265456b..4c58278f3f 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -7,11 +7,13 @@ use rootcause::Report;use uuid::Uuid;use super::models::{- AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,- CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEvent, CalendarEventUpsert,- CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus, GoogleCalendarSyncSnapshot,+ AppliedGoogleGrant, AttendeeResponseStatus, CalendarBackfillClaim,+ CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,+ CalendarCreationTarget, CalendarEvent, CalendarEventDraft, CalendarEventMutationTarget,+ CalendarEventPatch, CalendarEventUpsert, CalendarLinkTokenIdentity, CalendarOccurrence,+ CalendarOccurrenceCursor, CalendarSyncStatus, GoogleCalendarSyncSnapshot, GoogleCalendarTarget,GoogleEventSyncBatch, GoogleScopeSet, GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig,- OccurrenceRange, ProviderCalendar, StoredGoogleCalendar,+ OccurrenceRange, ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,};/// Classification supplied by provider adapters to backfill policy.@@ -53,20 +55,8 @@ impl GoogleProviderError {/// Stable identifiers and sync policy for one provider calendar fetch.#[derive(Clone, Debug, PartialEq, Eq)]pub struct GoogleEventSyncContext {- /// Macro user who owns the resulting entities.- pub owner_id: String,- /// Connected inbox whose grant authorizes the request.- pub email_link_id: Uuid,- /// Calendar account persisted for the connected inbox.- pub account_id: Uuid,- /// Persisted Macro calendar identifier.- pub calendar_id: Uuid,- /// Provider calendar identifier used in Google API paths.- pub provider_calendar_id: String,- /// Whether the provider role prohibits event mutation.- pub is_read_only: bool,- /// Occurrence window to materialize.- pub range: OccurrenceRange,+ /// Calendar identity and materialization window.+ pub target: GoogleCalendarTarget,/// Last continuation token committed for this provider calendar.pub sync_token: Option<String>,/// Domain-chosen reconciliation mode for this run.@@ -84,11 +74,140 @@ pub enum CalendarEventWrite {/// Normalized provider event.upsert: CalendarEventUpsert,},+ /// Provider echo of a user-initiated mutation the caller already+ /// authorized. Unfenced: Google acknowledged the write, so persisting+ /// its response races sync only through the per-event advisory lock.+ UserMutation(CalendarEventUpsert),/// Unfenced persistence used only by PostgreSQL adapter fixtures.#[cfg(test)]Fixture(CalendarEventUpsert),}+/// Classified failure minting an access token for a connected inbox.+#[derive(Debug, thiserror::Error)]+pub enum CalendarTokenError {+ /// The grant is invalid, revoked, or missing the calendar capability.+ #[error("calendar access token requires reauthorization: {0}")]+ ReauthRequired(String),+ /// Transport or infrastructure failure that may recover.+ #[error("calendar access token fetch failed transiently: {0}")]+ Transient(String),+}++/// Access-token acquisition for provider calls made outside backfill workers.+pub trait CalendarAccessTokenProvider: Send + Sync + 'static {+ /// Mint or reuse an access token for the connected inbox.+ fn fetch_access_token(+ &self,+ identity: &CalendarLinkTokenIdentity,+ ) -> impl Future<Output = Result<String, CalendarTokenError>> + Send;+}++/// Provider write operations used by user-initiated calendar mutations.+///+/// Every method that changes provider state returns the normalized echo of+/// the affected event so the caller can persist read-your-writes state; the+/// adapter owns recurrence expansion by refreshing changed series bounded to+/// the target's window, exactly like ingestion.+pub trait GoogleCalendarMutationProvider: Send + Sync + 'static {+ /// Insert a new event into the target calendar.+ fn create_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ draft: &CalendarEventDraft,+ ) -> impl Future<Output = Result<CalendarEventUpsert, GoogleProviderError>> + Send;++ /// Patch the supplied fields of an existing event. Returns `None` when+ /// the event no longer exists at the provider.+ fn update_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ patch: &CalendarEventPatch,+ ) -> impl Future<Output = Result<Option<CalendarEventUpsert>, GoogleProviderError>> + Send;++ /// Delete an event. An event already gone at the provider is success.+ fn delete_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ ) -> impl Future<Output = Result<(), GoogleProviderError>> + Send;++ /// Delete one occurrence of a recurring series, identified by its+ /// original start key, then refresh the series. An occurrence already+ /// gone at the provider refreshes without deleting.+ fn delete_event_instance(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> impl Future<Output = Result<GoogleSeriesMutationOutcome, GoogleProviderError>> + Send;++ /// End a recurring series just before the identified occurrence,+ /// deleting the series outright when nothing would remain.+ fn truncate_recurring_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> impl Future<Output = Result<GoogleSeriesMutationOutcome, GoogleProviderError>> + Send;++ /// Set the connected account's own RSVP on an event. An event that no+ /// longer exists at the provider surfaces as [`GoogleRsvpOutcome::Gone`];+ /// absence of a self attendee surfaces as+ /// [`GoogleRsvpOutcome::NotAttendee`].+ fn rsvp_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ self_email: &str,+ response: AttendeeResponseStatus,+ ) -> impl Future<Output = Result<GoogleRsvpOutcome, GoogleProviderError>> + Send;+}++/// How much of a recurring series a deletion removes.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum CalendarDeletionScope {+ /// The entire event or series.+ All,+ /// One occurrence, identified by its original start key.+ ThisEvent {+ /// Stable original-start key of the occurrence.+ recurrence_id: String,+ },+ /// The identified occurrence and everything after it.+ ThisAndFollowing {+ /// Stable original-start key of the first removed occurrence.+ recurrence_id: String,+ },+}++/// Result of a provider mutation that reshapes a recurring series.+pub enum GoogleSeriesMutationOutcome {+ /// The series survives; the echo carries its refreshed state.+ Applied(Box<CalendarEventUpsert>),+ /// The provider no longer has any of the series.+ SeriesDeleted,+ /// The series master vanished before the mutation could apply.+ Gone,+}++/// Result of attempting to set the connected account's RSVP.+pub enum GoogleRsvpOutcome {+ /// The RSVP was applied; the echo carries the refreshed event.+ Applied(Box<CalendarEventUpsert>),+ /// The connected account is not an attendee of the event.+ NotAttendee,+ /// The event no longer exists at the provider.+ Gone,+}+/// Inbound service port for querying calendar occurrence projections.pub trait CalendarOccurrenceService: Send + Sync + 'static {/// Return occurrences visible to a requester in a bounded viewport.@@ -194,6 +313,119 @@ pub trait CalendarRepository: Send + Sync + 'static {account_id: Uuid,calendar_ids: Vec<Uuid>,) -> impl Future<Output = Result<(), Report>> + Send;++ /// Resolve an event visible to the requester to its best Google source+ /// and the connected inbox that can mutate it. `None` covers both an+ /// unknown event and one the requester cannot see.+ fn get_event_mutation_target(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Option<CalendarEventMutationTarget>, Report>> + Send;++ /// Resolve the calendar a requester-created event lands in: the exact+ /// calendar when one is supplied, otherwise the supplied inbox's primary+ /// calendar, otherwise the requester's primary inbox's primary calendar.+ fn get_creation_target(+ &self,+ requester_id: &str,+ email_link_id: Option<Uuid>,+ calendar_id: Option<Uuid>,+ ) -> impl Future<Output = Result<Option<CalendarCreationTarget>, Report>> + Send;++ /// List every calendar visible to the requester across owned and+ /// delegated inboxes, primaries and writables first.+ fn list_visible_calendars(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<Vec<VisibleCalendar>, Report>> + Send;++ /// Retire a Google source the provider confirmed deleted (a recurring+ /// master also retires its expanded instances), restoring the best+ /// surviving source or removing the entity, mirroring feed tombstones.+ fn remove_google_source(+ &self,+ account_id: Uuid,+ calendar_id: Uuid,+ provider_event_id: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Inbound service port for user-initiated calendar event mutations.+pub trait CalendarMutationService: Send + Sync + 'static {+ /// Create an event on the selected calendar — or the requester's (or+ /// the supplied inbox's) primary calendar — and persist the provider echo.+ fn create_event(+ &self,+ requester_id: &str,+ email_link_id: Option<Uuid>,+ calendar_id: Option<Uuid>,+ draft: CalendarEventDraft,+ ) -> impl Future<Output = Result<CalendarEvent, CalendarMutationError>> + Send;++ /// List the calendars the requester can see, flagged for writability.+ fn list_visible_calendars(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<Vec<VisibleCalendar>, CalendarMutationError>> + Send;++ /// Patch an event at its provider and persist the echo.+ fn update_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ patch: CalendarEventPatch,+ ) -> impl Future<Output = Result<CalendarEvent, CalendarMutationError>> + Send;++ /// Delete an event at its provider — entirely, one occurrence, or from+ /// an occurrence onward — and reconcile the local projection.+ fn delete_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ scope: CalendarDeletionScope,+ ) -> impl Future<Output = Result<(), CalendarMutationError>> + Send;++ /// Set the requester's inbox RSVP on an event and persist the echo.+ fn respond_to_event(+ &self,+ requester_id: &str,+ event_id: Uuid,+ response: AttendeeResponseStatus,+ ) -> impl Future<Output = Result<CalendarEvent, CalendarMutationError>> + Send;+}++/// Use-case failures surfaced by calendar mutations.+#[derive(Debug, thiserror::Error)]+pub enum CalendarMutationError {+ /// The event does not exist or is not visible to the requester.+ #[error("calendar event was not found")]+ NotFound,+ /// The containing calendar prohibits mutation.+ #[error("calendar event is read-only")]+ ReadOnly,+ /// No writable calendar exists for the requester to create events in.+ #[error("no connected calendar can accept new events")]+ NoWritableCalendar,+ /// The connected account is not an attendee of the event.+ #[error("the connected account is not an attendee of this event")]+ NotAttendee,+ /// The supplied fields were invalid.+ #[error("invalid calendar mutation: {0}")]+ InvalidInput(String),+ /// The provider grant must be refreshed by the user.+ #[error("calendar mutation requires reauthorization: {0}")]+ ReauthRequired(String),+ /// The provider rejected the mutation permanently.+ #[error("calendar provider rejected the mutation: {0}")]+ ProviderRejected(String),+ /// Provider or infrastructure failure that may recover on retry.+ #[error("calendar mutation failed transiently: {0}")]+ Retryable(String),+ /// Persistence failed after the provider accepted the mutation; sync+ /// will converge the local projection.+ #[error("calendar mutation was applied but local persistence failed: {0}")]+ PersistFailed(String),}/// Provider API operations used by the Google backfill adapter.diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex 31815d8ced..bad6e504fa 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -468,13 +468,15 @@ where.sync_events(access_token,GoogleEventSyncContext {- owner_id: owner_id.to_string(),- email_link_id: key.email_link_id,- account_id,- calendar_id,- provider_calendar_id,- is_read_only,- range: range.clone(),+ target: super::models::GoogleCalendarTarget {+ owner_id: owner_id.to_string(),+ email_link_id: key.email_link_id,+ account_id,+ calendar_id,+ provider_calendar_id,+ is_read_only,+ range: range.clone(),+ },sync_token: stored_calendar.sync_token,plan,},diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 22a6d7ea58..3e065280eb 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -2,11 +2,12 @@ use super::*;use crate::domain::{models::{AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,- CalendarBackfillFailureDisposition, CalendarBackfillJobKey, CalendarEvent,- CalendarEventSource, CalendarOccurrence, CalendarSyncStatus, EventStatus, EventTime,- EventTransparency, EventVisibility, GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot,- GoogleEventSource, GoogleEventSyncBatch, GoogleWatchChannel, GoogleWatchConfig,- ProviderCalendar, StoredGoogleCalendar,+ CalendarBackfillFailureDisposition, CalendarBackfillJobKey, CalendarCreationTarget,+ CalendarEvent, CalendarEventMutationTarget, CalendarEventSource, CalendarOccurrence,+ CalendarSyncStatus, EventStatus, EventTime, EventTransparency, EventVisibility,+ GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSource,+ GoogleEventSyncBatch, GoogleWatchChannel, GoogleWatchConfig, ProviderCalendar,+ StoredGoogleCalendar,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarRepository, GoogleCalendarProvider,@@ -34,6 +35,7 @@ impl CalendarRepository for FakeRepo {async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, Report> {let upsert = match write {CalendarEventWrite::GoogleBackfill { upsert, .. }+ | CalendarEventWrite::UserMutation(upsert)| CalendarEventWrite::Fixture(upsert) => upsert,};let id = upsert.event.id;@@ -55,6 +57,39 @@ impl CalendarRepository for FakeRepo {Ok(CalendarSyncStatus::Ready)}+ async fn get_event_mutation_target(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Option<CalendarEventMutationTarget>, Report> {+ unreachable!("mutation lookups are not exercised by sync tests")+ }++ async fn get_creation_target(+ &self,+ _requester_id: &str,+ _email_link_id: Option<Uuid>,+ _calendar_id: Option<Uuid>,+ ) -> Result<Option<CalendarCreationTarget>, Report> {+ unreachable!("mutation lookups are not exercised by sync tests")+ }++ async fn list_visible_calendars(+ &self,+ _requester_id: &str,+ ) -> Result<Vec<crate::domain::models::VisibleCalendar>, Report> {+ unreachable!("mutation lookups are not exercised by sync tests")+ }++ async fn remove_google_source(+ &self,+ _account_id: Uuid,+ _calendar_id: Uuid,+ _provider_event_id: &str,+ ) -> Result<(), Report> {+ unreachable!("mutation cleanup is not exercised by sync tests")+ }+async fn upsert_google_calendar(&self,_key: CalendarBackfillJobKey,@@ -125,6 +160,7 @@ fn valid_upsert() -> CalendarEventUpsert {id: event_id,owner_id: "macro|[email protected]".to_string(),ical_uid: "[email protected]".to_string(),+ calendar_id: None,title: "Meeting".to_string(),description: None,location: None,@@ -226,7 +262,7 @@ impl GoogleCalendarProvider for FakeGoogleProvider {upserts: Vec::new(),observed_provider_event_ids: Some(Vec::new()),next_sync_token: "next".to_string(),- materialized_range: Some(context.range),+ materialized_range: Some(context.target.range),cancelled_provider_event_ids: Vec::new(),})}diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rsindex 0eb86f5ada..84e18b1b71 100644--- a/crates/calendar_events/src/inbound/mod.rs+++ b/crates/calendar_events/src/inbound/mod.rs@@ -3,3 +3,7 @@/// Axum routes for authenticated calendar queries.#[cfg(feature = "inbound")]pub mod axum_router;++/// Axum routes for authenticated calendar event mutations.+#[cfg(feature = "inbound")]+pub mod mutation_router;diff --git a/crates/calendar_events/src/inbound/mutation_router.rs b/crates/calendar_events/src/inbound/mutation_router.rsnew file mode 100644index 0000000000..16901d83e4--- /dev/null+++ b/crates/calendar_events/src/inbound/mutation_router.rs@@ -0,0 +1,529 @@+//! Axum router for user-initiated calendar event mutations.+//!+//! Handlers are thin: they parse transport DTOs, forward the authenticated+//! requester to the domain mutation service, and map domain errors to HTTP+//! semantics. Authorization and business policy live in the domain layer.++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::{get, patch, post, put},+};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,+};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::domain::{+ models::{+ AttendeeResponseStatus, CalendarAttendeeInput, CalendarEvent, CalendarEventDraft,+ CalendarEventPatch, EventTime, EventTransparency, EventVisibility, VisibleCalendar,+ },+ ports::{CalendarDeletionScope, CalendarMutationError, CalendarMutationService},+};++/// Router state for authenticated calendar mutations.+pub struct CalendarMutationRouterState<S, Auth> {+ service: Arc<S>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Auth> Clone for CalendarMutationRouterState<S, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: Arc::clone(&self.service),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S, Auth> CalendarMutationRouterState<S, Auth> {+ /// Create router state from a shared mutation service and authorization state.+ pub fn new(service: Arc<S>, authorization_state: MacroAuthorizationState<Auth>) -> Self {+ Self {+ service,+ authorization_state,+ }+ }+}++impl<S, Auth> FromRef<CalendarMutationRouterState<S, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &CalendarMutationRouterState<S, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Build the authenticated calendar mutation router, exposing `/calendars`+/// and `/events` (mounted under `/calendar` by the service).+pub fn calendar_mutation_router<S, Auth, T>(+ state: CalendarMutationRouterState<S, Auth>,+) -> Router<T>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/calendars", get(list_calendars::<S, Auth>))+ .route("/events", post(create_calendar_event::<S, Auth>))+ .route(+ "/events/{event_id}",+ patch(update_calendar_event::<S, Auth>).delete(delete_calendar_event::<S, Auth>),+ )+ .route(+ "/events/{event_id}/rsvp",+ put(rsvp_calendar_event::<S, Auth>),+ )+ .with_state(state)+}++/// An attendee supplied to a calendar mutation.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CalendarAttendeeInputBody {+ /// Attendee email address.+ pub email: String,+ /// Whether attendance is optional.+ #[serde(default)]+ pub is_optional: bool,+}++impl From<CalendarAttendeeInputBody> for CalendarAttendeeInput {+ fn from(body: CalendarAttendeeInputBody) -> Self {+ Self {+ email: body.email,+ is_optional: body.is_optional,+ }+ }+}++/// Request body creating a calendar event on the requester's calendar.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateCalendarEventRequest {+ /// Exact calendar to create the event on; takes precedence over the+ /// inbox default.+ pub calendar_id: Option<Uuid>,+ /// Connected inbox whose primary calendar receives the event; defaults+ /// to the requester's primary inbox.+ pub email_link_id: Option<Uuid>,+ /// Display title.+ pub title: String,+ /// Optional event body.+ pub description: Option<String>,+ /// Optional location label.+ pub location: Option<String>,+ /// Timed or all-day shape.+ pub time: EventTime,+ /// Invited attendees.+ #[serde(default)]+ pub attendees: Vec<CalendarAttendeeInputBody>,+ /// Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ #[serde(default)]+ pub recurrence_lines: Vec<String>,+ /// Event visibility.+ pub visibility: Option<EventVisibility>,+ /// Availability behavior.+ pub transparency: Option<EventTransparency>,+}++/// Request body patching an event; omitted fields are left untouched.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UpdateCalendarEventRequest {+ /// Replacement title; an empty string clears it.+ pub title: Option<String>,+ /// Replacement description; an empty string clears it.+ pub description: Option<String>,+ /// Replacement location; an empty string clears it.+ pub location: Option<String>,+ /// Replacement time.+ pub time: Option<EventTime>,+ /// Replacement attendee list.+ pub attendees: Option<Vec<CalendarAttendeeInputBody>>,+ /// Replacement recurrence properties; an empty list clears them.+ pub recurrence_lines: Option<Vec<String>>,+ /// Replacement visibility.+ pub visibility: Option<EventVisibility>,+ /// Replacement transparency.+ pub transparency: Option<EventTransparency>,+}++/// How much of a recurring series a deletion removes.+#[derive(Clone, Copy, Debug, Default, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CalendarDeletionScopeParam {+ /// The entire event or series.+ #[default]+ All,+ /// One occurrence.+ ThisEvent,+ /// One occurrence and everything after it.+ ThisAndFollowing,+}++/// Query selecting how much of a recurring series a deletion removes.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Query)]+#[serde(rename_all = "camelCase")]+pub struct DeleteCalendarEventQuery {+ /// Deletion scope; defaults to the entire event or series.+ #[serde(default)]+ pub scope: CalendarDeletionScopeParam,+ /// Original-start key of the occurrence a scoped deletion targets.+ pub recurrence_id: Option<String>,+}++/// Request body setting the requester's RSVP on an event.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct RsvpCalendarEventRequest {+ /// The response to record for the connected account.+ pub response: AttendeeResponseStatus,+}++/// Machine-readable failure category for calendar mutations.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CalendarMutationErrorCode {+ /// The event does not exist or is not visible to the requester.+ NotFound,+ /// The containing calendar prohibits mutation.+ ReadOnly,+ /// No connected calendar can accept new events.+ NoWritableCalendar,+ /// The connected account is not an attendee of the event.+ NotAttendee,+ /// The request was invalid.+ InvalidInput,+ /// The calendar grant must be re-consented.+ ReauthRequired,+ /// The provider rejected the mutation.+ ProviderRejected,+ /// A transient failure; the mutation can be retried.+ Retryable,+ /// The provider applied the mutation but local persistence lagged;+ /// refetching converges.+ PersistFailed,+}++/// HTTP error body returned by calendar mutation endpoints.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct CalendarMutationApiError {+ /// Machine-readable failure category.+ pub code: CalendarMutationErrorCode,+ /// Human-readable failure description.+ pub message: String,+ #[serde(skip)]+ status: StatusCode,+}++impl std::fmt::Display for CalendarMutationApiError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(&self.message)+ }+}++impl IntoResponse for CalendarMutationApiError {+ fn into_response(self) -> Response {+ (self.status, Json(&self)).into_response()+ }+}++impl From<CalendarMutationError> for CalendarMutationApiError {+ fn from(error: CalendarMutationError) -> Self {+ let (status, code, message) = match &error {+ CalendarMutationError::NotFound => (+ StatusCode::NOT_FOUND,+ CalendarMutationErrorCode::NotFound,+ "calendar event was not found".to_string(),+ ),+ CalendarMutationError::ReadOnly => (+ StatusCode::FORBIDDEN,+ CalendarMutationErrorCode::ReadOnly,+ "this calendar is read-only".to_string(),+ ),+ CalendarMutationError::NoWritableCalendar => (+ StatusCode::CONFLICT,+ CalendarMutationErrorCode::NoWritableCalendar,+ "no connected calendar can accept new events".to_string(),+ ),+ CalendarMutationError::NotAttendee => (+ StatusCode::CONFLICT,+ CalendarMutationErrorCode::NotAttendee,+ "the connected account is not an attendee of this event".to_string(),+ ),+ CalendarMutationError::InvalidInput(message) => (+ StatusCode::BAD_REQUEST,+ CalendarMutationErrorCode::InvalidInput,+ message.clone(),+ ),+ CalendarMutationError::ReauthRequired(_) => (+ StatusCode::FORBIDDEN,+ CalendarMutationErrorCode::ReauthRequired,+ "calendar access must be re-authorized".to_string(),+ ),+ CalendarMutationError::ProviderRejected(message) => (+ StatusCode::CONFLICT,+ CalendarMutationErrorCode::ProviderRejected,+ message.clone(),+ ),+ CalendarMutationError::Retryable(_) => (+ StatusCode::SERVICE_UNAVAILABLE,+ CalendarMutationErrorCode::Retryable,+ "the calendar mutation failed transiently; try again".to_string(),+ ),+ CalendarMutationError::PersistFailed(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ CalendarMutationErrorCode::PersistFailed,+ "the change reached the calendar provider; refresh to see it".to_string(),+ ),+ };+ if matches!(+ error,+ CalendarMutationError::Retryable(_) | CalendarMutationError::PersistFailed(_)+ ) {+ tracing::error!(error=?error, "calendar mutation failed");+ }+ Self {+ code,+ message,+ status,+ }+ }+}++/// Create a calendar event and return its synced entity.+#[tracing::instrument(skip_all, err)]+#[utoipa::path(+ post,+ path = "/calendar/events",+ tag = "calendar_events",+ request_body = CreateCalendarEventRequest,+ responses(+ (status = 201, description = "The created calendar event", body = CalendarEvent),+ (status = 400, description = "Invalid event fields", body = CalendarMutationApiError),+ (status = 401, description = "Authentication required"),+ (status = 403, description = "Calendar is read-only or needs reauthorization", body = CalendarMutationApiError),+ (status = 409, description = "No writable calendar or the provider rejected the event", body = CalendarMutationApiError),+ (status = 503, description = "Transient provider failure", body = CalendarMutationApiError),+ )+)]+pub async fn create_calendar_event<S, Auth>(+ State(state): State<CalendarMutationRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(request): Json<CreateCalendarEventRequest>,+) -> Result<(StatusCode, Json<CalendarEvent>), CalendarMutationApiError>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+{+ let draft = CalendarEventDraft {+ title: request.title,+ description: request.description,+ location: request.location,+ time: request.time,+ attendees: request.attendees.into_iter().map(Into::into).collect(),+ recurrence_lines: request.recurrence_lines,+ visibility: request.visibility,+ transparency: request.transparency,+ };+ let event = state+ .service+ .create_event(+ user.authorization.user.macro_user_id.as_ref(),+ request.email_link_id,+ request.calendar_id,+ draft,+ )+ .await?;+ Ok((StatusCode::CREATED, Json(event)))+}++/// Calendars visible to the requester across connected and delegated inboxes.+#[derive(Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListCalendarsResponse {+ /// Primaries and writable calendars first.+ pub calendars: Vec<VisibleCalendar>,+}++/// List the requester's visible calendars for pickers and filters.+#[tracing::instrument(skip_all, err)]+#[utoipa::path(+ get,+ path = "/calendar/calendars",+ tag = "calendar_events",+ responses(+ (status = 200, description = "Calendars visible to the requester", body = ListCalendarsResponse),+ (status = 401, description = "Authentication required"),+ (status = 503, description = "Transient failure", body = CalendarMutationApiError),+ )+)]+pub async fn list_calendars<S, Auth>(+ State(state): State<CalendarMutationRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+) -> Result<Json<ListCalendarsResponse>, CalendarMutationApiError>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+{+ let calendars = state+ .service+ .list_visible_calendars(user.authorization.user.macro_user_id.as_ref())+ .await?;+ Ok(Json(ListCalendarsResponse { calendars }))+}++/// Update fields of a calendar event and return its synced entity.+#[tracing::instrument(skip_all, fields(event_id = %event_id), err)]+#[utoipa::path(+ patch,+ path = "/calendar/events/{event_id}",+ tag = "calendar_events",+ params(("event_id" = Uuid, Path, description = "Calendar event entity id")),+ request_body = UpdateCalendarEventRequest,+ responses(+ (status = 200, description = "The updated calendar event", body = CalendarEvent),+ (status = 400, description = "Invalid event fields", body = CalendarMutationApiError),+ (status = 401, description = "Authentication required"),+ (status = 403, description = "Calendar is read-only or needs reauthorization", body = CalendarMutationApiError),+ (status = 404, description = "Event not found", body = CalendarMutationApiError),+ (status = 409, description = "The provider rejected the update", body = CalendarMutationApiError),+ (status = 503, description = "Transient provider failure", body = CalendarMutationApiError),+ )+)]+pub async fn update_calendar_event<S, Auth>(+ State(state): State<CalendarMutationRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(event_id): Path<Uuid>,+ Json(request): Json<UpdateCalendarEventRequest>,+) -> Result<Json<CalendarEvent>, CalendarMutationApiError>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+{+ let patch = CalendarEventPatch {+ title: request.title,+ description: request.description,+ location: request.location,+ time: request.time,+ attendees: request+ .attendees+ .map(|attendees| attendees.into_iter().map(Into::into).collect()),+ recurrence_lines: request.recurrence_lines,+ visibility: request.visibility,+ transparency: request.transparency,+ };+ let event = state+ .service+ .update_event(+ user.authorization.user.macro_user_id.as_ref(),+ event_id,+ patch,+ )+ .await?;+ Ok(Json(event))+}++/// Delete a calendar event at its provider.+#[tracing::instrument(skip_all, fields(event_id = %event_id), err)]+#[utoipa::path(+ delete,+ path = "/calendar/events/{event_id}",+ tag = "calendar_events",+ params(+ ("event_id" = Uuid, Path, description = "Calendar event entity id"),+ DeleteCalendarEventQuery,+ ),+ responses(+ (status = 204, description = "The event was deleted"),+ (status = 401, description = "Authentication required"),+ (status = 403, description = "Calendar is read-only or needs reauthorization", body = CalendarMutationApiError),+ (status = 404, description = "Event not found", body = CalendarMutationApiError),+ (status = 409, description = "The provider rejected the deletion", body = CalendarMutationApiError),+ (status = 503, description = "Transient provider failure", body = CalendarMutationApiError),+ )+)]+pub async fn delete_calendar_event<S, Auth>(+ State(state): State<CalendarMutationRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(event_id): Path<Uuid>,+ Query(query): Query<DeleteCalendarEventQuery>,+) -> Result<StatusCode, CalendarMutationApiError>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+{+ let scoped_occurrence = |kind: &'static str| {+ query.recurrence_id.clone().ok_or(CalendarMutationApiError {+ code: CalendarMutationErrorCode::InvalidInput,+ message: format!("a {kind} deletion requires recurrenceId"),+ status: StatusCode::BAD_REQUEST,+ })+ };+ let scope = match query.scope {+ CalendarDeletionScopeParam::All => CalendarDeletionScope::All,+ CalendarDeletionScopeParam::ThisEvent => CalendarDeletionScope::ThisEvent {+ recurrence_id: scoped_occurrence("this-event")?,+ },+ CalendarDeletionScopeParam::ThisAndFollowing => CalendarDeletionScope::ThisAndFollowing {+ recurrence_id: scoped_occurrence("this-and-following")?,+ },+ };+ state+ .service+ .delete_event(+ user.authorization.user.macro_user_id.as_ref(),+ event_id,+ scope,+ )+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++/// Set the requester's RSVP on a calendar event and return its synced entity.+#[tracing::instrument(skip_all, fields(event_id = %event_id), err)]+#[utoipa::path(+ put,+ path = "/calendar/events/{event_id}/rsvp",+ tag = "calendar_events",+ params(("event_id" = Uuid, Path, description = "Calendar event entity id")),+ request_body = RsvpCalendarEventRequest,+ responses(+ (status = 200, description = "The updated calendar event", body = CalendarEvent),+ (status = 401, description = "Authentication required"),+ (status = 403, description = "Calendar is read-only or needs reauthorization", body = CalendarMutationApiError),+ (status = 404, description = "Event not found", body = CalendarMutationApiError),+ (status = 409, description = "The connected account is not an attendee", body = CalendarMutationApiError),+ (status = 503, description = "Transient provider failure", body = CalendarMutationApiError),+ )+)]+pub async fn rsvp_calendar_event<S, Auth>(+ State(state): State<CalendarMutationRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(event_id): Path<Uuid>,+ Json(request): Json<RsvpCalendarEventRequest>,+) -> Result<Json<CalendarEvent>, CalendarMutationApiError>+where+ S: CalendarMutationService,+ Auth: MacroAuthorizationService,+{+ let event = state+ .service+ .respond_to_event(+ user.authorization.user.macro_user_id.as_ref(),+ event_id,+ request.response,+ )+ .await?;+ Ok(Json(event))+}diff --git a/crates/calendar_events/src/inbound/mutation_router/test.rs b/crates/calendar_events/src/inbound/mutation_router/test.rsnew file mode 100644index 0000000000..5ead43da15--- /dev/null+++ b/crates/calendar_events/src/inbound/mutation_router/test.rs@@ -0,0 +1,86 @@+use super::*;++fn transport_of(error: CalendarMutationError) -> (StatusCode, CalendarMutationErrorCode) {+ let api_error = CalendarMutationApiError::from(error);+ (api_error.status, api_error.code)+}++#[test]+fn domain_errors_map_to_distinct_transport_semantics() {+ assert_eq!(+ transport_of(CalendarMutationError::NotFound),+ (StatusCode::NOT_FOUND, CalendarMutationErrorCode::NotFound)+ );+ assert_eq!(+ transport_of(CalendarMutationError::ReadOnly),+ (StatusCode::FORBIDDEN, CalendarMutationErrorCode::ReadOnly)+ );+ assert_eq!(+ transport_of(CalendarMutationError::NoWritableCalendar),+ (+ StatusCode::CONFLICT,+ CalendarMutationErrorCode::NoWritableCalendar+ )+ );+ assert_eq!(+ transport_of(CalendarMutationError::NotAttendee),+ (StatusCode::CONFLICT, CalendarMutationErrorCode::NotAttendee)+ );+ assert_eq!(+ transport_of(CalendarMutationError::InvalidInput("bad".to_string())),+ (+ StatusCode::BAD_REQUEST,+ CalendarMutationErrorCode::InvalidInput+ )+ );+ assert_eq!(+ transport_of(CalendarMutationError::ReauthRequired("expired".to_string())),+ (+ StatusCode::FORBIDDEN,+ CalendarMutationErrorCode::ReauthRequired+ )+ );+ assert_eq!(+ transport_of(CalendarMutationError::ProviderRejected("no".to_string())),+ (+ StatusCode::CONFLICT,+ CalendarMutationErrorCode::ProviderRejected+ )+ );+ assert_eq!(+ transport_of(CalendarMutationError::Retryable("later".to_string())),+ (+ StatusCode::SERVICE_UNAVAILABLE,+ CalendarMutationErrorCode::Retryable+ )+ );+ assert_eq!(+ transport_of(CalendarMutationError::PersistFailed("lag".to_string())),+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ CalendarMutationErrorCode::PersistFailed+ )+ );+}++#[test]+fn provider_rejections_surface_their_message_but_internal_failures_do_not() {+ let rejected = CalendarMutationApiError::from(CalendarMutationError::ProviderRejected(+ "guests cannot invite others".to_string(),+ ));+ assert_eq!(rejected.message, "guests cannot invite others");++ let retryable = CalendarMutationApiError::from(CalendarMutationError::Retryable(+ "connection reset by peer at 10.0.0.7".to_string(),+ ));+ assert!(!retryable.message.contains("10.0.0.7"));+}++#[test]+fn attendee_body_defaults_to_required_attendance() {+ let body: CalendarAttendeeInputBody =+ serde_json::from_value(serde_json::json!({ "email": "[email protected]" })).unwrap();+ let input = CalendarAttendeeInput::from(body);+ assert!(!input.is_optional);+ assert_eq!(input.email, "[email protected]");+}diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rsindex 7474ab9417..e396a5606e 100644--- a/crates/calendar_events/src/outbound/google.rs+++ b/crates/calendar_events/src/outbound/google.rs@@ -10,14 +10,17 @@ use uuid::Uuid;use crate::domain::{models::{- AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarEventOverride,- CalendarEventSource, CalendarEventUpsert, CalendarOccurrence, EventStart, EventStatus,- EventTime, EventTransparency, EventVisibility, GoogleEventSource, GoogleEventSyncBatch,- GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig, OccurrenceRange, ProviderCalendar,+ AttendeeResponseStatus, CalendarAttendee, CalendarAttendeeInput, CalendarEvent,+ CalendarEventDraft, CalendarEventOverride, CalendarEventPatch, CalendarEventSource,+ CalendarEventUpsert, CalendarOccurrence, EventStart, EventStatus, EventTime,+ EventTransparency, EventVisibility, GoogleCalendarTarget, GoogleEventSource,+ GoogleEventSyncBatch, GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig,+ OccurrenceRange, ProviderCalendar,},ports::{- GoogleCalendarProvider, GoogleEventSyncContext, GoogleProviderError,- GoogleProviderErrorKind,+ GoogleCalendarMutationProvider, GoogleCalendarProvider, GoogleEventSyncContext,+ GoogleProviderError, GoogleProviderErrorKind, GoogleRsvpOutcome,+ GoogleSeriesMutationOutcome,},};@@ -380,7 +383,7 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {#[tracing::instrument(skip(self, access_token, context),- fields(provider_calendar_id = %context.provider_calendar_id),+ fields(provider_calendar_id = %context.target.provider_calendar_id),err)]async fn sync_events(@@ -388,13 +391,14 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {access_token: &str,context: GoogleEventSyncContext,) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ let target = &context.target;let (changes, next_sync_token, token_was_reset) = match self.event_changes(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,context.sync_token.as_deref(),- &context.range,+ &target.range,).await{@@ -403,10 +407,10 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {let (changes, next_sync_token) = self.event_changes(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,None,- &context.range,+ &target.range,).await?;(changes, next_sync_token, true)@@ -426,41 +430,41 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {let canonical_events = self.events(access_token,- context.email_link_id,- &context.provider_calendar_id,- &context.range,+ target.email_link_id,+ &target.provider_calendar_id,+ &target.range,false,).await?;let instances = self.events(access_token,- context.email_link_id,- &context.provider_calendar_id,- &context.range,+ target.email_link_id,+ &target.provider_calendar_id,+ &target.range,true,).await?;- let mapped = map_snapshot(&context, canonical_events, instances);+ let mapped = map_snapshot(target, canonical_events, instances);return Ok(GoogleEventSyncBatch {upserts: mapped.upserts,observed_provider_event_ids: Some(mapped.observed_provider_event_ids),next_sync_token,- materialized_range: Some(context.range.clone()),+ materialized_range: Some(target.range.clone()),cancelled_provider_event_ids: Vec::new(),});}let mut applied = self- .apply_change_feed(access_token, &context, changes)+ .apply_change_feed(access_token, target, changes).await?;let materialized_range =if let GoogleSyncPlan::ExtendTail { from, from_date } = context.plan {- self.extend_tail(access_token, &context, from, from_date, &mut applied)+ self.extend_tail(access_token, target, from, from_date, &mut applied).await?;- Some(context.range.clone())+ Some(target.range.clone())} else {None};@@ -538,7 +542,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {async fn apply_change_feed(&self,access_token: &str,- context: &GoogleEventSyncContext,+ target: &GoogleCalendarTarget,changes: Vec<GoogleEvent>,) -> Result<AppliedChangeFeed, GoogleProviderError> {let classified = classify_changes(changes);@@ -549,7 +553,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {for single in classified.single_upserts {let provider_event_id = single.id.clone();- match map_upsert(context, single.clone(), Vec::new(), vec![single]) {+ match map_upsert(target, single.clone(), Vec::new(), vec![single]) {Ok(upsert) => {applied.upserts.push(upsert);applied.upserted_singles.insert(provider_event_id);@@ -557,7 +561,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {Err(error) => {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed changed Google Calendar event");@@ -569,7 +573,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {// for recurrence expansion without re-sweeping the whole window.for (master_id, feed_master) in classified.refresh_masters {match self- .refresh_series(access_token, context, &master_id, feed_master)+ .refresh_series(access_token, target, &master_id, feed_master).await?{SeriesOutcome::Refreshed(upsert) => {@@ -591,7 +595,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {async fn refresh_series(&self,access_token: &str,- context: &GoogleEventSyncContext,+ target: &GoogleCalendarTarget,master_id: &str,feed_master: Option<GoogleEvent>,) -> Result<SeriesOutcome, GoogleProviderError> {@@ -600,8 +604,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {None => {self.event(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,master_id,).await?@@ -618,8 +622,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {} else {self.events_by_ical_uid(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,&master.ical_uid,).await?@@ -630,19 +634,19 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {let instances = self.instances(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,&master.id,- &context.range,+ &target.range,).await?;let provider_event_id = master.id.clone();- match map_upsert(context, master, exceptions, instances) {+ match map_upsert(target, master, exceptions, instances) {Ok(upsert) => Ok(SeriesOutcome::Refreshed(Box::new(upsert))),Err(error) => {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed changed Google Calendar series");@@ -657,16 +661,16 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {async fn extend_tail(&self,access_token: &str,- context: &GoogleEventSyncContext,+ target: &GoogleCalendarTarget,from: DateTime<Utc>,from_date: NaiveDate,applied: &mut AppliedChangeFeed,) -> Result<(), GoogleProviderError> {let tail = OccurrenceRange {starts_at: from,- ends_at: context.range.ends_at,+ ends_at: target.range.ends_at,start_date: from_date,- end_date: context.range.end_date,+ end_date: target.range.end_date,};if tail.starts_at >= tail.ends_at {return Ok(());@@ -674,8 +678,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {let tail_events = self.events(access_token,- context.email_link_id,- &context.provider_calendar_id,+ target.email_link_id,+ &target.provider_calendar_id,&tail,true,)@@ -684,7 +688,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {for single in tail_singles {let provider_event_id = single.id.clone();- match map_upsert(context, single.clone(), Vec::new(), vec![single]) {+ match map_upsert(target, single.clone(), Vec::new(), vec![single]) {Ok(upsert) => {applied.upserts.push(upsert);applied.upserted_singles.insert(provider_event_id);@@ -692,7 +696,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {Err(error) => {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed Google Calendar event in the coverage tail");@@ -702,7 +706,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {for master_id in tail_series {match self- .refresh_series(access_token, context, &master_id, None)+ .refresh_series(access_token, target, &master_id, None).await?{SeriesOutcome::Refreshed(upsert) => {@@ -722,6 +726,569 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {}}+/// Every mutation notifies affected guests, matching the Google Calendar+/// UI's default behavior for invitations and cancellations.+const SEND_UPDATES: (&str, &str) = ("sendUpdates", "all");++impl<G: GoogleRequestGate> GoogleCalendarClient<G> {+ /// Normalize the provider echo of a mutation into a persistable upsert.+ ///+ /// Recurring series are re-read from the provider so Google stays the+ /// recurrence expansion authority, exactly like ingestion. `None` means+ /// the series master disappeared between the mutation and the refresh.+ async fn mutation_readback(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ event: GoogleEvent,+ ) -> Result<Option<CalendarEventUpsert>, GoogleProviderError> {+ let outcome = if let Some(master_id) = event.recurring_event_id.clone() {+ self.refresh_series(access_token, target, &master_id, None)+ .await?+ } else if !event.recurrence.is_empty() {+ let master_id = event.id.clone();+ self.refresh_series(access_token, target, &master_id, Some(event))+ .await?+ } else {+ return map_upsert(target, event.clone(), Vec::new(), vec![event])+ .map(Some)+ .map_err(mutation_normalization_error);+ };+ match outcome {+ SeriesOutcome::Refreshed(upsert) => Ok(Some(*upsert)),+ SeriesOutcome::Gone => Ok(None),+ SeriesOutcome::Malformed => Err(GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ "Google Calendar returned a malformed series after the mutation",+ )),+ }+ }++ async fn delete_event_raw(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ ) -> Result<(), GoogleProviderError> {+ let calendar = urlencoding::encode(&target.provider_calendar_id);+ let event = urlencoding::encode(provider_event_id);+ self.gate.acquire(target.email_link_id).await?;+ let response = self+ .client+ .delete(format!(+ "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}"+ ))+ .bearer_auth(access_token)+ .query(&[SEND_UPDATES])+ .send()+ .await+ .map_err(provider_transport_error)?;+ let status = response.status();+ // An event already deleted (or cancelled) at the provider is success.+ if status.is_success() || status == StatusCode::NOT_FOUND || status == StatusCode::GONE {+ return Ok(());+ }+ let body = response.text().await.map_err(provider_transport_error)?;+ Err(provider_response_error(status, &body))+ }++ /// Refresh a series after reshaping it, mapping the outcome for callers.+ async fn series_outcome(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ ) -> Result<GoogleSeriesMutationOutcome, GoogleProviderError> {+ match self+ .refresh_series(access_token, target, master_provider_event_id, None)+ .await?+ {+ SeriesOutcome::Refreshed(upsert) => Ok(GoogleSeriesMutationOutcome::Applied(upsert)),+ SeriesOutcome::Gone => Ok(GoogleSeriesMutationOutcome::Gone),+ SeriesOutcome::Malformed => Err(GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ "Google Calendar returned a malformed series after the mutation",+ )),+ }+ }++ async fn patch_event_raw(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ body: serde_json::Value,+ ) -> Result<Option<GoogleEvent>, GoogleProviderError> {+ let calendar = urlencoding::encode(&target.provider_calendar_id);+ let event = urlencoding::encode(provider_event_id);+ self.gate.acquire(target.email_link_id).await?;+ let response = self+ .client+ .patch(format!(+ "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}"+ ))+ .bearer_auth(access_token)+ .query(&[SEND_UPDATES])+ .json(&body)+ .send()+ .await+ .map_err(provider_transport_error)?;+ let status = response.status();+ if status == StatusCode::NOT_FOUND || status == StatusCode::GONE {+ return Ok(None);+ }+ if !status.is_success() {+ let body = response.text().await.map_err(provider_transport_error)?;+ return Err(provider_response_error(status, &body));+ }+ response+ .json()+ .await+ .map(Some)+ .map_err(provider_transport_error)+ }+}++impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClient<G> {+ #[tracing::instrument(+ skip(self, access_token, target, draft),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn create_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ draft: &CalendarEventDraft,+ ) -> Result<CalendarEventUpsert, GoogleProviderError> {+ let calendar = urlencoding::encode(&target.provider_calendar_id);+ self.gate.acquire(target.email_link_id).await?;+ let created: GoogleEvent = send_google(+ self.client+ .post(format!("{GOOGLE_CALENDAR_API}/calendars/{calendar}/events"))+ .bearer_auth(access_token)+ .query(&[SEND_UPDATES])+ .json(&draft_body(draft)),+ )+ .await?;+ // The insert already happened and carries no idempotency key, so a+ // readback miss must not surface as retryable: a client retry would+ // POST a duplicate event.+ self.mutation_readback(access_token, target, created)+ .await?+ .ok_or_else(|| {+ GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ "Google Calendar dropped the event immediately after creation",+ )+ })+ }++ #[tracing::instrument(+ skip(self, access_token, target, patch),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn update_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ patch: &CalendarEventPatch,+ ) -> Result<Option<CalendarEventUpsert>, GoogleProviderError> {+ let Some(updated) = self+ .patch_event_raw(access_token, target, provider_event_id, patch_body(patch))+ .await?+ else {+ return Ok(None);+ };+ self.mutation_readback(access_token, target, updated).await+ }++ #[tracing::instrument(+ skip(self, access_token, target),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn delete_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ ) -> Result<(), GoogleProviderError> {+ self.delete_event_raw(access_token, target, provider_event_id)+ .await+ }++ #[tracing::instrument(+ skip(self, access_token, target),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn delete_event_instance(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> Result<GoogleSeriesMutationOutcome, GoogleProviderError> {+ let Some(start) = parse_occurrence_start(original_start) else {+ return Err(GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ "the occurrence identifier is not a recognizable start",+ ));+ };+ // A one-day window around the occurrence bounds the lookup; the+ // exact instance is matched locally by its original start.+ let window = occurrence_window(&start);+ let instances = self+ .instances(+ access_token,+ target.email_link_id,+ &target.provider_calendar_id,+ master_provider_event_id,+ &window,+ )+ .await?;+ let matched = instances.into_iter().find(|instance| {+ instance+ .original_start_time+ .as_ref()+ .and_then(google_start)+ .is_some_and(|candidate| candidate == start)+ });+ if let Some(instance) = matched {+ self.delete_event_raw(access_token, target, &instance.id)+ .await?;+ }+ self.series_outcome(access_token, target, master_provider_event_id)+ .await+ }++ #[tracing::instrument(+ skip(self, access_token, target),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn truncate_recurring_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ master_provider_event_id: &str,+ original_start: &str,+ ) -> Result<GoogleSeriesMutationOutcome, GoogleProviderError> {+ let Some(cutoff) = parse_occurrence_start(original_start) else {+ return Err(GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ "the occurrence identifier is not a recognizable start",+ ));+ };+ let Some(master) = self+ .event(+ access_token,+ target.email_link_id,+ &target.provider_calendar_id,+ master_provider_event_id,+ )+ .await?+ else {+ return Ok(GoogleSeriesMutationOutcome::Gone);+ };+ // Removing everything from the first occurrence onward is a series+ // deletion, matching Google Calendar's own behavior.+ let master_start = google_time(&master).ok().map(|time| event_start_of(&time));+ if master_start.is_some_and(|start| !occurrence_is_after(&cutoff, &start)) {+ self.delete_event_raw(access_token, target, &master.id)+ .await?;+ return Ok(GoogleSeriesMutationOutcome::SeriesDeleted);+ }+ let truncated = truncate_recurrence_lines(&master.recurrence, &cutoff);+ let Some(updated) = self+ .patch_event_raw(+ access_token,+ target,+ &master.id,+ serde_json::json!({ "recurrence": truncated }),+ )+ .await?+ else {+ return Ok(GoogleSeriesMutationOutcome::Gone);+ };+ match self+ .mutation_readback(access_token, target, updated)+ .await?+ {+ Some(upsert) => Ok(GoogleSeriesMutationOutcome::Applied(Box::new(upsert))),+ None => Ok(GoogleSeriesMutationOutcome::Gone),+ }+ }++ #[tracing::instrument(+ skip(self, access_token, target, self_email),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn rsvp_event(+ &self,+ access_token: &str,+ target: &GoogleCalendarTarget,+ provider_event_id: &str,+ self_email: &str,+ response: AttendeeResponseStatus,+ ) -> Result<GoogleRsvpOutcome, GoogleProviderError> {+ // Patching `attendees` replaces the whole array, so start from the+ // provider's current list rather than a possibly stale projection.+ let Some(current) = self+ .event(+ access_token,+ target.email_link_id,+ &target.provider_calendar_id,+ provider_event_id,+ )+ .await?+ else {+ return Ok(GoogleRsvpOutcome::Gone);+ };+ let mut attendees: Vec<GoogleAttendee> = current.attendees.clone().unwrap_or_default();+ let self_position = attendees+ .iter()+ .position(|attendee| attendee.is_self)+ .or_else(|| {+ attendees.iter().position(|attendee| {+ attendee+ .as_deref()+ .is_some_and(|email| email.eq_ignore_ascii_case(self_email))+ })+ });+ let Some(position) = self_position else {+ return Ok(GoogleRsvpOutcome::NotAttendee);+ };+ attendees[position].response_status = Some(google_response_status(response).to_string());+ let body = serde_json::json!({ "attendees": attendees });+ let Some(updated) = self+ .patch_event_raw(access_token, target, provider_event_id, body)+ .await?+ else {+ return Ok(GoogleRsvpOutcome::Gone);+ };+ match self+ .mutation_readback(access_token, target, updated)+ .await?+ {+ Some(upsert) => Ok(GoogleRsvpOutcome::Applied(Box::new(upsert))),+ None => Ok(GoogleRsvpOutcome::Gone),+ }+ }+}++/// Parse a stored occurrence key (RFC 3339 instant or local date).+fn parse_occurrence_start(value: &str) -> Option<EventStart> {+ if let Ok(instant) = DateTime::parse_from_rfc3339(value) {+ return Some(EventStart::Timed(instant.with_timezone(&Utc)));+ }+ NaiveDate::parse_from_str(value, "%Y-%m-%d")+ .ok()+ .map(EventStart::AllDay)+}++fn start_instant(start: &EventStart) -> DateTime<Utc> {+ match start {+ EventStart::Timed(instant) => *instant,+ EventStart::AllDay(date) => date+ .and_hms_opt(0, 0, 0)+ .expect("midnight is a valid time")+ .and_utc(),+ }+}++fn event_start_of(time: &EventTime) -> EventStart {+ match time {+ EventTime::Timed { starts_at, .. } => EventStart::Timed(*starts_at),+ EventTime::AllDay { start_date, .. } => EventStart::AllDay(*start_date),+ }+}++fn occurrence_is_after(cutoff: &EventStart, master_start: &EventStart) -> bool {+ start_instant(cutoff) > start_instant(master_start)+}++/// One-day range around an occurrence, bounding an exact-instance lookup.+fn occurrence_window(start: &EventStart) -> OccurrenceRange {+ let instant = start_instant(start);+ let date = match start {+ EventStart::Timed(instant) => instant.date_naive(),+ EventStart::AllDay(date) => *date,+ };+ OccurrenceRange {+ starts_at: instant - chrono::Duration::days(1),+ ends_at: instant + chrono::Duration::days(1),+ start_date: date - chrono::Duration::days(1),+ end_date: date + chrono::Duration::days(1),+ }+}++/// Rewrite a recurrence property list to end just before `cutoff`,+/// replacing any existing `UNTIL` or `COUNT` bound.+fn truncate_recurrence_lines(lines: &[String], cutoff: &EventStart) -> Vec<String> {+ let until = match cutoff {+ EventStart::Timed(instant) => (*instant - chrono::Duration::seconds(1))+ .format("%Y%m%dT%H%M%SZ")+ .to_string(),+ EventStart::AllDay(date) => (*date - chrono::Duration::days(1))+ .format("%Y%m%d")+ .to_string(),+ };+ lines+ .iter()+ .map(|line| {+ let Some(params) = line.strip_prefix("RRULE:") else {+ return line.clone();+ };+ let mut kept: Vec<&str> = params+ .split(';')+ .filter(|param| {+ let upper = param.to_ascii_uppercase();+ !upper.starts_with("UNTIL=") && !upper.starts_with("COUNT=")+ })+ .collect();+ let until_param = format!("UNTIL={until}");+ kept.push(&until_param);+ format!("RRULE:{}", kept.join(";"))+ })+ .collect()+}++fn mutation_normalization_error(error: Report) -> GoogleProviderError {+ GoogleProviderError::new(+ GoogleProviderErrorKind::Permanent,+ format!("Google Calendar returned a malformed event after the mutation: {error:?}"),+ )+}++fn google_response_status(status: AttendeeResponseStatus) -> &'static str {+ match status {+ AttendeeResponseStatus::NeedsAction => "needsAction",+ AttendeeResponseStatus::Accepted => "accepted",+ AttendeeResponseStatus::Declined => "declined",+ AttendeeResponseStatus::Tentative => "tentative",+ }+}++/// Serialize an event time as Google `start`/`end` objects. The unused shape+/// is set to an explicit `null` so a patch can switch between timed and+/// all-day; inserts ignore the nulls.+fn google_time_body(time: &EventTime) -> (serde_json::Value, serde_json::Value) {+ match time {+ EventTime::Timed {+ starts_at,+ ends_at,+ time_zone,+ } => {+ let mut start = serde_json::json!({+ "dateTime": starts_at.to_rfc3339(),+ "date": null,+ });+ let mut end = serde_json::json!({+ "dateTime": ends_at.to_rfc3339(),+ "date": null,+ });+ if let Some(time_zone) = time_zone {+ start["timeZone"] = serde_json::Value::String(time_zone.clone());+ end["timeZone"] = serde_json::Value::String(time_zone.clone());+ }+ (start, end)+ }+ EventTime::AllDay {+ start_date,+ end_date,+ } => (+ serde_json::json!({ "date": start_date.to_string(), "dateTime": null }),+ serde_json::json!({ "date": end_date.to_string(), "dateTime": null }),+ ),+ }+}++fn google_attendees_body(attendees: &[CalendarAttendeeInput]) -> serde_json::Value {+ attendees+ .iter()+ .map(|attendee| {+ serde_json::json!({+ "email": attendee.email,+ "optional": attendee.is_optional,+ })+ })+ .collect()+}++/// Map an optional user-supplied text field: empty clears the provider value.+fn google_text_body(value: &str) -> serde_json::Value {+ if value.is_empty() {+ serde_json::Value::Null+ } else {+ serde_json::Value::String(value.to_string())+ }+}++fn draft_body(draft: &CalendarEventDraft) -> serde_json::Value {+ let (start, end) = google_time_body(&draft.time);+ let mut body = serde_json::json!({+ "summary": draft.title,+ "start": start,+ "end": end,+ });+ if let Some(description) = &draft.description {+ body["description"] = google_text_body(description);+ }+ if let Some(location) = &draft.location {+ body["location"] = google_text_body(location);+ }+ if !draft.attendees.is_empty() {+ body["attendees"] = google_attendees_body(&draft.attendees);+ }+ if !draft.recurrence_lines.is_empty() {+ body["recurrence"] = serde_json::json!(draft.recurrence_lines);+ }+ if let Some(visibility) = draft.visibility {+ body["visibility"] = serde_json::Value::String(visibility.as_str().to_string());+ }+ if let Some(transparency) = draft.transparency {+ body["transparency"] = serde_json::Value::String(transparency.as_str().to_string());+ }+ body+}++fn patch_body(patch: &CalendarEventPatch) -> serde_json::Value {+ let mut body = serde_json::json!({});+ if let Some(title) = &patch.title {+ body["summary"] = google_text_body(title);+ }+ if let Some(description) = &patch.description {+ body["description"] = google_text_body(description);+ }+ if let Some(location) = &patch.location {+ body["location"] = google_text_body(location);+ }+ if let Some(time) = &patch.time {+ let (start, end) = google_time_body(time);+ body["start"] = start;+ body["end"] = end;+ }+ if let Some(attendees) = &patch.attendees {+ body["attendees"] = google_attendees_body(attendees);+ }+ if let Some(recurrence_lines) = &patch.recurrence_lines {+ body["recurrence"] = serde_json::json!(recurrence_lines);+ }+ if let Some(visibility) = patch.visibility {+ body["visibility"] = serde_json::Value::String(visibility.as_str().to_string());+ }+ if let Some(transparency) = patch.transparency {+ body["transparency"] = serde_json::Value::String(transparency.as_str().to_string());+ }+ body+}+/// Whether this run must rebuild the complete bounded snapshot instead of/// applying the change feed. ExtendTail deliberately stays out of this set:/// it applies the feed and then materializes only the uncovered tail.@@ -800,7 +1367,7 @@ struct MappedGoogleSnapshot {}fn map_snapshot(- context: &GoogleEventSyncContext,+ target: &GoogleCalendarTarget,canonical_events: Vec<GoogleEvent>,instances: Vec<GoogleEvent>,) -> MappedGoogleSnapshot {@@ -845,7 +1412,7 @@ fn map_snapshot(.filter_map(|(uid, master)| {let provider_event_id = master.id.clone();map_upsert(- context,+ target,master,exceptions.remove(&uid).unwrap_or_default(),occurrences.remove(&uid).unwrap_or_default(),@@ -853,7 +1420,7 @@ fn map_snapshot(.inspect_err(|error| {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed Google Calendar master");@@ -868,7 +1435,7 @@ fn map_snapshot(}fn map_upsert(- context: &GoogleEventSyncContext,+ target: &GoogleCalendarTarget,master: GoogleEvent,exceptions: Vec<GoogleEvent>,instances: Vec<GoogleEvent>,@@ -878,9 +1445,9 @@ fn map_upsert(let created_at = parse_datetime(master.created.as_deref()).unwrap_or_else(Utc::now);let updated_at = parse_datetime(master.updated.as_deref()).unwrap_or(created_at);let source = CalendarEventSource::Google(GoogleEventSource {- email_link_id: context.email_link_id,- account_id: context.account_id,- calendar_id: context.calendar_id,+ email_link_id: target.email_link_id,+ account_id: target.account_id,+ calendar_id: target.calendar_id,provider_event_id: master.id.clone(),provider_recurring_event_id: master.recurring_event_id.clone(),provider_etag: master.etag.clone(),@@ -888,8 +1455,9 @@ fn map_upsert(});let event = CalendarEvent {id: event_id,- owner_id: context.owner_id.clone(),+ owner_id: target.owner_id.clone(),ical_uid: master.ical_uid.clone(),+ calendar_id: Some(target.calendar_id),title: master.summary.clone().unwrap_or_default(),description: master.description.clone(),location: master.location.clone(),@@ -911,7 +1479,7 @@ fn map_upsert(.clone().or_else(|| conference_url(master.conference_data.as_ref())),sequence: master.sequence.unwrap_or_default(),- is_read_only: context.is_read_only,+ is_read_only: target.is_read_only,attendees: master.attendees.clone()@@ -957,7 +1525,7 @@ fn map_upsert(.inspect_err(|error| {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed Google Calendar recurrence exception");@@ -984,7 +1552,7 @@ fn map_upsert(})}).transpose()?;- Ok(time.overlaps(&context.range).then(|| CalendarOccurrence {+ Ok(time.overlaps(&target.range).then(|| CalendarOccurrence {event_id,occurrence_key: original_start.as_ref()@@ -998,7 +1566,7 @@ fn map_upsert(.inspect_err(|error| {tracing::warn!(error=?error,- provider_calendar_id=%context.provider_calendar_id,+ provider_calendar_id=%target.provider_calendar_id,provider_event_id,"skipping malformed Google Calendar recurrence instance");@@ -1232,11 +1800,17 @@ struct GooglePerson {display_name: Option<String>,}+/// Writes replace the whole `attendees` array, so every field Google returns+/// must survive a deserialize/serialize round trip; unmapped fields (id,+/// additionalGuests, resource, ...) are carried through `extra`.#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]struct GoogleAttendee {+ #[serde(skip_serializing_if = "Option::is_none")]email: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]display_name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]response_status: Option<String>,#[serde(default)]organizer: bool,@@ -1244,7 +1818,10 @@ struct GoogleAttendee {optional: bool,#[serde(default, rename = "self")]is_self: bool,+ #[serde(skip_serializing_if = "Option::is_none")]comment: Option<String>,+ #[serde(flatten)]+ extra: serde_json::Map<String, serde_json::Value>,}#[derive(Clone, Debug, Deserialize, Serialize)]diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rsindex 2df11ddfec..5ffa6a6d20 100644--- a/crates/calendar_events/src/outbound/google/test.rs+++ b/crates/calendar_events/src/outbound/google/test.rs@@ -23,7 +23,7 @@ fn calendar_access_role_is_reflected_on_mapped_events() {end_date: NaiveDate::from_ymd_opt(2026, 8, 1).unwrap(),};- let context = GoogleEventSyncContext {+ let target = GoogleCalendarTarget {owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -31,10 +31,8 @@ fn calendar_access_role_is_reflected_on_mapped_events() {provider_calendar_id: "primary".to_string(),is_read_only: true,range,- sync_token: None,- plan: GoogleSyncPlan::FullSnapshot,};- let upsert = map_upsert(&context, master, Vec::new(), Vec::new()).unwrap();+ let upsert = map_upsert(&target, master, Vec::new(), Vec::new()).unwrap();assert!(upsert.event.is_read_only);}@@ -70,7 +68,7 @@ fn malformed_recurring_instance_does_not_overstate_snapshot_coverage() {start_date: NaiveDate::from_ymd_opt(2026, 7, 1).unwrap(),end_date: NaiveDate::from_ymd_opt(2026, 8, 1).unwrap(),};- let context = GoogleEventSyncContext {+ let target = GoogleCalendarTarget {owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -78,11 +76,9 @@ fn malformed_recurring_instance_does_not_overstate_snapshot_coverage() {provider_calendar_id: "primary".to_string(),is_read_only: false,range,- sync_token: None,- plan: GoogleSyncPlan::FullSnapshot,};- let upsert = map_upsert(&context, master, Vec::new(), vec![malformed_instance]).unwrap();+ let upsert = map_upsert(&target, master, Vec::new(), vec![malformed_instance]).unwrap();assert!(upsert.occurrences.is_empty());}@@ -107,7 +103,7 @@ fn malformed_master_is_quarantined_without_deleting_its_provider_identity() {let ends_at = DateTime::parse_from_rfc3339("2026-08-01T00:00:00Z").unwrap().with_timezone(&Utc);- let context = GoogleEventSyncContext {+ let target = GoogleCalendarTarget {owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -120,11 +116,9 @@ fn malformed_master_is_quarantined_without_deleting_its_provider_identity() {start_date: starts_at.date_naive(),end_date: ends_at.date_naive(),},- sync_token: Some("token".to_string()),- plan: GoogleSyncPlan::FullSnapshot,};- let mapped = map_snapshot(&context, vec![valid, malformed], Vec::new());+ let mapped = map_snapshot(&target, vec![valid, malformed], Vec::new());assert_eq!(mapped.upserts.len(), 1);assert_eq!(@@ -381,3 +375,67 @@ fn only_the_snapshot_plan_or_a_reset_token_forces_a_full_rebuild() {"ExtendTail must reach the tail path, not the full rebuild");}++#[test]+fn truncation_rewrites_the_rrule_bound_and_keeps_other_lines() {+ let cutoff = EventStart::Timed(+ DateTime::parse_from_rfc3339("2026-08-12T09:00:00+00:00")+ .unwrap()+ .with_timezone(&Utc),+ );+ assert_eq!(+ truncate_recurrence_lines(+ &[+ "RRULE:FREQ=WEEKLY;COUNT=10;BYDAY=MO,FR".to_string(),+ "EXDATE;TZID=UTC:20260810T090000".to_string(),+ ],+ &cutoff,+ ),+ vec![+ "RRULE:FREQ=WEEKLY;BYDAY=MO,FR;UNTIL=20260812T085959Z".to_string(),+ "EXDATE;TZID=UTC:20260810T090000".to_string(),+ ]+ );++ let all_day_cutoff = EventStart::AllDay(NaiveDate::from_ymd_opt(2026, 8, 12).unwrap());+ assert_eq!(+ truncate_recurrence_lines(+ &["RRULE:FREQ=DAILY;UNTIL=20270101".to_string()],+ &all_day_cutoff,+ ),+ vec!["RRULE:FREQ=DAILY;UNTIL=20260811".to_string()]+ );+}++#[test]+fn occurrence_keys_parse_back_to_starts() {+ assert_eq!(+ parse_occurrence_start("2026-08-12T09:00:00+00:00"),+ Some(EventStart::Timed(+ DateTime::parse_from_rfc3339("2026-08-12T09:00:00Z")+ .unwrap()+ .with_timezone(&Utc)+ ))+ );+ assert_eq!(+ parse_occurrence_start("2026-08-12"),+ Some(EventStart::AllDay(+ NaiveDate::from_ymd_opt(2026, 8, 12).unwrap()+ ))+ );+ assert_eq!(parse_occurrence_start("not-a-start"), None);++ let master = EventStart::Timed(+ DateTime::parse_from_rfc3339("2026-08-04T09:00:00Z")+ .unwrap()+ .with_timezone(&Utc),+ );+ assert!(occurrence_is_after(+ &parse_occurrence_start("2026-08-05T09:00:00+00:00").unwrap(),+ &master+ ));+ assert!(!occurrence_is_after(+ &parse_occurrence_start("2026-08-04T09:00:00+00:00").unwrap(),+ &master+ ));+}diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex 6bbe344c1e..d08f7e2065 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -12,11 +12,13 @@ use crate::domain::{models::{AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,- CalendarBackfillJobKey, CalendarBackfillKind, CalendarEvent, CalendarEventOverride,- CalendarEventSource, CalendarEventUpsert, CalendarOccurrence, CalendarOccurrenceCursor,- CalendarSyncStatus, EventStart, EventStatus, EventTime, EventTransparency, EventVisibility,- GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel,- OccurrenceRange, ProviderCalendar, StoredGoogleCalendar,+ CalendarBackfillJobKey, CalendarBackfillKind, CalendarCreationTarget, CalendarEvent,+ CalendarEventMutationTarget, CalendarEventOverride, CalendarEventSource,+ CalendarEventUpsert, CalendarLinkTokenIdentity, CalendarOccurrence,+ CalendarOccurrenceCursor, CalendarSyncStatus, EventStart, EventStatus, EventTime,+ EventTransparency, EventVisibility, GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot,+ GoogleScopeSet, GoogleWatchChannel, OccurrenceRange, ProviderCalendar,+ StoredGoogleCalendar, VisibleCalendar,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarRepository,@@ -265,6 +267,7 @@ struct StoredCalendarRow {struct OccurrenceJoinRow {event_id: Uuid,+ canonical_calendar_id: Option<Uuid>,occurrence_key: String,recurrence_id: Option<String>,occurrence_starts_at: Option<DateTime<Utc>>,@@ -473,6 +476,7 @@ impl CalendarRepository for PgCalendarRepository {.await?;upsert}+ CalendarEventWrite::UserMutation(upsert) => upsert,#[cfg(test)]CalendarEventWrite::Fixture(upsert) => upsert,};@@ -649,6 +653,7 @@ impl CalendarRepository for PgCalendarRepository {r#"SELECToccurrence.event_id,+ canonical_source.calendar_id AS "canonical_calendar_id?",occurrence.occurrence_key,occurrence.recurrence_id,occurrence.starts_at AS occurrence_starts_at,@@ -679,6 +684,21 @@ impl CalendarRepository for PgCalendarRepository {event.updated_atFROM calendar_event_occurrences occurrenceJOIN calendar_events event ON event.id = occurrence.event_id+ LEFT JOIN LATERAL (+ SELECT source.calendar_id+ FROM calendar_event_sources source+ JOIN calendars calendar ON calendar.id = source.calendar_id+ JOIN calendar_accounts account ON account.id = source.account_id+ WHERE source.event_id = event.id+ AND NOT calendar.is_deleted+ AND account.sync_status <> 'disabled'+ ORDER BY+ source.source_sequence DESC,+ source.source_updated_at DESC,+ source.last_seen_at DESC,+ source.id DESC+ LIMIT 1+ ) canonical_source ON trueWHERE occurrence.owner_id IN (SELECT $1::textUNION@@ -1114,6 +1134,241 @@ impl CalendarRepository for PgCalendarRepository {tx.commit().await.map_err(report)}++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn get_event_mutation_target(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<Option<CalendarEventMutationTarget>, Report> {+ // Rank Google sources exactly like source restoration so mutations+ // address the same provider copy reads are projected from.+ let row = sqlx::query!(+ r#"+ SELECT+ event.id AS event_id,+ event.owner_id,+ event.is_read_only,+ source.provider_event_id AS "provider_event_id!",+ source.provider_recurring_event_id,+ source.account_id AS "account_id!",+ source.calendar_id AS "calendar_id!",+ calendar.provider_calendar_id,+ account.email_link_id,+ link.fusionauth_user_id,+ link.email_address,+ link.provider::text AS "provider!"+ FROM calendar_events event+ JOIN calendar_event_sources source+ ON source.event_id = event.id+ AND source.source_kind = 'google'+ JOIN calendars calendar ON calendar.id = source.calendar_id+ JOIN calendar_accounts account ON account.id = source.account_id+ JOIN email_links link ON link.id = account.email_link_id+ WHERE event.id = $1+ AND NOT calendar.is_deleted+ AND account.sync_status <> 'disabled'+ AND (+ event.owner_id = $2+ OR EXISTS (+ SELECT 1+ FROM macro_user_links delegation+ WHERE delegation.link_id = event.source_link_id+ AND delegation.primary_macro_id = $2+ )+ )+ ORDER BY+ source.source_sequence DESC,+ source.source_updated_at DESC,+ source.last_seen_at DESC,+ source.id DESC+ LIMIT 1+ "#,+ event_id,+ requester_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(report)?;+ Ok(row.map(|row| CalendarEventMutationTarget {+ event_id: row.event_id,+ is_read_only: row.is_read_only,+ provider_event_id: row.provider_event_id,+ provider_recurring_event_id: row.provider_recurring_event_id,+ owner_id: row.owner_id,+ email_link_id: row.email_link_id,+ account_id: row.account_id,+ calendar_id: row.calendar_id,+ provider_calendar_id: row.provider_calendar_id,+ token_identity: CalendarLinkTokenIdentity {+ fusionauth_user_id: row.fusionauth_user_id,+ email_address: row.email_address,+ provider: row.provider,+ },+ }))+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn get_creation_target(+ &self,+ requester_id: &str,+ email_link_id: Option<Uuid>,+ calendar_id: Option<Uuid>,+ ) -> Result<Option<CalendarCreationTarget>, Report> {+ let row = sqlx::query!(+ r#"+ SELECT+ link.macro_id AS owner_id,+ link.id AS email_link_id,+ account.id AS account_id,+ calendar.id AS calendar_id,+ calendar.provider_calendar_id,+ calendar.access_role,+ link.fusionauth_user_id,+ link.email_address,+ link.provider::text AS "provider!"+ FROM email_links link+ JOIN calendar_accounts account ON account.email_link_id = link.id+ JOIN calendars calendar ON calendar.account_id = account.id+ WHERE NOT calendar.is_deleted+ AND account.sync_status <> 'disabled'+ AND (+ ($3::uuid IS NOT NULL AND calendar.id = $3)+ OR ($3::uuid IS NULL AND calendar.is_primary)+ )+ AND ($2::uuid IS NULL OR link.id = $2)+ AND (+ link.macro_id = $1+ OR EXISTS (+ SELECT 1+ FROM macro_user_links delegation+ WHERE delegation.link_id = link.id+ AND delegation.primary_macro_id = $1+ )+ )+ ORDER BY+ (link.macro_id = $1) DESC,+ link.is_primary DESC,+ link.created_at ASC+ LIMIT 1+ "#,+ requester_id,+ email_link_id,+ calendar_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(report)?;+ Ok(row.map(|row| CalendarCreationTarget {+ owner_id: row.owner_id,+ email_link_id: row.email_link_id,+ account_id: row.account_id,+ calendar_id: row.calendar_id,+ provider_calendar_id: row.provider_calendar_id,+ is_read_only: !matches!(row.access_role.as_deref(), Some("owner" | "writer")),+ token_identity: CalendarLinkTokenIdentity {+ fusionauth_user_id: row.fusionauth_user_id,+ email_address: row.email_address,+ provider: row.provider,+ },+ }))+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn list_visible_calendars(+ &self,+ requester_id: &str,+ ) -> Result<Vec<VisibleCalendar>, Report> {+ let rows = sqlx::query!(+ r#"+ SELECT+ calendar.id,+ link.id AS email_link_id,+ link.email_address,+ calendar.name,+ calendar.color,+ calendar.is_primary,+ calendar.access_role+ FROM email_links link+ JOIN calendar_accounts account ON account.email_link_id = link.id+ JOIN calendars calendar ON calendar.account_id = account.id+ WHERE NOT calendar.is_deleted+ AND account.sync_status <> 'disabled'+ AND (+ link.macro_id = $1+ OR EXISTS (+ SELECT 1+ FROM macro_user_links delegation+ WHERE delegation.link_id = link.id+ AND delegation.primary_macro_id = $1+ )+ )+ ORDER BY+ (link.macro_id = $1) DESC,+ link.is_primary DESC,+ link.created_at ASC,+ calendar.is_primary DESC,+ (calendar.access_role IN ('owner', 'writer')) DESC,+ calendar.name ASC+ "#,+ requester_id,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(report)?;+ Ok(rows+ .into_iter()+ .map(|row| VisibleCalendar {+ id: row.id,+ email_link_id: row.email_link_id,+ email_address: row.email_address,+ name: row.name,+ color: row.color,+ is_primary: row.is_primary,+ is_writable: matches!(row.access_role.as_deref(), Some("owner" | "writer")),+ })+ .collect())+ }++ #[tracing::instrument(skip(self), err)]+ async fn remove_google_source(+ &self,+ account_id: Uuid,+ calendar_id: Uuid,+ provider_event_id: &str,+ ) -> Result<(), Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ let cancelled = [provider_event_id.to_string()];+ // A deleted recurring master retires its expanded instances via+ // provider_recurring_event_id, matching Google's tombstone shape.+ let affected_event_ids = sqlx::query_scalar!(+ r#"+ WITH deleted_sources AS (+ DELETE FROM calendar_event_sources source+ WHERE source.source_kind = 'google'+ AND source.account_id = $1+ AND source.calendar_id = $2+ AND (+ source.provider_event_id = ANY($3::text[])+ OR source.provider_recurring_event_id = ANY($3::text[])+ )+ RETURNING source.event_id+ )+ SELECT DISTINCT event_id AS "event_id!"+ FROM deleted_sources+ "#,+ account_id,+ calendar_id,+ &cancelled,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(report)?;+ for event_id in affected_event_ids {+ restore_best_source_or_delete(&mut tx, event_id).await?;+ }+ tx.commit().await.map_err(report)+ }}impl GoogleCalendarSyncRepository for PgCalendarRepository {@@ -2152,6 +2407,7 @@ fn event_from_join(id: row.event_id,owner_id: row.owner_id,ical_uid: row.ical_uid,+ calendar_id: row.canonical_calendar_id,title: row.title,description: row.description,location: row.location,diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex 01ea4ee028..bcfd1757fc 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -122,6 +122,7 @@ fn timed_upsert(id,owner_id: owner_id.to_string(),ical_uid: uid.to_string(),+ calendar_id: Some(calendar_id),title: title.to_string(),description: None,location: None,@@ -1972,3 +1973,297 @@ async fn unclaimed_permanent_google_failure_marks_account_error(pool: PgPool) {Some("provider rejected data"));}++async fn grant_and_provider_ids(repo: &PgCalendarRepository, link_id: Uuid) -> (Uuid, Uuid) {+ repo.apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ provider_ids(repo, link_id).await+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn user_mutation_write_persists_a_google_echo_without_a_lease(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = grant_and_provider_ids(&repo, link_id).await;++ let upsert = timed_upsert(+ owner_id,+ link_id,+ provider,+ "[email protected]",+ "Google event",+ 1,+ );+ let event_id = repo+ .upsert_event(CalendarEventWrite::UserMutation(upsert))+ .await+ .unwrap();++ let row = sqlx::query!(+ r#"+ SELECT+ (SELECT title FROM calendar_events WHERE id = $1) AS "title!",+ (SELECT count(*) FROM calendar_event_occurrences WHERE event_id = $1) AS "occurrences!",+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1 AND source_kind = 'google') AS "sources!"+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ (row.title.as_str(), row.occurrences, row.sources),+ ("Google event", 2, 1)+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn mutation_target_resolves_only_for_visible_requesters(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let delegate_id = "macro|[email protected]";+ let stranger_id = "macro|[email protected]";+ insert_user(&pool, owner_id).await;+ insert_user(&pool, delegate_id).await;+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = grant_and_provider_ids(&repo, link_id).await;+ let event_id = repo+ .upsert_event(CalendarEventWrite::UserMutation(timed_upsert(+ owner_id,+ link_id,+ provider,+ "[email protected]",+ "Target event",+ 1,+ )))+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)+ VALUES ($1, $2, $3)+ "#,+ delegate_id,+ owner_id,+ link_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ let target = repo+ .get_event_mutation_target(owner_id, event_id)+ .await+ .unwrap()+ .expect("owner sees the mutation target");+ assert_eq!(target.provider_event_id, "[email protected]");+ assert_eq!(+ target.master_provider_event_id(),+ );+ assert_eq!(target.account_id, provider.0);+ assert_eq!(target.calendar_id, provider.1);+ assert_eq!(target.provider_calendar_id, "primary");+ assert_eq!(target.owner_id, owner_id);+ assert_eq!(target.token_identity.provider, "GMAIL");++ let delegated = repo+ .get_event_mutation_target(delegate_id, event_id)+ .await+ .unwrap();+ assert!(delegated.is_some(), "delegate sees the mutation target");++ let hidden = repo+ .get_event_mutation_target(stranger_id, event_id)+ .await+ .unwrap();+ assert!(hidden.is_none(), "stranger cannot see the mutation target");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn creation_target_prefers_the_requesters_own_primary_inbox(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, calendar_id) = grant_and_provider_ids(&repo, link_id).await;++ let target = repo+ .get_creation_target(owner_id, None, None)+ .await+ .unwrap()+ .expect("owner resolves a creation target");+ assert_eq!(target.account_id, account_id);+ assert_eq!(target.calendar_id, calendar_id);+ assert_eq!(target.owner_id, owner_id);+ assert!(!target.is_read_only);++ let explicit = repo+ .get_creation_target(owner_id, Some(link_id), None)+ .await+ .unwrap();+ assert!(explicit.is_some());++ let unknown_link = repo+ .get_creation_target(owner_id, Some(Uuid::now_v7()), None)+ .await+ .unwrap();+ assert!(unknown_link.is_none());++ let stranger = repo+ .get_creation_target("macro|[email protected]", None, None)+ .await+ .unwrap();+ assert!(stranger.is_none());++ let team_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "team".to_string(),+ name: "Team".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: Some("#33b679".to_string()),+ access_role: Some("writer".to_string()),+ is_primary: false,+ is_selected: true,+ },+ )+ .await+ .unwrap();+ let picked = repo+ .get_creation_target(owner_id, None, Some(team_id))+ .await+ .unwrap()+ .expect("an explicit calendar overrides the primary default");+ assert_eq!(picked.calendar_id, team_id);+ assert_eq!(picked.provider_calendar_id, "team");+ assert!(!picked.is_read_only);++ let foreign_calendar = repo+ .get_creation_target(+ "macro|[email protected]",+ None,+ Some(team_id),+ )+ .await+ .unwrap();+ assert!(+ foreign_calendar.is_none(),+ "calendar picks stay requester-scoped"+ );++ let calendars = repo.list_visible_calendars(owner_id).await.unwrap();+ assert_eq!(+ calendars+ .iter()+ .map(|calendar| (+ calendar.name.as_str(),+ calendar.is_primary,+ calendar.is_writable+ ))+ .collect::<Vec<_>>(),+ vec![("Primary", true, true), ("Team", false, true)]+ );+ assert!(+ repo.list_visible_calendars("macro|[email protected]")+ .await+ .unwrap()+ .is_empty()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn removing_a_google_source_restores_the_surviving_calendar_copy(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = grant_and_provider_ids(&repo, link_id).await;+ let secondary_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "team".to_string(),+ name: "Team".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("writer".to_string()),+ is_primary: false,+ is_selected: true,+ },+ )+ .await+ .unwrap();++ // The same iCalUID observed through two calendars of one inbox: two+ // sources, one canonical entity.+ let mut primary_copy = timed_upsert(+ owner_id,+ link_id,+ (account_id, primary_id),+ "[email protected]",+ "Primary copy",+ 2,+ );+ primary_copy.event.is_read_only = false;+ let event_id = repo+ .upsert_event(CalendarEventWrite::UserMutation(primary_copy))+ .await+ .unwrap();+ let mut team_copy = timed_upsert(+ owner_id,+ link_id,+ (account_id, secondary_id),+ "[email protected]",+ "Team copy",+ 1,+ );+ team_copy.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id: secondary_id,+ provider_event_id: "team-copy-id".to_string(),+ provider_recurring_event_id: None,+ provider_etag: None,+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event(CalendarEventWrite::UserMutation(team_copy))+ .await+ .unwrap();++ repo.remove_google_source(account_id, primary_id, "[email protected]")+ .await+ .unwrap();+ let row = sqlx::query!(+ r#"+ SELECT+ (SELECT title FROM calendar_events WHERE id = $1) AS "title!",+ (SELECT calendar_id FROM calendar_event_sources WHERE event_id = $1) AS "calendar_id",+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS "sources!"+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ (row.title.as_str(), row.calendar_id, row.sources),+ ("Team copy", Some(secondary_id), 1),+ "the surviving calendar's copy is promoted back to canonical"+ );++ repo.remove_google_source(account_id, secondary_id, "team-copy-id")+ .await+ .unwrap();+ let remaining = sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_events WHERE id = $1"#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(remaining, 0, "an event with no surviving source is deleted");+}diff --git a/packages/sdk/generated/email/index.ts b/packages/sdk/generated/email/index.tsindex 9ae698ed07..10928acce9 100644--- a/packages/sdk/generated/email/index.ts+++ b/packages/sdk/generated/email/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value } from './types.gen';+export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarMutationApiError, CalendarMutationErrorCode, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, VisibleCalendar } from './types.gen';diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.tsindex d976acbe05..6943c54780 100644--- a/packages/sdk/generated/email/sdk.gen.ts+++ b/packages/sdk/generated/email/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';+import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -57,6 +57,62 @@ export class Sdk extends HeyApiClient {Sdk.__registry.set(this, args?.key);}+ /**+ * List the requester's visible calendars for pickers and filters.+ */+ public listCalendars<ThrowOnError extends boolean = false>(options?: Options<ListCalendarsData, ThrowOnError>): RequestResult<ListCalendarsResponses, ListCalendarsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListCalendarsResponses, ListCalendarsErrors, ThrowOnError>({ url: '/calendar/calendars', ...options });+ }++ /**+ * Create a calendar event and return its synced entity.+ */+ public createCalendarEvent<ThrowOnError extends boolean = false>(options: Options<CreateCalendarEventData, ThrowOnError>): RequestResult<CreateCalendarEventResponses, CreateCalendarEventErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateCalendarEventResponses, CreateCalendarEventErrors, ThrowOnError>({+ url: '/calendar/events',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Delete a calendar event at its provider.+ */+ public deleteCalendarEvent<ThrowOnError extends boolean = false>(options: Options<DeleteCalendarEventData, ThrowOnError>): RequestResult<DeleteCalendarEventResponses, DeleteCalendarEventErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteCalendarEventResponses, DeleteCalendarEventErrors, ThrowOnError>({ url: '/calendar/events/{event_id}', ...options });+ }++ /**+ * Update fields of a calendar event and return its synced entity.+ */+ public updateCalendarEvent<ThrowOnError extends boolean = false>(options: Options<UpdateCalendarEventData, ThrowOnError>): RequestResult<UpdateCalendarEventResponses, UpdateCalendarEventErrors, ThrowOnError> {+ return (options.client ?? this.client).patch<UpdateCalendarEventResponses, UpdateCalendarEventErrors, ThrowOnError>({+ url: '/calendar/events/{event_id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Set the requester's RSVP on a calendar event and return its synced entity.+ */+ public rsvpCalendarEvent<ThrowOnError extends boolean = false>(options: Options<RsvpCalendarEventData, ThrowOnError>): RequestResult<RsvpCalendarEventResponses, RsvpCalendarEventErrors, ThrowOnError> {+ return (options.client ?? this.client).put<RsvpCalendarEventResponses, RsvpCalendarEventErrors, ThrowOnError>({+ url: '/calendar/events/{event_id}/rsvp',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Get an attachment by ID.*/diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex de4a7f93b8..0f74603b5c 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -500,6 +500,11 @@ export type AttachmentForwarded = {size_bytes?: number | null;};+/**+ * RSVP state for an attendee.+ */+export type AttendeeResponseStatus = 'needs_action' | 'accepted' | 'declined' | 'tentative';+export type BackfillJob = {created_at: string;fusionauth_user_id: string;@@ -529,6 +534,165 @@ export type BlockSenderRequest = {email_address: string;};+/**+ * An attendee on a calendar event.+ */+export type CalendarAttendee = {+ /**+ * Optional attendee comment.+ */+ comment?: string | null;+ /**+ * Provider display name.+ */+ displayName?: string | null;+ /**+ * Normalized email address.+ */+ email: string;+ /**+ * Whether attendance is optional.+ */+ isOptional: boolean;+ /**+ * Whether this attendee is the organizer.+ */+ isOrganizer: boolean;+ /**+ * Whether this attendee represents the connected account.+ */+ isSelf: boolean;+ /**+ * RSVP state.+ */+ responseStatus: AttendeeResponseStatus;+};++/**+ * An attendee supplied to a calendar mutation.+ */+export type CalendarAttendeeInputBody = {+ /**+ * Attendee email address.+ */+ email: string;+ /**+ * Whether attendance is optional.+ */+ isOptional?: boolean;+};++/**+ * How much of a recurring series a deletion removes.+ */+export type CalendarDeletionScopeParam = 'all' | 'this_event' | 'this_and_following';++/**+ * A stable, first-class Macro calendar event entity.+ */+export type CalendarEvent = {+ /**+ * Attendees, keyed by email during persistence.+ */+ attendees: Array<CalendarAttendee>;+ /**+ * Calendar the canonical source belongs to, when known. Absent only in+ * projections stored before calendars were attributed.+ */+ calendarId?: string | null;+ /**+ * Direct join URL when known.+ */+ conferenceUrl?: string | null;+ /**+ * Entity creation time.+ */+ createdAt: string;+ /**+ * Optional event body.+ */+ description?: string | null;+ /**+ * RFC 5545 UID used to reconcile provider and email sources.+ */+ icalUid: string;+ /**+ * Macro entity identifier.+ */+ id: string;+ /**+ * Whether the current user can edit the canonical source.+ */+ isReadOnly: boolean;+ /**+ * Optional physical or virtual location label.+ */+ location?: string | null;+ /**+ * Organizer email.+ */+ organizerEmail?: string | null;+ /**+ * Organizer display name.+ */+ organizerName?: string | null;+ /**+ * Macro user who owns this event entity.+ */+ ownerId: string;+ /**+ * Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ */+ recurrenceLines: Array<string>;+ /**+ * Provider/iCalendar sequence number.+ */+ sequence: number;+ /**+ * Event status.+ */+ status: EventStatus;+ /**+ * Timed or all-day shape.+ */+ time: EventTime;+ /**+ * Display title.+ */+ title: string;+ /**+ * Availability behavior.+ */+ transparency: EventTransparency;+ /**+ * Entity update time.+ */+ updatedAt: string;+ /**+ * Event visibility.+ */+ visibility: EventVisibility;+};++/**+ * HTTP error body returned by calendar mutation endpoints.+ */+export type CalendarMutationApiError = {+ /**+ * Machine-readable failure category.+ */+ code: CalendarMutationErrorCode;+ /**+ * Human-readable failure description.+ */+ message: string;+};++/**+ * Machine-readable failure category for calendar mutations.+ */+export type CalendarMutationErrorCode = 'not_found' | 'read_only' | 'no_writable_calendar' | 'not_attendee' | 'invalid_input' | 'reauth_required' | 'provider_rejected' | 'retryable' | 'persist_failed';+export type CancelBackfillParams = {job_id: string;};@@ -559,6 +723,48 @@ export type ContactInfoWithInteraction = ContactInfoLegacy & {last_interaction: string;};+/**+ * Request body creating a calendar event on the requester's calendar.+ */+export type CreateCalendarEventRequest = {+ /**+ * Invited attendees.+ */+ attendees?: Array<CalendarAttendeeInputBody>;+ /**+ * Exact calendar to create the event on; takes precedence over the+ * inbox default.+ */+ calendarId?: string | null;+ /**+ * Optional event body.+ */+ description?: string | null;+ /**+ * Connected inbox whose primary calendar receives the event; defaults+ * to the requester's primary inbox.+ */+ emailLinkId?: string | null;+ /**+ * Optional location label.+ */+ location?: string | null;+ /**+ * Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ */+ recurrenceLines?: Array<string>;+ /**+ * Timed or all-day shape.+ */+ time: EventTime;+ /**+ * Display title.+ */+ title: string;+ transparency?: null | EventTransparency;+ visibility?: null | EventVisibility;+};+/*** Request body for creating a draft.*/@@ -615,6 +821,54 @@ export type ErrorResponse = {message: string;};+/**+ * Canonical event status.+ */+export type EventStatus = 'confirmed' | 'tentative' | 'cancelled';++/**+ * The mutually exclusive time shape of a calendar event.+ *+ * Fields are renamed per variant rather than with `rename_all_fields`+ * because utoipa only honors variant-level serde renames when it+ * derives the OpenAPI schema.+ */+export type EventTime = {+ /**+ * Exclusive end instant.+ */+ endsAt: string;+ kind: 'timed';+ /**+ * Inclusive start instant.+ */+ startsAt: string;+ /**+ * Original IANA time-zone identifier, when supplied.+ */+ timeZone?: string | null;+} | {+ /**+ * Exclusive local end date.+ */+ endDate: string;+ kind: 'allDay';+ /**+ * Inclusive local start date.+ */+ startDate: string;+};++/**+ * Whether an event blocks availability.+ */+export type EventTransparency = 'opaque' | 'transparent';++/**+ * Visibility of event details.+ */+export type EventVisibility = 'default' | 'public' | 'private' | 'confidential';+/*** The response returned from the get backfill job endpoint*/@@ -763,6 +1017,16 @@ export type ListBlockedResponse = {blocked_emails: Array<string>;};+/**+ * Calendars visible to the requester across connected and delegated inboxes.+ */+export type ListCalendarsResponse = {+ /**+ * Primaries and writable calendars first.+ */+ calendars: Array<VisibleCalendar>;+};+export type ListContactsResponse = {/*** the thread, with messages inside@@ -919,6 +1183,16 @@ export type ResyncResponse = {backfill_job_id: string;};+/**+ * Request body setting the requester's RSVP on an event.+ */+export type RsvpCalendarEventRequest = {+ /**+ * The response to record for the connected account.+ */+ response: AttendeeResponseStatus;+};+/*** Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).*/@@ -1040,6 +1314,35 @@ export type UnresolvedSignatureImagesError = {unresolved_image_count: number;};+/**+ * Request body patching an event; omitted fields are left untouched.+ */+export type UpdateCalendarEventRequest = {+ /**+ * Replacement attendee list.+ */+ attendees?: Array<CalendarAttendeeInputBody> | null;+ /**+ * Replacement description; an empty string clears it.+ */+ description?: string | null;+ /**+ * Replacement location; an empty string clears it.+ */+ location?: string | null;+ /**+ * Replacement recurrence properties; an empty list clears them.+ */+ recurrenceLines?: Array<string> | null;+ time?: null | EventTime;+ /**+ * Replacement title; an empty string clears it.+ */+ title?: string | null;+ transparency?: null | EventTransparency;+ visibility?: null | EventVisibility;+};+export type UpdateLabelBatchRequest = {label_id: string;message_ids: Array<string>;@@ -1129,6 +1432,261 @@ export type UserProvider = 'GMAIL';export type Value = unknown;+/**+ * A calendar visible to a requester, listed for pickers and filters.+ */+export type VisibleCalendar = {+ /**+ * Provider color.+ */+ color?: string | null;+ /**+ * Connected inbox address, for grouping in multi-inbox pickers.+ */+ emailAddress: string;+ /**+ * Connected inbox that syncs this calendar.+ */+ emailLinkId: string;+ /**+ * Persisted Macro calendar identifier.+ */+ id: string;+ /**+ * Whether this is its account's primary calendar.+ */+ isPrimary: boolean;+ /**+ * Whether the grant can create and modify events on this calendar.+ */+ isWritable: boolean;+ /**+ * Provider display name.+ */+ name: string;+};++export type ListCalendarsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/calendar/calendars';+};++export type ListCalendarsErrors = {+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Transient failure+ */+ 503: CalendarMutationApiError;+};++export type ListCalendarsError = ListCalendarsErrors[keyof ListCalendarsErrors];++export type ListCalendarsResponses = {+ /**+ * Calendars visible to the requester+ */+ 200: ListCalendarsResponse;+};++export type ListCalendarsResponse2 = ListCalendarsResponses[keyof ListCalendarsResponses];++export type CreateCalendarEventData = {+ body: CreateCalendarEventRequest;+ path?: never;+ query?: never;+ url: '/calendar/events';+};++export type CreateCalendarEventErrors = {+ /**+ * Invalid event fields+ */+ 400: CalendarMutationApiError;+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Calendar is read-only or needs reauthorization+ */+ 403: CalendarMutationApiError;+ /**+ * No writable calendar or the provider rejected the event+ */+ 409: CalendarMutationApiError;+ /**+ * Transient provider failure+ */+ 503: CalendarMutationApiError;+};++export type CreateCalendarEventError = CreateCalendarEventErrors[keyof CreateCalendarEventErrors];++export type CreateCalendarEventResponses = {+ /**+ * The created calendar event+ */+ 201: CalendarEvent;+};++export type CreateCalendarEventResponse = CreateCalendarEventResponses[keyof CreateCalendarEventResponses];++export type DeleteCalendarEventData = {+ body?: never;+ path: {+ /**+ * Calendar event entity id+ */+ event_id: string;+ };+ query?: {+ /**+ * Deletion scope; defaults to the entire event or series.+ */+ scope?: CalendarDeletionScopeParam;+ /**+ * Original-start key of the occurrence a scoped deletion targets.+ */+ recurrenceId?: string;+ };+ url: '/calendar/events/{event_id}';+};++export type DeleteCalendarEventErrors = {+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Calendar is read-only or needs reauthorization+ */+ 403: CalendarMutationApiError;+ /**+ * Event not found+ */+ 404: CalendarMutationApiError;+ /**+ * The provider rejected the deletion+ */+ 409: CalendarMutationApiError;+ /**+ * Transient provider failure+ */+ 503: CalendarMutationApiError;+};++export type DeleteCalendarEventError = DeleteCalendarEventErrors[keyof DeleteCalendarEventErrors];++export type DeleteCalendarEventResponses = {+ /**+ * The event was deleted+ */+ 204: void;+};++export type DeleteCalendarEventResponse = DeleteCalendarEventResponses[keyof DeleteCalendarEventResponses];++export type UpdateCalendarEventData = {+ body: UpdateCalendarEventRequest;+ path: {+ /**+ * Calendar event entity id+ */+ event_id: string;+ };+ query?: never;+ url: '/calendar/events/{event_id}';+};++export type UpdateCalendarEventErrors = {+ /**+ * Invalid event fields+ */+ 400: CalendarMutationApiError;+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Calendar is read-only or needs reauthorization+ */+ 403: CalendarMutationApiError;+ /**+ * Event not found+ */+ 404: CalendarMutationApiError;+ /**+ * The provider rejected the update+ */+ 409: CalendarMutationApiError;+ /**+ * Transient provider failure+ */+ 503: CalendarMutationApiError;+};++export type UpdateCalendarEventError = UpdateCalendarEventErrors[keyof UpdateCalendarEventErrors];++export type UpdateCalendarEventResponses = {+ /**+ * The updated calendar event+ */+ 200: CalendarEvent;+};++export type UpdateCalendarEventResponse = UpdateCalendarEventResponses[keyof UpdateCalendarEventResponses];++export type RsvpCalendarEventData = {+ body: RsvpCalendarEventRequest;+ path: {+ /**+ * Calendar event entity id+ */+ event_id: string;+ };+ query?: never;+ url: '/calendar/events/{event_id}/rsvp';+};++export type RsvpCalendarEventErrors = {+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Calendar is read-only or needs reauthorization+ */+ 403: CalendarMutationApiError;+ /**+ * Event not found+ */+ 404: CalendarMutationApiError;+ /**+ * The connected account is not an attendee+ */+ 409: CalendarMutationApiError;+ /**+ * Transient provider failure+ */+ 503: CalendarMutationApiError;+};++export type RsvpCalendarEventError = RsvpCalendarEventErrors[keyof RsvpCalendarEventErrors];++export type RsvpCalendarEventResponses = {+ /**+ * The updated calendar event+ */+ 200: CalendarEvent;+};++export type RsvpCalendarEventResponse = RsvpCalendarEventResponses[keyof RsvpCalendarEventResponses];+export type GetAttachmentData = {body?: never;path: {diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex d6747f19b7..0e184082bb 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -1202,6 +1202,11 @@ export type CalendarEvent = {* Attendees, keyed by email during persistence.*/attendees: Array<CalendarAttendee>;+ /**+ * Calendar the canonical source belongs to, when known. Absent only in+ * projections stored before calendars were attributed.+ */+ calendarId?: string | null;/*** Direct join URL when known.*/diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex 8825787b02..f3320ff972 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -10,6 +10,371 @@"version": "0.1.0"},"paths": {+ "/calendar/calendars": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "List the requester's visible calendars for pickers and filters.",+ "operationId": "list_calendars",+ "responses": {+ "200": {+ "description": "Calendars visible to the requester",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListCalendarsResponse"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "503": {+ "description": "Transient failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events": {+ "post": {+ "tags": ["calendar_events"],+ "summary": "Create a calendar event and return its synced entity.",+ "operationId": "create_calendar_event",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "The created calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "400": {+ "description": "Invalid event fields",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "No writable calendar or the provider rejected the event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events/{event_id}": {+ "delete": {+ "tags": ["calendar_events"],+ "summary": "Delete a calendar event at its provider.",+ "operationId": "delete_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "scope",+ "in": "query",+ "description": "Deletion scope; defaults to the entire event or series.",+ "required": false,+ "schema": {+ "$ref": "#/components/schemas/CalendarDeletionScopeParam"+ }+ },+ {+ "name": "recurrenceId",+ "in": "query",+ "description": "Original-start key of the occurrence a scoped deletion targets.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "The event was deleted"+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The provider rejected the deletion",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["calendar_events"],+ "summary": "Update fields of a calendar event and return its synced entity.",+ "operationId": "update_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The updated calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "400": {+ "description": "Invalid event fields",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The provider rejected the update",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },+ "/calendar/events/{event_id}/rsvp": {+ "put": {+ "tags": ["calendar_events"],+ "summary": "Set the requester's RSVP on a calendar event and return its synced entity.",+ "operationId": "rsvp_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "Calendar event entity id",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RsvpCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The updated calendar event",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarEvent"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "Calendar is read-only or needs reauthorization",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "404": {+ "description": "Event not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "409": {+ "description": "The connected account is not an attendee",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ },+ "503": {+ "description": "Transient provider failure",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarMutationApiError"+ }+ }+ }+ }+ }+ }+ },"/email/attachments/{id}": {"get": {"tags": ["Attachments"],@@ -3825,81 +4190,291 @@"type": ["string", "null"],"description": "The Gmail attachment ID for fetching data from Gmail API."},- "size_bytes": {- "type": ["integer", "null"],- "format": "int64",- "description": "File size in bytes."+ "size_bytes": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "File size in bytes."+ }+ }+ },+ "AttendeeResponseStatus": {+ "type": "string",+ "description": "RSVP state for an attendee.",+ "enum": ["needs_action", "accepted", "declined", "tentative"]+ },+ "BackfillJob": {+ "type": "object",+ "required": [+ "id",+ "fusionauth_user_id",+ "total_threads",+ "status",+ "threads_retrieved_count",+ "created_at",+ "updated_at"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "format": "date-time"+ },+ "fusionauth_user_id": {+ "type": "string"+ },+ "id": {+ "type": "string",+ "format": "uuid"+ },+ "link_id": {+ "type": ["string", "null"],+ "format": "uuid"+ },+ "status": {+ "$ref": "#/components/schemas/BackfillJobStatus"+ },+ "threads_requested_limit": {+ "type": ["integer", "null"],+ "format": "int32"+ },+ "threads_retrieved_count": {+ "type": "integer",+ "format": "int32"+ },+ "total_threads": {+ "type": "integer",+ "format": "int32"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time"+ }+ }+ },+ "BackfillJobStatus": {+ "type": "string",+ "enum": ["Init", "InProgress", "Complete", "Cancelled", "Failed"]+ },+ "BackfillStatus": {+ "type": "string",+ "description": "Progress/terminal state of a backfill job for [`RefreshEmailEvent::Backfill`].",+ "enum": ["progress", "complete", "failed"]+ },+ "BlockSenderRequest": {+ "type": "object",+ "description": "Request to block a sender.",+ "required": ["email_address"],+ "properties": {+ "email_address": {+ "type": "string",+ "description": "The email address of the sender to block."+ }+ }+ },+ "CalendarAttendee": {+ "type": "object",+ "description": "An attendee on a calendar event.",+ "required": [+ "email",+ "responseStatus",+ "isOrganizer",+ "isOptional",+ "isSelf"+ ],+ "properties": {+ "comment": {+ "type": ["string", "null"],+ "description": "Optional attendee comment."+ },+ "displayName": {+ "type": ["string", "null"],+ "description": "Provider display name."+ },+ "email": {+ "type": "string",+ "description": "Normalized email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."+ },+ "isOrganizer": {+ "type": "boolean",+ "description": "Whether this attendee is the organizer."+ },+ "isSelf": {+ "type": "boolean",+ "description": "Whether this attendee represents the connected account."+ },+ "responseStatus": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "RSVP state."+ }+ }+ },+ "CalendarAttendeeInputBody": {+ "type": "object",+ "description": "An attendee supplied to a calendar mutation.",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "Attendee email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."}}},- "BackfillJob": {+ "CalendarDeletionScopeParam": {+ "type": "string",+ "description": "How much of a recurring series a deletion removes.",+ "enum": ["all", "this_event", "this_and_following"]+ },+ "CalendarEvent": {"type": "object",+ "description": "A stable, first-class Macro calendar event entity.","required": ["id",- "fusionauth_user_id",- "total_threads",+ "ownerId",+ "icalUid",+ "title","status",- "threads_retrieved_count",- "created_at",- "updated_at"+ "visibility",+ "transparency",+ "time",+ "recurrenceLines",+ "sequence",+ "isReadOnly",+ "attendees",+ "createdAt",+ "updatedAt"],"properties": {- "created_at": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees, keyed by email during persistence."+ },+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Direct join URL when known."+ },+ "createdAt": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "Entity creation time."},- "fusionauth_user_id": {- "type": "string"+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "icalUid": {+ "type": "string",+ "description": "RFC 5545 UID used to reconcile provider and email sources."},"id": {"type": "string",- "format": "uuid"+ "format": "uuid",+ "description": "Macro entity identifier."},- "link_id": {+ "isReadOnly": {+ "type": "boolean",+ "description": "Whether the current user can edit the canonical source."+ },+ "location": {"type": ["string", "null"],- "format": "uuid"+ "description": "Optional physical or virtual location label."},- "status": {- "$ref": "#/components/schemas/BackfillJobStatus"+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer email."},- "threads_requested_limit": {- "type": ["integer", "null"],- "format": "int32"+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer display name."},- "threads_retrieved_count": {- "type": "integer",- "format": "int32"+ "ownerId": {+ "type": "string",+ "description": "Macro user who owns this event entity."},- "total_threads": {+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "sequence": {"type": "integer",- "format": "int32"+ "format": "int32",+ "description": "Provider/iCalendar sequence number.",+ "minimum": 0},- "updated_at": {+ "status": {+ "$ref": "#/components/schemas/EventStatus",+ "description": "Event status."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {"type": "string",- "format": "date-time"+ "description": "Display title."+ },+ "transparency": {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity update time."+ },+ "visibility": {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."}}},- "BackfillJobStatus": {- "type": "string",- "enum": ["Init", "InProgress", "Complete", "Cancelled", "Failed"]- },- "BackfillStatus": {- "type": "string",- "description": "Progress/terminal state of a backfill job for [`RefreshEmailEvent::Backfill`].",- "enum": ["progress", "complete", "failed"]- },- "BlockSenderRequest": {+ "CalendarMutationApiError": {"type": "object",- "description": "Request to block a sender.",- "required": ["email_address"],+ "description": "HTTP error body returned by calendar mutation endpoints.",+ "required": ["code", "message"],"properties": {- "email_address": {+ "code": {+ "$ref": "#/components/schemas/CalendarMutationErrorCode",+ "description": "Machine-readable failure category."+ },+ "message": {"type": "string",- "description": "The email address of the sender to block."+ "description": "Human-readable failure description."}}},+ "CalendarMutationErrorCode": {+ "type": "string",+ "description": "Machine-readable failure category for calendar mutations.",+ "enum": [+ "not_found",+ "read_only",+ "no_writable_calendar",+ "not_attendee",+ "invalid_input",+ "reauth_required",+ "provider_rejected",+ "retryable",+ "persist_failed"+ ]+ },"CancelBackfillParams": {"type": "object","required": ["job_id"],@@ -3986,6 +4561,75 @@}]},+ "CreateCalendarEventRequest": {+ "type": "object",+ "description": "Request body creating a calendar event on the requester's calendar.",+ "required": ["title", "time"],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"+ },+ "description": "Invited attendees."+ },+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Exact calendar to create the event on; takes precedence over the\ninbox default."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "emailLinkId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Connected inbox whose primary calendar receives the event; defaults\nto the requester's primary inbox."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Optional location label."+ },+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ },+ "transparency": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ }+ ]+ },+ "visibility": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."+ }+ ]+ }+ }+ },"CreateDraftRequest": {"type": "object","description": "Request body for creating a draft.",@@ -4048,6 +4692,72 @@}}},+ "EventStatus": {+ "type": "string",+ "description": "Canonical event status.",+ "enum": ["confirmed", "tentative", "cancelled"]+ },+ "EventTime": {+ "oneOf": [+ {+ "type": "object",+ "description": "An event with absolute instants.",+ "required": ["startsAt", "endsAt", "kind"],+ "properties": {+ "endsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Exclusive end instant."+ },+ "kind": {+ "type": "string",+ "enum": ["timed"]+ },+ "startsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Inclusive start instant."+ },+ "timeZone": {+ "type": ["string", "null"],+ "description": "Original IANA time-zone identifier, when supplied."+ }+ }+ },+ {+ "type": "object",+ "description": "An all-day event using RFC 5545's exclusive end date.",+ "required": ["startDate", "endDate", "kind"],+ "properties": {+ "endDate": {+ "type": "string",+ "format": "date",+ "description": "Exclusive local end date."+ },+ "kind": {+ "type": "string",+ "enum": ["allDay"]+ },+ "startDate": {+ "type": "string",+ "format": "date",+ "description": "Inclusive local start date."+ }+ }+ }+ ],+ "description": "The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema."+ },+ "EventTransparency": {+ "type": "string",+ "description": "Whether an event blocks availability.",+ "enum": ["opaque", "transparent"]+ },+ "EventVisibility": {+ "type": "string",+ "description": "Visibility of event details.",+ "enum": ["default", "public", "private", "confidential"]+ },"GetActiveBackfillJobResponse": {"type": "object","description": "The response returned from the get backfill job endpoint",@@ -4337,6 +5047,20 @@}}},+ "ListCalendarsResponse": {+ "type": "object",+ "description": "Calendars visible to the requester across connected and delegated inboxes.",+ "required": ["calendars"],+ "properties": {+ "calendars": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/VisibleCalendar"+ },+ "description": "Primaries and writable calendars first."+ }+ }+ },"ListContactsResponse": {"type": "object","required": ["contacts"],@@ -4839,6 +5563,17 @@}}},+ "RsvpCalendarEventRequest": {+ "type": "object",+ "description": "Request body setting the requester's RSVP on an event.",+ "required": ["response"],+ "properties": {+ "response": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "The response to record for the connected account."+ }+ }+ },"SendMessageRequest": {"type": "object","description": "Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).",@@ -5090,6 +5825,71 @@}}},+ "UpdateCalendarEventRequest": {+ "type": "object",+ "description": "Request body patching an event; omitted fields are left untouched.",+ "properties": {+ "attendees": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"+ },+ "description": "Replacement attendee list."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Replacement description; an empty string clears it."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Replacement location; an empty string clears it."+ },+ "recurrenceLines": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Replacement recurrence properties; an empty list clears them."+ },+ "time": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTime",+ "description": "Replacement time."+ }+ ]+ },+ "title": {+ "type": ["string", "null"],+ "description": "Replacement title; an empty string clears it."+ },+ "transparency": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Replacement transparency."+ }+ ]+ },+ "visibility": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Replacement visibility."+ }+ ]+ }+ }+ },"UpdateLabelBatchRequest": {"type": "object","required": ["message_ids", "label_id", "value"],@@ -5250,7 +6050,51 @@"type": "string","enum": ["GMAIL"]},- "Value": {}+ "Value": {},+ "VisibleCalendar": {+ "type": "object",+ "description": "A calendar visible to a requester, listed for pickers and filters.",+ "required": [+ "id",+ "emailLinkId",+ "emailAddress",+ "name",+ "isPrimary",+ "isWritable"+ ],+ "properties": {+ "color": {+ "type": ["string", "null"],+ "description": "Provider color."+ },+ "emailAddress": {+ "type": "string",+ "description": "Connected inbox address, for grouping in multi-inbox pickers."+ },+ "emailLinkId": {+ "type": "string",+ "format": "uuid",+ "description": "Connected inbox that syncs this calendar."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Persisted Macro calendar identifier."+ },+ "isPrimary": {+ "type": "boolean",+ "description": "Whether this is its account's primary calendar."+ },+ "isWritable": {+ "type": "boolean",+ "description": "Whether the grant can create and modify events on this calendar."+ },+ "name": {+ "type": "string",+ "description": "Provider display name."+ }+ }+ }}},"tags": [diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 3d6b191fa9..c586734d05 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -12766,6 +12766,11 @@},"description": "Attendees, keyed by email during persistence."},+ "calendarId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed."+ },"conferenceUrl": {"type": ["string", "null"],"description": "Direct join URL when known."diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex bd856d295b..772066f6f0 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -159,15 +159,20 @@ export const emailExcluded = [export const emailBacklog = ['addDraftAttachment','addForwardedAttachment',+ 'createCalendarEvent','createDraft',+ 'deleteCalendarEvent','deleteDraft','deleteEmailFilter','deleteScheduledDraft','getScheduledMessages',+ 'listCalendars','listContacts','listEmailFilters','removeDraftAttachment','removeForwardedAttachment',+ 'rsvpCalendarEvent',+ 'updateCalendarEvent','upsertEmailFilter','upsertScheduledMessage',] as const satisfies readonly (keyof EmailSdk)[];diff --git a/services/email_service/Cargo.toml b/services/email_service/Cargo.tomlindex 93414704e4..f3c5cc418e 100644--- a/services/email_service/Cargo.toml+++ b/services/email_service/Cargo.toml@@ -76,7 +76,7 @@ sfs_map = []sfs_delete = [][dependencies]-calendar_events = { path = "../../crates/calendar_events", features = ["google", "postgres"] }+calendar_events = { path = "../../crates/calendar_events", features = ["google", "inbound", "postgres"] }ammonia = "4.1.4"anyhow = { workspace = true }authentication_service_client = { path = "../../crates/authentication_service_client" }diff --git a/services/email_service/src/api/context.rs b/services/email_service/src/api/context.rsindex ef068f00c1..3c12214df4 100644--- a/services/email_service/src/api/context.rs+++ b/services/email_service/src/api/context.rs@@ -1,5 +1,8 @@use axum::extract::FromRef;-use calendar_events::{domain::service::CalendarService, outbound::pg::PgCalendarRepository};+use calendar_events::{+ domain::{mutations::CalendarMutationServiceImpl, service::CalendarService},+ outbound::{google::GoogleCalendarClient, pg::PgCalendarRepository},+};use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,@@ -9,6 +12,8 @@ use email::{},outbound::{EmailPgRepo, GmailTokenProviderImpl},};+use email_service::calendar_tokens::CalendarTokenProviderAdapter;+use email_service::pubsub::calendar_backfill_adapters::RedisCalendarRequestGate;use email_service::config::Config;use email_service::util::redis::RedisClient;@@ -28,6 +33,11 @@ use tokio_util::task::TaskTracker;pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;pub(crate) type CalendarGrantService = CalendarService<PgCalendarRepository>;+pub(crate) type CalendarMutationSvc = CalendarMutationServiceImpl<+ PgCalendarRepository,+ GoogleCalendarClient<RedisCalendarRequestGate>,+ CalendarTokenProviderAdapter,+>;pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;pub(crate) type EmailEntityAccessManagementService =EntityAccessManagementServiceImpl<entity_access_management::outbound::PgRepository>;@@ -66,4 +76,5 @@ pub(crate) struct ApiContext {pub gmail_token_state: GmailTokenState<GmailTokenProviderImpl>,pub macro_event_broker: Arc<EmailEventBroker>,pub calendar_service: Arc<CalendarGrantService>,+ pub calendar_mutation_service: Arc<CalendarMutationSvc>,}diff --git a/services/email_service/src/api/mod.rs b/services/email_service/src/api/mod.rsindex f139ef057c..32c4494885 100644--- a/services/email_service/src/api/mod.rs+++ b/services/email_service/src/api/mod.rs@@ -1,5 +1,6 @@use anyhow::Context;use axum::Router;+use calendar_events::inbound::mutation_router::CalendarMutationRouterState;use context::ApiContext;use tower::ServiceBuilder;use tower_http::{compression::CompressionLayer, trace::TraceLayer};@@ -49,9 +50,23 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {}fn api_router(state: ApiContext) -> Router<ApiContext> {+ // Calendar mutations follow the calendar sync kill switch: without sync+ // a provider write would never be reflected locally.+ let calendar_router = if state.config.calendar_sync_enabled {+ calendar_watch::router().merge(+ calendar_events::inbound::mutation_router::calendar_mutation_router(+ CalendarMutationRouterState::new(+ state.calendar_mutation_service.clone(),+ state.authorization_state.clone(),+ ),+ ),+ )+ } else {+ calendar_watch::router()+ };Router::new().nest("/email", email::router(state)).nest("/gmail", gmail::router()).nest("/internal", internal::router())- .nest("/calendar", calendar_watch::router())+ .nest("/calendar", calendar_router)}diff --git a/services/email_service/src/api/swagger.rs b/services/email_service/src/api/swagger.rsindex 678fea66ca..8a4e9b3791 100644--- a/services/email_service/src/api/swagger.rs+++ b/services/email_service/src/api/swagger.rs@@ -105,6 +105,11 @@ use utoipa::OpenApi;email::contacts::list_blocked::handler,email::sync::disable::disable_handler,email::settings::patch::patch_settings_handler,+ calendar_events::inbound::mutation_router::list_calendars,+ calendar_events::inbound::mutation_router::create_calendar_event,+ calendar_events::inbound::mutation_router::update_calendar_event,+ calendar_events::inbound::mutation_router::delete_calendar_event,+ calendar_events::inbound::mutation_router::rsvp_calendar_event,),components(schemas(@@ -186,7 +191,24 @@ use utoipa::OpenApi;service::thread::Thread,service::message::Message,PatchSettingsRequest,- PatchSettingsResponse+ PatchSettingsResponse,+ // Calendar mutation types+ calendar_events::inbound::mutation_router::CreateCalendarEventRequest,+ calendar_events::inbound::mutation_router::ListCalendarsResponse,+ calendar_events::domain::models::VisibleCalendar,+ calendar_events::inbound::mutation_router::UpdateCalendarEventRequest,+ calendar_events::inbound::mutation_router::RsvpCalendarEventRequest,+ calendar_events::inbound::mutation_router::CalendarAttendeeInputBody,+ calendar_events::inbound::mutation_router::CalendarMutationApiError,+ calendar_events::inbound::mutation_router::CalendarMutationErrorCode,+ calendar_events::inbound::mutation_router::CalendarDeletionScopeParam,+ calendar_events::domain::models::CalendarEvent,+ calendar_events::domain::models::CalendarAttendee,+ calendar_events::domain::models::AttendeeResponseStatus,+ calendar_events::domain::models::EventTime,+ calendar_events::domain::models::EventStatus,+ calendar_events::domain::models::EventVisibility,+ calendar_events::domain::models::EventTransparency),),tags(diff --git a/services/email_service/src/calendar_tokens.rs b/services/email_service/src/calendar_tokens.rsnew file mode 100644index 0000000000..cb9d156883--- /dev/null+++ b/services/email_service/src/calendar_tokens.rs@@ -0,0 +1,65 @@+//! Access-token adapter for user-initiated calendar mutations.++use authentication_service_client::{AuthServiceClient, error::AuthServiceClientError};+use calendar_events::domain::{+ models::CalendarLinkTokenIdentity,+ ports::{CalendarAccessTokenProvider, CalendarTokenError},+};+use email::outbound::fetch_gmail_access_token;+use email_utils::token_cache_key::TokenCacheKey;+use redis::aio::MultiplexedConnection;+use std::sync::Arc;++/// Mints Google access tokens for calendar mutations through the same+/// Redis-cached auth-service path Gmail requests use.+#[derive(Clone)]+pub struct CalendarTokenProviderAdapter {+ redis_conn: MultiplexedConnection,+ auth_service_client: Arc<AuthServiceClient>,+}++impl CalendarTokenProviderAdapter {+ /// Construct the adapter from the shared Redis connection and auth client.+ pub fn new(+ redis_conn: MultiplexedConnection,+ auth_service_client: Arc<AuthServiceClient>,+ ) -> Self {+ Self {+ redis_conn,+ auth_service_client,+ }+ }+}++impl CalendarAccessTokenProvider for CalendarTokenProviderAdapter {+ async fn fetch_access_token(+ &self,+ identity: &CalendarLinkTokenIdentity,+ ) -> Result<String, CalendarTokenError> {+ let key = TokenCacheKey::new(+ &identity.fusionauth_user_id,+ &identity.email_address,+ &identity.provider,+ );+ fetch_gmail_access_token(&key, &self.redis_conn, &self.auth_service_client)+ .await+ .map_err(|error| {+ let reauth = error.chain().any(|cause| {+ cause+ .downcast_ref::<AuthServiceClientError>()+ .is_some_and(|cause| {+ matches!(+ cause,+ AuthServiceClientError::Forbidden+ | AuthServiceClientError::NotFound+ )+ })+ });+ if reauth {+ CalendarTokenError::ReauthRequired(format!("{error:?}"))+ } else {+ CalendarTokenError::Transient(format!("{error:?}"))+ }+ })+ }+}diff --git a/services/email_service/src/lib.rs b/services/email_service/src/lib.rsindex a0ecf5aae0..f9b1b6557d 100644--- a/services/email_service/src/lib.rs+++ b/services/email_service/src/lib.rs@@ -4,6 +4,8 @@ pub mod backfill_completion_service;pub mod backfill_init_service;/// Durable publication of grant-triggered calendar work.pub mod calendar_outbox;+/// Access-token adapter for user-initiated calendar mutations.+pub mod calendar_tokens;pub mod config;pub mod convert;pub mod pubsub;diff --git a/services/email_service/src/main.rs b/services/email_service/src/main.rsindex 93cf3c2a19..8e90a69af7 100644--- a/services/email_service/src/main.rs+++ b/services/email_service/src/main.rs@@ -1,7 +1,10 @@#![recursion_limit = "256"]use crate::api::context::{ApiContext, AuthorizationService};use anyhow::Context;-use calendar_events::{domain::service::CalendarService, outbound::pg::PgCalendarRepository};+use calendar_events::{+ domain::{mutations::CalendarMutationServiceImpl, service::CalendarService},+ outbound::{google::GoogleCalendarClient, pg::PgCalendarRepository},+};use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,@@ -11,6 +14,8 @@ use email::{},outbound::{EmailPgRepo, GmailTokenProviderImpl},};+use email_service::calendar_tokens::CalendarTokenProviderAdapter;+use email_service::pubsub::calendar_backfill_adapters::RedisCalendarRequestGate;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -178,10 +183,21 @@ async fn main() -> anyhow::Result<()> {.context("failed to get multiplexed redis connection for gmail token provider")?;let redis_client = Arc::new(redis_client);let gmail_token_state = GmailTokenState::new(GmailTokenProviderImpl::new(- redis_conn,+ redis_conn.clone(),auth_service_client.clone(),));let calendar_service = Arc::new(CalendarService::new(PgCalendarRepository::new(db.clone())));+ let calendar_mutation_service = Arc::new(CalendarMutationServiceImpl::new(+ PgCalendarRepository::new(db.clone()),+ GoogleCalendarClient::with_gate(+ reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(30))+ .build()+ .context("failed to build the google calendar mutation http client")?,+ RedisCalendarRequestGate::new((*redis_client).clone()),+ ),+ CalendarTokenProviderAdapter::new(redis_conn.clone(), auth_service_client.clone()),+ ));let api_result = api::setup_and_serve(ApiContext {db,internal_api_key: config.internal_api_key.clone(),@@ -202,6 +218,7 @@ async fn main() -> anyhow::Result<()> {gmail_token_state,macro_event_broker: Arc::new(macro_event_broker),calendar_service,+ calendar_mutation_service,}).await;