Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add Zoom and Google Meet conferencing integrations (#3368)
Luke Vella50b6a7101e48
diff --git a/apps/docs/api-reference/errors.mdx b/apps/docs/api-reference/errors.mdxindex 3257a1780..94eff9372 100644--- a/apps/docs/api-reference/errors.mdx+++ b/apps/docs/api-reference/errors.mdx@@ -25,7 +25,9 @@ Every failure is `application/json` with the same shape:| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` || 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space || 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |-| 400 | `INAPPROPRIATE_CONTENT` | The title, description or location was flagged by content moderation |+| 400 | `CONFERENCING_UNAVAILABLE` | The requested video call provider is not offered on this instance |+| 400 | `CONFERENCING_NOT_CONNECTED` | The organizer has not connected an account for the requested video call provider |+| 400 | `INAPPROPRIATE_CONTENT` | The title, description, location or video call was flagged by content moderation || 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned || 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription || 404 | `NOT_FOUND` | No route matches the method and path |diff --git a/apps/docs/api-reference/openapi.json b/apps/docs/api-reference/openapi.jsonindex 5b8debf3a..2188bcaf6 100644--- a/apps/docs/api-reference/openapi.json+++ b/apps/docs/api-reference/openapi.json@@ -2,7 +2,7 @@"openapi": "3.1.0","info": {"title": "Rallly API",- "description": "## Versioning\n\n`v1` is stable. Additive changes (new endpoints, new optional fields) may land on this path at any time; breaking changes only arrive under a new version prefix.\n\n## Rate limits\n\nAll endpoints share two limits per space: **60 requests per minute** and **5000 requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.\n\nEvery response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.\n\nIf the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.\n\n## Dates and times\n\nEvery poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timeZone` (or the viewer's) for display. Timestamps such as `createdAt` and `updatedAt` are always ISO 8601 instants in UTC.\n\n## Request bodies\n\nRequest bodies are validated strictly: a field that is not part of the documented schema is rejected with `VALIDATION_ERROR` rather than ignored, so a misspelt setting never silently falls back to its default.\n\n## Enums\n\nVote types are an open set. The built-in values are `yes`, `ifNeedBe` and `no`; new types may be added without a version change, so clients must tolerate values they do not recognise. `status` and `kind` are closed sets.\n\n## Lists\n\nList endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter to fetch the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response.\n\n## Errors\n\nEvery failure is `application/json` with the shape `{ \"error\": { \"code\", \"message\" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.\n\n| Status | Code | When |\n| --- | --- | --- |\n| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, contained an unknown field, or the body was not valid JSON |\n| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |\n| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |\n| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |\n| 400 | `INAPPROPRIATE_CONTENT` | The title, description or location was flagged by content moderation |\n| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned |\n| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |\n| 404 | `NOT_FOUND` | No route matches the method and path |\n| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |\n| 404 | `PARTICIPANT_NOT_FOUND` | The participant does not exist or belongs to another poll |\n| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |\n| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |\n| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |",+ "description": "## Versioning\n\n`v1` is stable. Additive changes (new endpoints, new optional fields) may land on this path at any time; breaking changes only arrive under a new version prefix.\n\n## Rate limits\n\nAll endpoints share two limits per space: **60 requests per minute** and **5000 requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.\n\nEvery response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.\n\nIf the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.\n\n## Dates and times\n\nEvery poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timeZone` (or the viewer's) for display. Timestamps such as `createdAt` and `updatedAt` are always ISO 8601 instants in UTC.\n\n## Request bodies\n\nRequest bodies are validated strictly: a field that is not part of the documented schema is rejected with `VALIDATION_ERROR` rather than ignored, so a misspelt setting never silently falls back to its default.\n\n## Enums\n\nVote types are an open set. The built-in values are `yes`, `ifNeedBe` and `no`; new types may be added without a version change, so clients must tolerate values they do not recognise. `status` and `kind` are closed sets.\n\n## Lists\n\nList endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter to fetch the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response.\n\n## Errors\n\nEvery failure is `application/json` with the shape `{ \"error\": { \"code\", \"message\" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.\n\n| Status | Code | When |\n| --- | --- | --- |\n| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, contained an unknown field, or the body was not valid JSON |\n| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |\n| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |\n| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |\n| 400 | `CONFERENCING_UNAVAILABLE` | The requested video call provider is not offered on this instance |\n| 400 | `CONFERENCING_NOT_CONNECTED` | The organizer has not connected an account for the requested video call provider |\n| 400 | `INAPPROPRIATE_CONTENT` | The title, description, location or video call was flagged by content moderation |\n| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned |\n| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |\n| 404 | `NOT_FOUND` | No route matches the method and path |\n| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |\n| 404 | `PARTICIPANT_NOT_FOUND` | The participant does not exist or belongs to another poll |\n| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |\n| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |\n| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |","version": "1.0.0"},"servers": [@@ -49,7 +49,68 @@"type": "null"}],- "example": "Zoom"+ "example": "Conference Room A"+ },+ "conferencing": {+ "anyOf": [+ {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "zoom"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "meet"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "custom"+ },+ "label": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "uri": {+ "type": "string",+ "format": "uri"+ }+ },+ "required": [+ "provider",+ "label"+ ]+ }+ ]+ },+ {+ "type": "null"+ }+ ],+ "description": "The video call for the event, or `null`. A `zoom` or `meet` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",+ "example": {+ "provider": "zoom"+ }},"timeZone": {"anyOf": [@@ -142,6 +203,7 @@"title","description","location",+ "conferencing","timeZone","status","kind",@@ -329,10 +391,72 @@"maxLength": 1000},"location": {- "example": "Zoom",+ "description": "Where the event takes place, as free text.",+ "example": "Conference Room A","type": "string","maxLength": 255},+ "conferencing": {+ "description": "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",+ "examples": [+ {+ "provider": "zoom"+ },+ {+ "provider": "custom",+ "label": "Microsoft Teams",+ "uri": "https://teams.microsoft.com/l/meetup-join/abc"+ }+ ],+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "zoom"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "meet"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "custom"+ },+ "label": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "uri": {+ "type": "string",+ "format": "uri"+ }+ },+ "required": [+ "provider",+ "label"+ ]+ }+ ]+ },"requireEmail": {"description": "Require participants to provide their email address","example": true,@@ -428,10 +552,72 @@"maxLength": 1000},"location": {- "example": "Zoom",+ "description": "Where the event takes place, as free text.",+ "example": "Conference Room A","type": "string","maxLength": 255},+ "conferencing": {+ "description": "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",+ "examples": [+ {+ "provider": "zoom"+ },+ {+ "provider": "custom",+ "label": "Microsoft Teams",+ "uri": "https://teams.microsoft.com/l/meetup-join/abc"+ }+ ],+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "zoom"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "meet"+ }+ },+ "required": [+ "provider"+ ]+ },+ {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "const": "custom"+ },+ "label": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "uri": {+ "type": "string",+ "format": "uri"+ }+ },+ "required": [+ "provider",+ "label"+ ]+ }+ ]+ },"requireEmail": {"description": "Require participants to provide their email address","example": true,diff --git a/apps/web/.env.sample b/apps/web/.env.sampleindex 480902c0a..5aed7403c 100644--- a/apps/web/.env.sample+++ b/apps/web/.env.sample@@ -43,3 +43,10 @@ KV_REST_API_TOKEN=dev_fake_token_123456789abcdefghijklmnop# Toggle Self-Hosted mode# Enable to remove the pay-wall and subscription billing functionalityNEXT_PUBLIC_SELF_HOSTED=false++# Conferencing integrations (optional). Set CONFERENCING_ENABLED=true to let+# users connect Zoom and Google Meet and add meeting links to their events.+# Google Meet reuses GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET.+# CONFERENCING_ENABLED=false+# ZOOM_CLIENT_ID=+# ZOOM_CLIENT_SECRET=diff --git a/apps/web/.env.test b/apps/web/.env.testindex c1e7953e4..dedfd9cbb 100644--- a/apps/web/.env.test+++ b/apps/web/.env.test@@ -17,3 +17,9 @@ SMTP_PORT=1025SMTP_REJECT_UNAUTHORIZED=falseWEBHOOK_ALLOW_PRIVATE_URLS=true++# Conferencing integrations: the Zoom app is a stand-in so the provider is+# offered; the OAuth round trip itself is never driven in tests.+CONFERENCING_ENABLED=true+ZOOM_CLIENT_ID=test-zoom+ZOOM_CLIENT_SECRET=test-zoom-secretdiff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 2bb035b03..9e064165b 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -12,6 +12,8 @@"accountDeletionCancelled": "Your account is no longer scheduled for deletion","accountMenu": "Account menu","accountNotLinkedDescription": "A user with this email already exists. Please log in using the original method.",+ "actionErrorConferencingFailed": "We couldn't create the meeting link. Check your account in Conferencing settings and try again.",+ "actionErrorConferencingNotConnected": "Your video call account is not connected. Connect it in Conferencing settings and try again.","actionErrorForbidden": "You are not allowed to perform this action","actionErrorInternalServerError": "An internal server error occurred","actionErrorInvalidSession": "Your session is no longer valid",@@ -28,6 +30,7 @@"addComment": "Add comment","addDescription": "Add description","addLicenseKey": "Add license key",+ "addLocation": "Add location","addParticipant": "Add participant","address": "Address","addressPlaceholder": "123 Main Street",@@ -108,6 +111,8 @@"brandingSettingsDescription": "Customize your instance branding","brandingStorageNotConfigured": "Logo uploads require object storage, which has not been configured on this instance.","calendar": "Calendar",+ "calendarConnected": "Calendar connected",+ "calendarConnectFailed": "We couldn't connect that calendar. Please try again.","calendarDisconnectedError": "Failed to disconnect calendar","calendarDisconnectedSuccess": "Calendar disconnected successfully","calendarHelp": "You can't create a poll without any options. Add at least one option to continue.",@@ -165,9 +170,16 @@"commentsSheetEmptyDescription": "Be the first to share your thoughts on this poll.","commentsSheetSubmitted": "Your comment has been added","commentsTriggerLabel": "{count, plural, =0 {Comments} one {1 Comment} other {# Comments}}",+ "conferencing": "Conferencing",+ "conferencingConnected": "Account connected",+ "conferencingConnectFailed": "We couldn't connect that account. Please try again.",+ "conferencingDescription": "Connect the tools you use for video calls so we can add meeting links to your events.",+ "conferencingDisconnected": "Account disconnected",+ "conferencingNotConnected": "{provider} is not connected. Visit the <a>Conferencing settings</a> page to connect your account.","configuredByEnvironmentVariable": "This setting has been configured by environment variable.","confirm": "Confirm","confirmSpaceName": "Please type the space name to confirm:",+ "connectAccount": "Connect account","connectCalendar": "Connect calendar","connectGoogleCalendar": "Google Calendar","connectMicrosoftCalendar": "Microsoft Calendar",@@ -211,6 +223,11 @@"customBrandingManagedByInstance": "Branding is managed by your instance administrator.","customBrandingSettingLabel": "Show your logo and colors to participants.","customBrandingSettingTitle": "Custom branding",+ "customLinkInvalid": "That doesn't look like a link.",+ "customLinkOptional": "Link (optional)",+ "customVideoCall": "Custom",+ "customVideoCallNamePlaceholder": "Microsoft Teams",+ "customVideoCallNameRequired": "Name the call, like Microsoft Teams.","dangerZone": "Danger zone","dangerZoneAccountDeletion": "Delete your account and all data associated with it","dates": "Dates",@@ -266,6 +283,7 @@"details": "Details","developer": "Developer","disabled": "Disabled",+ "disconnect": "Disconnect","disconnectCalendar": "Disconnect calendar","disconnectingCalendar": "Disconnecting calendar...","dismissPasswordSetup": "Don't show again",@@ -410,6 +428,7 @@"industryReligiousOrganisation": "Religious organisation","industrySportsAndRecreation": "Sports and recreation","industryTechnology": "Technology",+ "inPerson": "In-person","instanceSettingsDescription": "Configure your instance settings","invalidEmailAddress": "Please enter a valid email address","invalidFileType": "Invalid file type",@@ -577,6 +596,8 @@"noCalendars": "No calendars found","noCalendarsDescription": "No calendars found","noChanges": "No changes",+ "noConferencingAccounts": "No accounts connected",+ "noConferencingAccountsDescription": "Connect an account and we'll add a meeting link to your events for you.","noDatesSelected": "No dates selected","noDatesSelectedDescription": "Click on a date to add a time slot","noDeliveriesYet": "No deliveries yet",@@ -611,6 +632,7 @@"noWebhooksDescription": "Add a webhook to receive events on your own server","oidcAutoSignInDescription": "You are being redirected to the login page...","openPollCount": "{count, plural, other {# open}}",+ "opensInNewTab": "(opens in new tab)","optional": "(optional)","optionalLabel": "(Optional)","optionCount": "{count, plural, one {# option} other {# options}}",@@ -965,6 +987,7 @@"verifyEmailDescription": "Enter the 6-digit code we sent to <b>{email}</b>","verifyEmailTitle": "Verify your email","versionTileNewMajorNotice": "v{major} is available. Read the migration guide.",+ "videoCall": "Video call","viewAdvisory": "{count, plural, one {View advisory} other {View advisories}}","viewClosedPolls": "View closed polls","viewInvites": "View invites",diff --git a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx b/apps/web/src/app/[locale]/(optional-space)/new/page.tsxindex 57863f7c6..35d5958c7 100644--- a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx+++ b/apps/web/src/app/[locale]/(optional-space)/new/page.tsx@@ -11,6 +11,7 @@ import type { Metadata } from "next";import { redirect } from "next/navigation";import { Link } from "@/components/link";import { BrandStyle } from "@/features/branding/components/brand-style";+import { loadConferencingOptions } from "@/features/conferencing/loaders";import { loadInstancePolicy } from "@/features/instance-policy/loaders";import { CreatePoll } from "@/features/poll/components/create-poll";import { getActiveSpaceForUser } from "@/features/space/data";@@ -30,6 +31,8 @@ export default async function Page() {redirect("/setup");}+ const conferencing = await loadConferencingOptions({ userId });+const primaryColor =space?.primaryColor &&isSpaceBrandingActive({@@ -43,6 +46,7 @@ export default async function Page() {<div className="page-bg-gray-100 absolute inset-0 h-dvh scroll-pt-16 overflow-auto dark:bg-gray-900">{primaryColor ? <BrandStyle primaryColor={primaryColor} /> : null}<CreatePoll+ conferencing={conferencing}nav={<Breadcrumb><BreadcrumbList>diff --git a/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx b/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsxnew file mode 100644index 000000000..05a8f8ea1--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx@@ -0,0 +1,32 @@+"use client";++import { toast } from "@rallly/ui/sonner";+import React from "react";+import { useTranslation } from "@/i18n/client";+import { useFlash } from "@/lib/flash/client";+import { OAUTH_FLASH_KEY } from "@/lib/oauth/constants";++// Surfaces the outcome of the OAuth round trip once the user lands back here.+// Consuming the flash here also keeps a calendar outcome from lingering until+// another page that reads the same key picks it up.+export function CalendarConnectionFlash() {+ const { t } = useTranslation();+ const flash = useFlash(OAUTH_FLASH_KEY);++ React.useEffect(() => {+ if (!flash) return;+ if (flash.startsWith("connected:")) {+ toast.success(+ t("calendarConnected", { defaultValue: "Calendar connected" }),+ );+ } else {+ toast.error(+ t("calendarConnectFailed", {+ defaultValue: "We couldn't connect that calendar. Please try again.",+ }),+ );+ }+ }, [flash, t]);++ return null;+}diff --git a/apps/web/src/app/[locale]/(space)/settings/calendars/page.tsx b/apps/web/src/app/[locale]/(space)/settings/calendars/page.tsxindex f5621af63..cc29b4f54 100644--- a/apps/web/src/app/[locale]/(space)/settings/calendars/page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/calendars/page.tsx@@ -21,6 +21,7 @@ import { Trans } from "@/i18n/client";import { getTranslation } from "@/i18n/server";import { isFeatureEnabled } from "@/lib/feature-flags/server";import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";+import { CalendarConnectionFlash } from "./components/calendar-connection-flash";import { CalendarConnectionList } from "./components/calendar-connection-list";import { ConnectCalendarDropdown } from "./components/connect-calendar-dropdown";import { DefaultCalendarSelect } from "./components/default-calendar-select";@@ -42,6 +43,7 @@ export default async function CalendarsPage() {return (<HydrationBoundary state={dehydrate(trpc.queryClient)}><SettingsPage>+ <CalendarConnectionFlash /><SettingsPageHeader><SettingsPageTitle><Trans i18nKey="calendars" defaults="Calendars" />diff --git a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsxindex 6d7db25ba..094347e50 100644--- a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx@@ -22,6 +22,7 @@ import {ShapesIcon,UserIcon,UsersIcon,+ VideoIcon,WebhookIcon,} from "lucide-react";import { usePathname } from "next/navigation";@@ -69,6 +70,7 @@ export function AccountSidebarMenu() {];const isCalendarsEnabled = useFeatureFlag("calendars");+ const isConferencingEnabled = useFeatureFlag("conferencing");if (isCalendarsEnabled) {menuItems.push({@@ -79,6 +81,15 @@ export function AccountSidebarMenu() {});}+ if (isConferencingEnabled) {+ menuItems.push({+ id: "conferencing",+ label: t("conferencing", { defaultValue: "Conferencing" }),+ icon: <VideoIcon />,+ href: "/settings/conferencing",+ });+ }+return (<SidebarMenu>{menuItems.map((item) => (diff --git a/apps/web/src/app/[locale]/(space)/settings/conferencing/page.tsx b/apps/web/src/app/[locale]/(space)/settings/conferencing/page.tsxnew file mode 100644index 000000000..4aabaf13a--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/conferencing/page.tsx@@ -0,0 +1,83 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { Suspense } from "react";+import { PageSection, PageSectionContent } from "@/components/page-layout";+import {+ SettingsPage,+ SettingsPageAction,+ SettingsPageContent,+ SettingsPageDescription,+ SettingsPageHeader,+ SettingsPageTitle,+} from "@/components/settings-layout";+import { Spinner } from "@/components/spinner";+import { ConferencingConnectionFlash } from "@/features/conferencing/components/conferencing-connection-flash";+import { ConferencingConnectionList } from "@/features/conferencing/components/conferencing-connection-list";+import { ConnectConferencingDropdown } from "@/features/conferencing/components/connect-conferencing-dropdown";+import { getAvailableConferencingProviders } from "@/features/conferencing/constants";+import { loadConferencingConnections } from "@/features/conferencing/loaders";+import { integrationIdToConferencingProvider } from "@/features/conferencing/utils";+import { Trans } from "@/i18n/client";+import { getTranslation } from "@/i18n/server";+import { isFeatureEnabled } from "@/lib/feature-flags/server";++export default function ConferencingPage() {+ if (!isFeatureEnabled("conferencing")) {+ notFound();+ }++ return (+ <SettingsPage>+ <ConferencingConnectionFlash />+ <SettingsPageHeader>+ <SettingsPageTitle>+ <Trans i18nKey="conferencing" defaults="Conferencing" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="conferencingDescription"+ defaults="Connect the tools you use for video calls so we can add meeting links to your events."+ />+ </SettingsPageDescription>+ <SettingsPageAction>+ <ConnectConferencingDropdown+ providers={getAvailableConferencingProviders()}+ />+ </SettingsPageAction>+ </SettingsPageHeader>+ <SettingsPageContent>+ <PageSection>+ <PageSectionContent>+ <Suspense fallback={<Spinner />}>+ <ConnectionList />+ </Suspense>+ </PageSectionContent>+ </PageSection>+ </SettingsPageContent>+ </SettingsPage>+ );+}++async function ConnectionList() {+ const connections = await loadConferencingConnections();+ // The stored provider is the OAuth provider ("google"); the form and icons+ // speak in conferencing providers, which the integration id identifies.+ const items = connections.flatMap((connection) => {+ const provider = integrationIdToConferencingProvider(+ connection.integrationId,+ );+ return provider ? [{ ...connection, provider }] : [];+ });+ return <ConferencingConnectionList connections={items} />;+}++export async function generateMetadata(): Promise<Metadata> {+ const { t } = await getTranslation();+ return {+ title: t("conferencing", { defaultValue: "Conferencing" }),+ description: t("conferencingDescription", {+ defaultValue:+ "Connect the tools you use for video calls so we can add meeting links to your events.",+ }),+ };+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsxindex f37765b8d..17cd2c83d 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx@@ -1,6 +1,7 @@import { Alert, AlertDescription } from "@rallly/ui/alert";import { Skeleton } from "@rallly/ui/skeleton";import { BarChart2Icon, CalendarIcon, InfoIcon } from "lucide-react";+import { getUserUpcomingEventCount } from "@/features/scheduled-event/data";import { getAccountDeletionSummary } from "@/features/user/account-deletion/data";import { loadUser } from "@/features/user/loaders";import { Trans } from "@/i18n/client";@@ -9,11 +10,17 @@ import { Trans } from "@/i18n/client";// settings page never waits on the counts.export async function AccountDeletionSummary() {const user = await loadUser();- const { activePollCount, upcomingEventCount, hasActiveSubscription } =- await getAccountDeletionSummary({- userId: user.id,- timeZone: user.timeZone ?? "UTC",- });+ // Composed here rather than inside the user feature so user does not+ // depend on scheduled-event (which depends on conferencing, which gates+ // its loaders on user).+ const [{ activePollCount, hasActiveSubscription }, upcomingEventCount] =+ await Promise.all([+ getAccountDeletionSummary({ userId: user.id }),+ getUserUpcomingEventCount({+ userId: user.id,+ timeZone: user.timeZone ?? "UTC",+ }),+ ]);const hasResources = activePollCount > 0 || upcomingEventCount > 0;diff --git a/apps/web/src/app/api/integrations/[...connection]/route.ts b/apps/web/src/app/api/integrations/[...connection]/route.tsindex 29cf364d7..a0ea486d6 100644--- a/apps/web/src/app/api/integrations/[...connection]/route.ts+++ b/apps/web/src/app/api/integrations/[...connection]/route.ts@@ -3,12 +3,57 @@ import {createCalendarConnection,syncCalendars,} from "@/features/calendars/mutations";+import { isConferencingEnabled } from "@/features/conferencing/constants";+import { createConferencingConnection } from "@/features/conferencing/mutations";import { saveOAuthCredentials } from "@/features/credentials/mutations";import { getSession } from "@/lib/auth";import { GoogleOAuthClient } from "@/lib/oauth/providers/google";+import { ZoomOAuthClient } from "@/lib/oauth/providers/zoom";import { OAuthIntegration } from "@/lib/oauth/server";+import type { OAuthClient } from "@/lib/oauth/types";-type Integration = "google-calendar" | "outlook-calendar";+type Integration =+ | "google-calendar"+ | "outlook-calendar"+ | "google-meet"+ | "zoom";++async function requireSessionUserId() {+ const session = await getSession();+ if (!session?.user) {+ throw new Error("User not found");+ }+ return session.user.id;+}++function conferencingOnConnect({+ integrationId,+ displayName,+}: {+ integrationId: Integration;+ displayName: string;+}): NonNullable<OAuthClient["onConnect"]> {+ return async ({ provider, tokens, providerAccountId, userInfo }) => {+ const userId = await requireSessionUserId();++ const credential = await saveOAuthCredentials({+ userId,+ provider,+ providerAccountId,+ tokens,+ });++ await createConferencingConnection({+ userId,+ provider,+ integrationId,+ credentialId: credential.id,+ providerAccountId,+ userInfo,+ displayName,+ });+ };+}const { handler } = OAuthIntegration<Integration>({basePath: "/api/integrations",@@ -34,12 +79,7 @@ const { handler } = OAuthIntegration<Integration>({providerAccountId,userInfo,}) => {- const session = await getSession();- if (!session?.user) {- throw new Error("User not found");- }-- const userId = session.user.id;+ const userId = await requireSessionUserId();// save credentials to databaseconst credential = await saveOAuthCredentials({@@ -64,6 +104,48 @@ const { handler } = OAuthIntegration<Integration>({},});}+ case "google-meet": {+ if (+ !isConferencingEnabled ||+ !env.GOOGLE_CLIENT_ID ||+ !env.GOOGLE_CLIENT_SECRET+ ) {+ return null;+ }+ return new GoogleOAuthClient({+ clientId: env.GOOGLE_CLIENT_ID,+ clientSecret: env.GOOGLE_CLIENT_SECRET,+ callbackUrl,+ scopes: [+ "https://www.googleapis.com/auth/meetings.space.created",+ "https://www.googleapis.com/auth/userinfo.email",+ "https://www.googleapis.com/auth/userinfo.profile",+ ],+ onConnect: conferencingOnConnect({+ integrationId,+ displayName: "Google Meet",+ }),+ });+ }+ case "zoom": {+ if (+ !isConferencingEnabled ||+ !env.ZOOM_CLIENT_ID ||+ !env.ZOOM_CLIENT_SECRET+ ) {+ return null;+ }+ return new ZoomOAuthClient({+ clientId: env.ZOOM_CLIENT_ID,+ clientSecret: env.ZOOM_CLIENT_SECRET,+ callbackUrl,+ scopes: ["meeting:write:meeting", "user:read:user"],+ onConnect: conferencingOnConnect({+ integrationId,+ displayName: "Zoom",+ }),+ });+ }default:return null;}diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.tsindex 0b0bb1ee1..85612b2f5 100644--- a/apps/web/src/app/api/v1/[...route]/route.test.ts+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts@@ -14,6 +14,23 @@ const mockGetSpaceMemberByEmail = vi.fn();const mockTrack = vi.fn();const mockIdentifyGroup = vi.fn();+const mockGetAvailableConferencingProviders = vi.fn(() => [] as string[]);+const mockGetConnectedConferencingProviders = vi.fn(+ async (_userId: string) => [] as string[],+);++vi.mock("@/features/conferencing/constants", () => ({+ isConferencingEnabled: false,+ getAvailableConferencingProviders: () =>+ mockGetAvailableConferencingProviders(),+}));++vi.mock("@/features/conferencing/data", () => ({+ getConnectedConferencingProviders: (userId: string) =>+ mockGetConnectedConferencingProviders(userId),+ parsePollConferencing: (value: unknown) => value,+}));+vi.mock("@/features/moderation/mutations", () => ({moderateContent: vi.fn().mockResolvedValue({ verdict: "safe", reason: "" }),}));@@ -170,6 +187,7 @@ describe("API v1 - /polls", () => {title: "Test Poll",description: null,location: null,+ conferencing: null,timeZone: null,status: "open",kind: "date",@@ -771,6 +789,152 @@ describe("API v1 - /polls", () => {);});+ it("stores a custom video call and echoes it back", async () => {+ mockCreatePoll.mockImplementationOnce(async (input) => ({+ id: "test-poll-id",+ title: input.title,+ description: null,+ location: null,+ conferencing: input.conferencing,+ timeZone: null,+ status: "open",+ kind: "date",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: false,+ hideParticipants: false,+ hideScores: false,+ disableComments: true,+ allowTentativeVotes: true,+ participantCount: 0,+ user: null,+ options: [],+ }));+ const res = await app.request("/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ conferencing: {+ provider: "custom",+ label: "Microsoft Teams",+ uri: "https://teams.microsoft.com/l/meetup-join/abc",+ },+ kind: "date",+ options: [{ date: "2025-01-15" }],+ }),+ });++ expect(res.status).toBe(201);+ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ conferencing: {+ provider: "custom",+ label: "Microsoft Teams",+ uri: "https://teams.microsoft.com/l/meetup-join/abc",+ },+ }),+ );+ const body = await res.json();+ expect(body.data.conferencing).toEqual({+ provider: "custom",+ label: "Microsoft Teams",+ uri: "https://teams.microsoft.com/l/meetup-join/abc",+ });+ });++ it("rejects a non-http custom link", async () => {+ const res = await app.request("/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ conferencing: {+ provider: "custom",+ label: "Call",+ uri: "javascript:alert(1)",+ },+ kind: "date",+ options: [{ date: "2025-01-15" }],+ }),+ });++ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it("rejects a provider the instance does not offer", async () => {+ mockGetAvailableConferencingProviders.mockReturnValueOnce([]);+ const res = await app.request("/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ conferencing: { provider: "zoom" },+ kind: "date",+ options: [{ date: "2025-01-15" }],+ }),+ });++ expect(res.status).toBe(400);+ expect((await res.json()).error.code).toBe("CONFERENCING_UNAVAILABLE");+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it("rejects a provider the organizer has not connected", async () => {+ mockGetAvailableConferencingProviders.mockReturnValueOnce(["zoom"]);+ mockGetConnectedConferencingProviders.mockResolvedValueOnce([]);+ const res = await app.request("/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ conferencing: { provider: "zoom" },+ kind: "date",+ options: [{ date: "2025-01-15" }],+ }),+ });++ expect(res.status).toBe(400);+ expect((await res.json()).error.code).toBe("CONFERENCING_NOT_CONNECTED");+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it("stores a connected provider", async () => {+ mockGetAvailableConferencingProviders.mockReturnValueOnce(["zoom"]);+ mockGetConnectedConferencingProviders.mockResolvedValueOnce(["zoom"]);+ const res = await app.request("/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ conferencing: { provider: "zoom" },+ kind: "date",+ options: [{ date: "2025-01-15" }],+ }),+ });++ expect(res.status).toBe(201);+ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({ conferencing: { provider: "zoom" } }),+ );+ });+it("should return error when too many date options", async () => {const dates = Array.from({ length: 101 }, (_, i) => {const date = new Date(2025, 0, 1 + i);diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.tsindex 28931e9c4..46928ae0f 100644--- a/apps/web/src/app/api/v1/[...route]/route.ts+++ b/apps/web/src/app/api/v1/[...route]/route.ts@@ -9,6 +9,10 @@ import {validator,} from "hono-openapi";import { after } from "next/server";+import { getAvailableConferencingProviders } from "@/features/conferencing/constants";+import { getConnectedConferencingProviders } from "@/features/conferencing/data";+import type { PollConferencing } from "@/features/conferencing/schema";+import { moderatedLinkText } from "@/features/conferencing/utils";import { moderateContent } from "@/features/moderation/mutations";import { MAX_POLL_OPTIONS } from "@/features/poll/constants";import {@@ -100,6 +104,7 @@ function toPollResponseBody(poll: {title: string;description: string | null;location: string | null;+ conferencing: PollConferencing | null;timeZone: string | null;status: string;kind: PollKind;@@ -125,6 +130,7 @@ function toPollResponseBody(poll: {title: poll.title,description: poll.description,location: poll.location,+ conferencing: poll.conferencing ?? null,timeZone: poll.timeZone,status: poll.status,kind: poll.kind,@@ -304,7 +310,7 @@ async function buildOpenApiSpec() {"| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |","| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |","| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |",- "| 400 | `INAPPROPRIATE_CONTENT` | The title, description or location was flagged by content moderation |",+ "| 400 | `CONFERENCING_UNAVAILABLE` | The requested video call provider is not offered on this instance |\n| 400 | `CONFERENCING_NOT_CONNECTED` | The organizer has not connected an account for the requested video call provider |\n| 400 | `INAPPROPRIATE_CONTENT` | The title, description, location or video call was flagged by content moderation |","| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned |","| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |","| 404 | `NOT_FOUND` | No route matches the method and path |",@@ -480,6 +486,35 @@ app.post(organizerUserId = spaceMember.userId;}+ // Same gates as the app: the instance must offer the provider and the+ // organizer must have linked an account, since their account hosts the+ // meeting at finalize. A custom call needs neither.+ const conferencing = input.conferencing;+ if (conferencing && conferencing.provider !== "custom") {+ if (+ !getAvailableConferencingProviders().includes(conferencing.provider)+ ) {+ return c.json(+ apiError(+ "CONFERENCING_UNAVAILABLE",+ `${conferencing.provider} is not available on this instance.`,+ ),+ 400,+ );+ }+ const connected =+ await getConnectedConferencingProviders(organizerUserId);+ if (!connected.includes(conferencing.provider)) {+ return c.json(+ apiError(+ "CONFERENCING_NOT_CONNECTED",+ `The organizer has not connected a ${conferencing.provider} account.`,+ ),+ 400,+ );+ }+ }+// Same gate as the app. The strike goes to the key holder, who is the// paying account, whichever member the poll is organized by.const moderation = await moderateContent({@@ -488,6 +523,10 @@ app.post(Title: input.title,Description: input.description ?? "",Location: input.location ?? "",+ Conferencing:+ conferencing?.provider === "custom"+ ? `${conferencing.label} ${moderatedLinkText(conferencing.uri)}`+ : "",},});@@ -573,6 +612,7 @@ app.post(title: input.title,description: input.description,location: input.location,+ conferencing,requireParticipantEmail: input.requireEmail,hideParticipants: input.hideParticipants,hideScores: input.hideScores,@@ -643,6 +683,7 @@ app.post(title: input.title,description: input.description,location: input.location,+ conferencing,timeZone,requireParticipantEmail: input.requireEmail,hideParticipants: input.hideParticipants,diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.tsindex ddceb1d94..dd45c850d 100644--- a/apps/web/src/app/api/v1/schemas.ts+++ b/apps/web/src/app/api/v1/schemas.ts@@ -1,4 +1,5 @@import * as z from "zod";+import { pollConferencingSchema } from "@/features/conferencing/schema";import { MAX_POLL_TITLE_LENGTH } from "@/features/poll/schema";import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import { timezoneSchema } from "@/lib/utils/timezone-schema";@@ -174,7 +175,22 @@ const pollSettingsFields = {.max(1000).optional().meta({ example: "Pick a time that works for everyone" }),- location: z.string().trim().max(255).optional().meta({ example: "Zoom" }),+ location: z.string().trim().max(255).optional().meta({+ description: "Where the event takes place, as free text.",+ example: "Conference Room A",+ }),+ conferencing: pollConferencingSchema.optional().meta({+ description:+ "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",+ examples: [+ { provider: "zoom" },+ {+ provider: "custom",+ label: "Microsoft Teams",+ uri: "https://teams.microsoft.com/l/meetup-join/abc",+ },+ ],+ }),requireEmail: z.boolean().optional().meta({description: "Require participants to provide their email address",example: true,@@ -221,6 +237,7 @@ const createDatePollInputSchema = z}),description: pollSettingsFields.description,location: pollSettingsFields.location,+ conferencing: pollSettingsFields.conferencing,requireEmail: pollSettingsFields.requireEmail,hideParticipants: pollSettingsFields.hideParticipants,hideScores: pollSettingsFields.hideScores,@@ -242,6 +259,7 @@ const createTimePollInputSchema = z}),description: pollSettingsFields.description,location: pollSettingsFields.location,+ conferencing: pollSettingsFields.conferencing,requireEmail: pollSettingsFields.requireEmail,hideParticipants: pollSettingsFields.hideParticipants,hideScores: pollSettingsFields.hideScores,@@ -425,7 +443,12 @@ const pollSchema = zdescription: z.string().nullable().meta({example: "Pick a time that works for everyone",}),- location: z.string().nullable().meta({ example: "Zoom" }),+ location: z.string().nullable().meta({ example: "Conference Room A" }),+ conferencing: pollConferencingSchema.nullable().meta({+ description:+ "The video call for the event, or `null`. A `zoom` or `meet` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",+ example: { provider: "zoom" },+ }),timeZone: z.string().nullable().meta({ example: "Europe/London" }),status: pollStatusSchema,kind: pollKindSchema,diff --git a/apps/web/src/env.ts b/apps/web/src/env.tsindex d50516c58..228382cfa 100644--- a/apps/web/src/env.ts+++ b/apps/web/src/env.ts@@ -109,6 +109,14 @@ export const env = createEnv({GOOGLE_CLIENT_ID: z.string().optional(),GOOGLE_CLIENT_SECRET: z.string().optional(),+ /**+ * Conferencing integrations (Zoom, Google Meet). The flag needs at least+ * one provider's OAuth app configured; see createFinalSchema below.+ */+ CONFERENCING_ENABLED: z.enum(["true", "false"]).default("false"),+ ZOOM_CLIENT_ID: z.string().optional(),+ ZOOM_CLIENT_SECRET: z.string().optional(),+/*** Microsoft Integration*/@@ -280,6 +288,9 @@ export const env = createEnv({LICENSE_API_AUTH_TOKEN: process.env.LICENSE_API_AUTH_TOKEN,GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,+ CONFERENCING_ENABLED: process.env.CONFERENCING_ENABLED,+ ZOOM_CLIENT_ID: process.env.ZOOM_CLIENT_ID,+ ZOOM_CLIENT_SECRET: process.env.ZOOM_CLIENT_SECRET,MICROSOFT_TENANT_ID: process.env.MICROSOFT_TENANT_ID,MICROSOFT_CLIENT_ID: process.env.MICROSOFT_CLIENT_ID,MICROSOFT_CLIENT_SECRET: process.env.MICROSOFT_CLIENT_SECRET,@@ -317,5 +328,29 @@ export const env = createEnv({"SMTP_USER and SMTP_PWD must be set together. Set both to use authenticated SMTP, or neither to connect without authentication.",});}++ if (Boolean(env.ZOOM_CLIENT_ID) !== Boolean(env.ZOOM_CLIENT_SECRET)) {+ ctx.addIssue({+ code: "custom",+ path: [env.ZOOM_CLIENT_ID ? "ZOOM_CLIENT_SECRET" : "ZOOM_CLIENT_ID"],+ message:+ "ZOOM_CLIENT_ID and ZOOM_CLIENT_SECRET must be set together.",+ });+ }++ // A flag that is on with nothing behind it would render an empty+ // settings page; fail loudly at boot instead of hiding the feature.+ const hasZoom = Boolean(env.ZOOM_CLIENT_ID && env.ZOOM_CLIENT_SECRET);+ const hasGoogle = Boolean(+ env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET,+ );+ if (env.CONFERENCING_ENABLED === "true" && !hasZoom && !hasGoogle) {+ ctx.addIssue({+ code: "custom",+ path: ["CONFERENCING_ENABLED"],+ message:+ "CONFERENCING_ENABLED is set but no conferencing provider is configured. Set ZOOM_CLIENT_ID and ZOOM_CLIENT_SECRET for Zoom, or GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET for Google Meet, or turn the flag off.",+ });+ }}),});diff --git a/apps/web/src/features/conferencing/actions.ts b/apps/web/src/features/conferencing/actions.tsnew file mode 100644index 000000000..6f9ecb6aa--- /dev/null+++ b/apps/web/src/features/conferencing/actions.ts@@ -0,0 +1,19 @@+"use server";++import { refresh } from "next/cache";++import { authActionClient } from "@/lib/safe-action/server";+import { disconnectConferencingConnection } from "./mutations";+import { disconnectConferencingConnectionSchema } from "./schema";++export const disconnectConferencingConnectionAction = authActionClient+ .metadata({ actionName: "disconnect_conferencing_connection" })+ .inputSchema(disconnectConferencingConnectionSchema)+ .action(async ({ ctx, parsedInput }) => {+ await disconnectConferencingConnection({+ userId: ctx.user.id,+ id: parsedInput.id,+ });++ refresh();+ });diff --git a/apps/web/src/features/conferencing/assets/google-meet.svg b/apps/web/src/features/conferencing/assets/google-meet.svgnew file mode 100644index 000000000..400cc5862--- /dev/null+++ b/apps/web/src/features/conferencing/assets/google-meet.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 87.5 72">+ <path fill="#00832d" d="M49.5 36l8.53 9.75 11.47 7.33 2-17.02-2-16.64-11.69 6.44z"/>+ <path fill="#0066da" d="M0 51.5V66c0 3.315 2.685 6 6 6h14.5l3-10.96-3-9.54-9.95-3z"/>+ <path fill="#e94235" d="M20.5 0L0 20.5l10.55 3 9.95-3 2.95-9.41z"/>+ <path fill="#2684fc" d="M20.5 20.5H0v31h20.5z"/>+ <path fill="#00ac47" d="M82.6 8.68L69.5 19.42v33.66l13.16 10.79c1.97 1.54 4.85.135 4.85-2.37V11c0-2.535-2.945-3.925-4.91-2.32zM49.5 36v15.5h-29V72h43c3.315 0 6-2.685 6-6V53.08z"/>+ <path fill="#ffba00" d="M63.5 0h-43v20.5h29V36l20-16.57V6c0-3.315-2.685-6-6-6z"/>+</svg>diff --git a/apps/web/src/features/conferencing/assets/zoom.svg b/apps/web/src/features/conferencing/assets/zoom.svgnew file mode 100644index 000000000..4fd669bc8--- /dev/null+++ b/apps/web/src/features/conferencing/assets/zoom.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">+ <rect width="64" height="64" rx="14" fill="#0B5CFF"/>+ <path fill="#fff" d="M14 22.5A4.5 4.5 0 0 1 18.5 18h16a6.5 6.5 0 0 1 6.5 6.5v17a4.5 4.5 0 0 1-4.5 4.5h-16A6.5 6.5 0 0 1 14 39.5v-17Zm30 6.2 7.6-5.3a1.5 1.5 0 0 1 2.4 1.2v14.8a1.5 1.5 0 0 1-2.4 1.2L44 35.3v-6.6Z"/>+</svg>diff --git a/apps/web/src/features/conferencing/client.tsx b/apps/web/src/features/conferencing/client.tsxnew file mode 100644index 000000000..cd78b0d79--- /dev/null+++ b/apps/web/src/features/conferencing/client.tsx@@ -0,0 +1,16 @@+"use client";++// Starts the OAuth flow for a conferencing integration; the callback lands+// the user back on the page they left with `connected` or `error` set.+export const connectToConferencing = (+ integrationId: string,+ options: { redirectTo?: string } = {},+) => {+ const redirectTo = options.redirectTo || window.location.pathname;+ const url = new URL(+ `/api/integrations/auth/${integrationId}`,+ window.location.origin,+ );+ url.searchParams.set("redirect", redirectTo);+ window.location.href = url.toString();+};diff --git a/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsxnew file mode 100644index 000000000..147d6705a--- /dev/null+++ b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx@@ -0,0 +1,30 @@+"use client";++import { toast } from "@rallly/ui/sonner";+import React from "react";+import { useTranslation } from "@/i18n/client";+import { useFlash } from "@/lib/flash/client";+import { OAUTH_FLASH_KEY } from "@/lib/oauth/constants";++// Surfaces the outcome of the OAuth round trip once the user lands back here.+export function ConferencingConnectionFlash() {+ const { t } = useTranslation();+ const flash = useFlash(OAUTH_FLASH_KEY);++ React.useEffect(() => {+ if (!flash) return;+ if (flash.startsWith("connected:")) {+ toast.success(+ t("conferencingConnected", { defaultValue: "Account connected" }),+ );+ } else {+ toast.error(+ t("conferencingConnectFailed", {+ defaultValue: "We couldn't connect that account. Please try again.",+ }),+ );+ }+ }, [flash, t]);++ return null;+}diff --git a/apps/web/src/features/conferencing/components/conferencing-connection-list.tsx b/apps/web/src/features/conferencing/components/conferencing-connection-list.tsxnew file mode 100644index 000000000..0ab5b89a7--- /dev/null+++ b/apps/web/src/features/conferencing/components/conferencing-connection-list.tsx@@ -0,0 +1,118 @@+"use client";++import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";+import { Button } from "@rallly/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import { toast } from "@rallly/ui/sonner";+import { useMutation } from "@tanstack/react-query";+import { MoreVerticalIcon, UnplugIcon, VideoIcon } from "lucide-react";+import {+ EmptyState,+ EmptyStateDescription,+ EmptyStateIcon,+ EmptyStateTitle,+} from "@/components/empty-state";+import { disconnectConferencingConnectionAction } from "@/features/conferencing/actions";+import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";+import type { ConferencingProvider } from "@/features/conferencing/schema";+import { conferencingProviderLabels } from "@/features/conferencing/utils";+import { Trans, useTranslation } from "@/i18n/client";++export function ConferencingConnectionList({+ connections,+}: {+ connections: {+ id: string;+ provider: ConferencingProvider;+ email: string;+ displayName: string | null;+ }[];+}) {+ const { t } = useTranslation();+ const disconnect = useMutation(+ mutationOptions(disconnectConferencingConnectionAction, {+ onSuccess: () => {+ toast.success(+ t("conferencingDisconnected", {+ defaultValue: "Account disconnected",+ }),+ );+ },+ }),+ );++ if (connections.length === 0) {+ return (+ <EmptyState>+ <EmptyStateIcon>+ <VideoIcon />+ </EmptyStateIcon>+ <EmptyStateTitle>+ <Trans+ i18nKey="noConferencingAccounts"+ defaults="No accounts connected"+ />+ </EmptyStateTitle>+ <EmptyStateDescription>+ <Trans+ i18nKey="noConferencingAccountsDescription"+ defaults="Connect an account and we'll add a meeting link to your events for you."+ />+ </EmptyStateDescription>+ </EmptyState>+ );+ }++ return (+ <ul className="space-y-4">+ {connections.map((connection) => (+ <li+ key={connection.id}+ className="flex items-center gap-x-4 rounded-xl border p-4"+ >+ <ConferencingProviderIcon provider={connection.provider} size={32} />+ <div className="min-w-0 flex-1">+ <p className="font-semibold text-sm">+ {connection.displayName ??+ conferencingProviderLabels[connection.provider]}+ </p>+ <p className="truncate text-muted-foreground text-sm">+ {connection.email}+ </p>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ aria-label={t("moreOptions", {+ defaultValue: "More options",+ })}+ variant="ghost"+ size="icon"+ />+ }+ >+ <MoreVerticalIcon className="text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ variant="destructive"+ onClick={() => {+ disconnect.mutate({ id: connection.id });+ }}+ >+ <UnplugIcon />+ <Trans i18nKey="disconnect" defaults="Disconnect" />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ ))}+ </ul>+ );+}diff --git a/apps/web/src/features/conferencing/components/conferencing-field.tsx b/apps/web/src/features/conferencing/components/conferencing-field.tsxnew file mode 100644index 000000000..0a58a4b21--- /dev/null+++ b/apps/web/src/features/conferencing/components/conferencing-field.tsx@@ -0,0 +1,268 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+} from "@rallly/ui/dropdown-menu";+import { FormItem, FormLabel } from "@rallly/ui/form";+import { Input } from "@rallly/ui/input";+import { VideoIcon } from "lucide-react";+import React from "react";+import { Controller, useFormContext } from "react-hook-form";+import { Link } from "@/components/link";+import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";+import type { ConferencingProvider } from "@/features/conferencing/schema";+import { conferencingProviderLabels } from "@/features/conferencing/utils";+import { Trans, useTranslation } from "@/i18n/client";++export type ConferencingOptions = {+ // Providers this instance offers, in menu order. A pasted link is always+ // offered and needs no provider.+ available: ConferencingProvider[];+ // Providers the organizer has linked an account for.+ connected: ConferencingProvider[];+};++type ConferencingFormValues = {+ conferencingProvider?: ConferencingProvider | "custom" | "";+ conferencingUrl?: string;+ conferencingLabel?: string;+};++// Menu entries for the shared "Add location" menu. Renders nothing once a+// choice is made: an event carries one meeting link.+export function ConferencingProviderMenuItems({+ available,+}: Pick<ConferencingOptions, "available">) {+ const form = useFormContext<ConferencingFormValues>();+ const value = form.watch("conferencingProvider");++ if (value) {+ return null;+ }++ return (+ <DropdownMenuGroup>+ <DropdownMenuLabel>+ <Trans i18nKey="videoCall" defaults="Video call" />+ </DropdownMenuLabel>+ {available.map((provider) => (+ <DropdownMenuItem+ key={provider}+ onClick={() => {+ form.setValue("conferencingProvider", provider, {+ shouldDirty: true,+ });+ }}+ >+ <ConferencingProviderIcon provider={provider} size={16} />+ {conferencingProviderLabels[provider]}+ </DropdownMenuItem>+ ))}+ <DropdownMenuItem+ onClick={() => {+ form.setValue("conferencingProvider", "custom", {+ shouldDirty: true,+ });+ }}+ >+ <VideoIcon />+ <Trans i18nKey="customVideoCall" defaults="Custom" />+ </DropdownMenuItem>+ </DropdownMenuGroup>+ );+}++// Shows the chosen provider, or the inputs for a pasted link. A provider+// link is created when the organizer finalizes the poll, so an unlinked+// account is caught here rather than at that later step.+export function ConferencingField({+ connected,+}: Pick<ConferencingOptions, "connected">) {+ const { t } = useTranslation();+ const form = useFormContext<ConferencingFormValues>();+ // `trigger` is stable; the context object itself is not (FormProvider+ // rebuilds it every render), so depending on `form` here would loop.+ const { trigger } = form;+ const value = form.watch("conferencingProvider");++ // Validate as soon as a provider is set — by the menu or by a draft+ // restored from storage — instead of waiting for the submit attempt. Runs+ // after mount so the Controller's rule is registered.+ React.useEffect(() => {+ if (value && value !== "custom") {+ void trigger("conferencingProvider");+ }+ }, [value, trigger]);++ if (!value) {+ return null;+ }++ const remove = () => {+ form.setValue("conferencingProvider", "");+ form.setValue("conferencingUrl", "");+ form.setValue("conferencingLabel", "");+ form.clearErrors([+ "conferencingProvider",+ "conferencingLabel",+ "conferencingUrl",+ ]);+ };++ const header = (+ <div className="flex items-center justify-between">+ <FormLabel+ htmlFor={value === "custom" ? "conferencing-label" : undefined}+ >+ <Trans i18nKey="videoCall" defaults="Video call" />+ </FormLabel>+ <Button+ type="button"+ variant="link"+ size="sm"+ className="h-auto p-0 text-muted-foreground hover:text-foreground"+ onClick={remove}+ >+ <Trans i18nKey="remove" defaults="Remove" />+ </Button>+ </div>+ );++ if (value === "custom") {+ return (+ <FormItem>+ {header}+ <div className="grid gap-2 sm:grid-cols-[12rem_1fr]">+ <Controller+ control={form.control}+ name="conferencingLabel"+ rules={{+ validate: (label) =>+ label?.trim()+ ? true+ : t("customVideoCallNameRequired", {+ defaultValue: "Name the call, like Microsoft Teams.",+ }),+ }}+ render={({ field, fieldState }) => (+ <div className="grid gap-2">+ <Input+ {...field}+ value={field.value ?? ""}+ id="conferencing-label"+ type="text"+ maxLength={100}+ placeholder={t("customVideoCallNamePlaceholder", {+ defaultValue: "Microsoft Teams",+ })}+ aria-invalid={fieldState.error ? true : undefined}+ />+ {fieldState.error ? (+ <p className="text-destructive text-sm" role="alert">+ {fieldState.error.message}+ </p>+ ) : null}+ </div>+ )}+ />+ <Controller+ control={form.control}+ name="conferencingUrl"+ rules={{+ validate: (url) => {+ if (!url?.trim()) {+ return true;+ }+ try {+ const { protocol } = new URL(url.trim());+ if (protocol !== "https:" && protocol !== "http:") {+ throw new Error();+ }+ return true;+ } catch {+ return t("customLinkInvalid", {+ defaultValue: "That doesn't look like a link.",+ });+ }+ },+ }}+ render={({ field, fieldState }) => (+ <div className="grid gap-2">+ {/* Not type="url": the browser's own constraint check would+ block submit before react-hook-form's rule runs, so the+ organizer would see no message. */}+ <Input+ {...field}+ value={field.value ?? ""}+ id="conferencing-url"+ type="text"+ inputMode="url"+ autoComplete="url"+ aria-label={t("customLinkOptional", {+ defaultValue: "Link (optional)",+ })}+ placeholder={t("customLinkOptional", {+ defaultValue: "Link (optional)",+ })}+ aria-invalid={fieldState.error ? true : undefined}+ />+ {fieldState.error ? (+ <p className="text-destructive text-sm" role="alert">+ {fieldState.error.message}+ </p>+ ) : null}+ </div>+ )}+ />+ </div>+ </FormItem>+ );+ }++ return (+ <Controller+ control={form.control}+ name="conferencingProvider"+ rules={{+ validate: (provider) =>+ !provider || provider === "custom" || connected.includes(provider)+ ? true+ : "not_connected",+ }}+ render={({ field, fieldState }) => {+ const provider = field.value as ConferencingProvider;+ const label = conferencingProviderLabels[provider];++ return (+ <FormItem>+ {header}+ <div className="flex h-9 items-center gap-x-2 rounded-md border bg-input-background px-3 text-sm">+ <ConferencingProviderIcon provider={provider} size={16} />+ <span>{label}</span>+ </div>+ {fieldState.error ? (+ <p className="text-destructive text-sm" role="alert">+ <Trans+ i18nKey="conferencingNotConnected"+ defaults="{provider} is not connected. Visit the <a>Conferencing settings</a> page to connect your account."+ values={{ provider: label }}+ components={{+ a: (+ <Link+ href="/settings/conferencing"+ className="underline hover:text-foreground"+ />+ ),+ }}+ />+ </p>+ ) : null}+ </FormItem>+ );+ }}+ />+ );+}diff --git a/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx b/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsxnew file mode 100644index 000000000..11fb6acb9--- /dev/null+++ b/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx@@ -0,0 +1,18 @@+import GoogleMeetIcon from "@/features/conferencing/assets/google-meet.svg";+import ZoomIcon from "@/features/conferencing/assets/zoom.svg";+import type { ConferencingProvider } from "@/features/conferencing/schema";++export function ConferencingProviderIcon({+ provider,+ size,+}: {+ provider: ConferencingProvider;+ size: number;+}) {+ switch (provider) {+ case "zoom":+ return <ZoomIcon width={size} height={size} aria-hidden="true" />;+ case "meet":+ return <GoogleMeetIcon width={size} height={size} aria-hidden="true" />;+ }+}diff --git a/apps/web/src/features/conferencing/components/connect-conferencing-dropdown.tsx b/apps/web/src/features/conferencing/components/connect-conferencing-dropdown.tsxnew file mode 100644index 000000000..0c99918fa--- /dev/null+++ b/apps/web/src/features/conferencing/components/connect-conferencing-dropdown.tsx@@ -0,0 +1,49 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import { ChevronDownIcon, PlusIcon } from "lucide-react";+import { connectToConferencing } from "@/features/conferencing/client";+import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";+import type { ConferencingProvider } from "@/features/conferencing/schema";+import {+ conferencingProviderIntegrations,+ conferencingProviderLabels,+} from "@/features/conferencing/utils";+import { Trans } from "@/i18n/client";++export function ConnectConferencingDropdown({+ providers,+}: {+ providers: ConferencingProvider[];+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={<Button />}>+ <PlusIcon data-icon="inline-start" />+ <Trans i18nKey="connectAccount" defaults="Connect account" />+ <ChevronDownIcon data-icon="inline-end" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {providers.map((provider) => (+ <DropdownMenuItem+ key={provider}+ onClick={() => {+ connectToConferencing(+ conferencingProviderIntegrations[provider].integrationId,+ );+ }}+ >+ <ConferencingProviderIcon provider={provider} size={16} />+ {conferencingProviderLabels[provider]}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/apps/web/src/features/conferencing/components/poll-conferencing-summary.tsx b/apps/web/src/features/conferencing/components/poll-conferencing-summary.tsxnew file mode 100644index 000000000..12d66921f--- /dev/null+++ b/apps/web/src/features/conferencing/components/poll-conferencing-summary.tsx@@ -0,0 +1,54 @@+"use client";++import { ArrowUpRightIcon, VideoIcon } from "lucide-react";+import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";+import type { PollConferencing } from "@/features/conferencing/schema";+import { conferencingProviderLabels } from "@/features/conferencing/utils";+import { Trans } from "@/i18n/client";++// What the organizer asked for, as shown on the poll page. A provider has no+// link until the poll is finalized, so it shows as the service name; a+// pasted link is already joinable.+export function PollConferencingSummary({+ conferencing,+}: {+ conferencing: PollConferencing;+}) {+ if (conferencing.provider === "custom") {+ if (!conferencing.uri) {+ return (+ <>+ <VideoIcon />+ <span className="truncate">{conferencing.label}</span>+ </>+ );+ }+ return (+ <>+ <VideoIcon />+ <a+ href={conferencing.uri}+ target="_blank"+ rel="noopener noreferrer"+ className="group inline-flex min-w-0 items-center gap-1 hover:text-foreground"+ >+ <span className="truncate">{conferencing.label}</span>+ <ArrowUpRightIcon+ aria-hidden="true"+ className="transition-colors group-hover:text-foreground"+ />+ <span className="sr-only">+ <Trans i18nKey="opensInNewTab" defaults="(opens in new tab)" />+ </span>+ </a>+ </>+ );+ }++ return (+ <>+ <ConferencingProviderIcon provider={conferencing.provider} size={16} />+ <span>{conferencingProviderLabels[conferencing.provider]}</span>+ </>+ );+}diff --git a/apps/web/src/features/conferencing/constants.ts b/apps/web/src/features/conferencing/constants.tsnew file mode 100644index 000000000..3bede0a8c--- /dev/null+++ b/apps/web/src/features/conferencing/constants.ts@@ -0,0 +1,20 @@+import type { ConferencingProvider } from "./schema";++export const isConferencingEnabled =+ process.env.CONFERENCING_ENABLED === "true";++// A provider is offered when its OAuth app is configured; Google Meet reuses+// the Google OAuth app the calendars integration already needs.+export function getAvailableConferencingProviders(): ConferencingProvider[] {+ if (!isConferencingEnabled) {+ return [];+ }+ const providers: ConferencingProvider[] = [];+ if (process.env.ZOOM_CLIENT_ID && process.env.ZOOM_CLIENT_SECRET) {+ providers.push("zoom");+ }+ if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {+ providers.push("meet");+ }+ return providers;+}diff --git a/apps/web/src/features/conferencing/data.ts b/apps/web/src/features/conferencing/data.tsindex dcbfd4f07..9a5de579a 100644--- a/apps/web/src/features/conferencing/data.ts+++ b/apps/web/src/features/conferencing/data.ts@@ -1,9 +1,19 @@import "server-only";import type { Prisma } from "@rallly/database";+import { prisma } from "@rallly/database";import { createLogger } from "@rallly/logger";-import type { Conferencing } from "./schema";-import { conferencingSchema } from "./schema";+import type {+ Conferencing,+ ConferencingProvider,+ PollConferencing,+} from "./schema";+import {+ conferencingProviderSchema,+ conferencingSchema,+ pollConferencingSchema,+} from "./schema";+import { conferencingProviderIntegrations } from "./utils";const logger = createLogger("conferencing/data");@@ -24,3 +34,69 @@ export function parseConferencing(}return parsed.data;}++export function parsePollConferencing(+ raw: Prisma.JsonValue | null,+ context?: { pollId?: string },+): PollConferencing | null {+ if (raw === null) {+ return null;+ }+ const parsed = pollConferencingSchema.safeParse(raw);+ if (!parsed.success) {+ logger.warn(+ { pollId: context?.pollId, value: raw },+ "Failed to parse poll conferencing",+ );+ return null;+ }+ return parsed.data;+}++export const getConferencingConnections = async (userId: string) => {+ return await prisma.conferencingConnection.findMany({+ where: { userId },+ select: {+ id: true,+ provider: true,+ integrationId: true,+ email: true,+ displayName: true,+ },+ orderBy: { createdAt: "asc" },+ });+};++// The providers a user can mint links for, derived from the integrations they+// have connected. One Google account may back both calendar and Meet, so the+// integration id (not the OAuth provider) decides.+export const getConnectedConferencingProviders = async (+ userId: string,+): Promise<ConferencingProvider[]> => {+ const connections = await prisma.conferencingConnection.findMany({+ where: { userId },+ select: { integrationId: true },+ distinct: ["integrationId"],+ });+ const connected = new Set(connections.map((c) => c.integrationId));+ return conferencingProviderSchema.options.filter((provider) =>+ connected.has(conferencingProviderIntegrations[provider].integrationId),+ );+};++export const getConferencingConnectionForProvider = async ({+ userId,+ provider,+}: {+ userId: string;+ provider: ConferencingProvider;+}) => {+ return await prisma.conferencingConnection.findFirst({+ where: {+ userId,+ integrationId: conferencingProviderIntegrations[provider].integrationId,+ },+ select: { id: true, credentialId: true, email: true },+ orderBy: { createdAt: "asc" },+ });+};diff --git a/apps/web/src/features/conferencing/loaders.ts b/apps/web/src/features/conferencing/loaders.tsnew file mode 100644index 000000000..bf4f75a14--- /dev/null+++ b/apps/web/src/features/conferencing/loaders.ts@@ -0,0 +1,27 @@+import "server-only";++import { cache } from "react";+import { loadUser } from "@/features/user/loaders";+import { getAvailableConferencingProviders } from "./constants";+import {+ getConferencingConnections,+ getConnectedConferencingProviders,+} from "./data";++export const loadConferencingConnections = cache(async () => {+ const user = await loadUser();+ return getConferencingConnections(user.id);+});++// What the poll form needs: the providers this instance offers and the ones+// the organizer has already linked. Guests have nothing to link; a pasted+// link needs no provider, so the options always exist.+export const loadConferencingOptions = cache(+ async ({ userId }: { userId: string | null }) => {+ const available = getAvailableConferencingProviders();+ const connected = userId+ ? await getConnectedConferencingProviders(userId)+ : [];+ return { available, connected };+ },+);diff --git a/apps/web/src/features/conferencing/mutations.ts b/apps/web/src/features/conferencing/mutations.tsnew file mode 100644index 000000000..5fa9be369--- /dev/null+++ b/apps/web/src/features/conferencing/mutations.ts@@ -0,0 +1,68 @@+import "server-only";++import { prisma } from "@rallly/database";+import type { UserInfo } from "@/lib/oauth/types";++export const createConferencingConnection = async ({+ userId,+ provider,+ providerAccountId,+ integrationId,+ credentialId,+ displayName,+ userInfo,+}: {+ userId: string;+ provider: string;+ providerAccountId: string;+ integrationId: string;+ credentialId: string;+ displayName: string;+ userInfo: UserInfo;+}) => {+ return await prisma.conferencingConnection.upsert({+ where: {+ user_provider_account_unique: {+ userId,+ provider,+ providerAccountId,+ },+ },+ create: {+ userId,+ provider,+ integrationId,+ credentialId,+ providerAccountId,+ email: userInfo.email,+ displayName,+ },+ update: {+ credentialId,+ email: userInfo.email,+ },+ });+};++// Only the connection goes; the credential row may still back a calendar+// connection on the same Google account.+export const disconnectConferencingConnection = async ({+ userId,+ id,+}: {+ userId: string;+ id: string;+}) => {+ const connection = await prisma.conferencingConnection.findFirst({+ where: { id, userId },+ select: { id: true },+ });++ if (!connection) {+ return { ok: false as const, reason: "not_found" as const };+ }++ await prisma.conferencingConnection.delete({ where: { id } });++ return { ok: true as const };+};diff --git a/apps/web/src/features/conferencing/schema.ts b/apps/web/src/features/conferencing/schema.tsindex 327aea11c..50cb61de6 100644--- a/apps/web/src/features/conferencing/schema.ts+++ b/apps/web/src/features/conferencing/schema.ts@@ -1,5 +1,29 @@import * as z from "zod";+// Providers Rallly can mint links for. Distinct from the stored-link union+// below, which also covers links pasted by hand (custom) and phone dial-ins.+export const conferencingProviderSchema = z.enum(["zoom", "meet"]);+export type ConferencingProvider = z.infer<typeof conferencingProviderSchema>;++// What a poll records before there is a link: a provider to mint with at+// finalize, or a call the organizer names themselves (any service, no+// account needed). The link is optional: most organizers announce the tool+// first and send the link once the time is set.+export const pollConferencingSchema = z.discriminatedUnion("provider", [+ z.object({ provider: z.literal("zoom") }),+ z.object({ provider: z.literal("meet") }),+ z.object({+ provider: z.literal("custom"),+ label: z.string().trim().min(1).max(100),+ uri: z.url({ protocol: /^https?$/ }).optional(),+ }),+]);+export type PollConferencing = z.infer<typeof pollConferencingSchema>;++export const disconnectConferencingConnectionSchema = z.object({+ id: z.string(),+});+const webConferencingSchema = z.object({provider: z.enum(["zoom", "meet", "teams"]),uri: z.url(),@@ -15,7 +39,7 @@ const phoneConferencingSchema = z.object({const customConferencingSchema = z.object({provider: z.literal("custom"),- uri: z.url(),+ uri: z.url({ protocol: /^https?$/ }),label: z.string().min(1),});diff --git a/apps/web/src/features/conferencing/service.ts b/apps/web/src/features/conferencing/service.tsnew file mode 100644index 000000000..55436f911--- /dev/null+++ b/apps/web/src/features/conferencing/service.ts@@ -0,0 +1,184 @@+import "server-only";++import { createLogger } from "@rallly/logger";+import { google } from "googleapis";+import { env } from "@/env";+import { loadCredential } from "@/features/credentials/data";+import { updateOAuthCredentialTokens } from "@/features/credentials/mutations";+import type { OAuthCredentials } from "@/features/credentials/schema";+import { ZoomOAuthClient } from "@/lib/oauth/providers/zoom";+import { getConferencingConnectionForProvider } from "./data";+import type { Conferencing, ConferencingProvider } from "./schema";+import {+ meetSpaceResponseSchema,+ meetSpaceToConferencing,+ zoomMeetingResponseSchema,+ zoomMeetingToConferencing,+} from "./utils";++const logger = createLogger("conferencing/service");++export type CreateConferencingMeetingResult =+ | { ok: true; conferencing: Conferencing }+ | { ok: false; reason: "not_connected" | "provider_error" };++// Mints a meeting link for a scheduled time. The organizer's own account+// hosts the meeting, so the link inherits their provider settings.+export async function createConferencingMeeting({+ userId,+ provider,+ title,+ start,+ end,+ timeZone,+}: {+ userId: string;+ provider: ConferencingProvider;+ title: string;+ start: Date;+ end: Date;+ timeZone?: string | null;+}): Promise<CreateConferencingMeetingResult> {+ const connection = await getConferencingConnectionForProvider({+ userId,+ provider,+ });++ if (!connection) {+ return { ok: false, reason: "not_connected" };+ }++ const credential = await loadCredential(connection.credentialId);++ if (!credential) {+ return { ok: false, reason: "not_connected" };+ }++ try {+ switch (provider) {+ case "zoom": {+ const secret = await refreshZoomTokenIfExpired({ credential });+ const conferencing = await createZoomMeeting({+ accessToken: secret.accessToken,+ title,+ start,+ end,+ timeZone,+ });+ return { ok: true, conferencing };+ }+ case "meet": {+ const conferencing = await createMeetSpace(credential.secret);+ return { ok: true, conferencing };+ }+ }+ } catch (error) {+ // `err` is the key pino's default serializer expands; `error` logs as {}.+ logger.error(+ { err: error, userId, provider, connectionId: connection.id },+ "Failed to create conferencing meeting",+ );+ return { ok: false, reason: "provider_error" };+ }+}++async function refreshZoomTokenIfExpired({+ credential,+}: {+ credential: NonNullable<Awaited<ReturnType<typeof loadCredential>>>;+}): Promise<OAuthCredentials> {+ const expiresAt = credential.secret.expiresAt+ ? new Date(credential.secret.expiresAt)+ : credential.expiresAt;+ // Refresh a minute early so a token that expires mid-request is not used.+ const isFresh = expiresAt && expiresAt.getTime() - 60_000 > Date.now();++ if (isFresh || !credential.secret.refreshToken) {+ return credential.secret;+ }++ if (!env.ZOOM_CLIENT_ID || !env.ZOOM_CLIENT_SECRET) {+ throw new Error("Zoom is not configured");+ }++ const client = new ZoomOAuthClient({+ clientId: env.ZOOM_CLIENT_ID,+ clientSecret: env.ZOOM_CLIENT_SECRET,+ scopes: credential.scopes,+ });++ const tokens = await client.refreshAccessToken(+ credential.secret.refreshToken,+ );++ // Zoom rotates the refresh token on every refresh; the old one is dead,+ // so the new pair is persisted before anything else can fail.+ await updateOAuthCredentialTokens({ id: credential.id, tokens });++ return {+ accessToken: tokens.accessToken,+ refreshToken: tokens.refreshToken,+ expiresAt: tokens.expiresAt?.toISOString(),+ scopes: tokens.scopes,+ };+}+async function createZoomMeeting({+ accessToken,+ title,+ start,+ end,+ timeZone,+}: {+ accessToken: string;+ title: string;+ start: Date;+ end: Date;+ timeZone?: string | null;+}): Promise<Conferencing> {+ const durationMinutes = Math.max(+ 1,+ Math.round((end.getTime() - start.getTime()) / 60_000),+ );+ const res = await fetch("https://api.zoom.us/v2/users/me/meetings", {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ topic: title,+ type: 2, // scheduled meeting+ start_time: start.toISOString(),+ duration: durationMinutes,+ ...(timeZone ? { timezone: timeZone } : {}),+ }),+ });++ if (!res.ok) {+ throw new Error(+ `Zoom meeting creation failed with status ${res.status}: ${await res.text()}`,+ );+ }++ return zoomMeetingToConferencing(+ zoomMeetingResponseSchema.parse(await res.json()),+ );+}++async function createMeetSpace(+ credentials: OAuthCredentials,+): Promise<Conferencing> {+ const auth = new google.auth.OAuth2({+ clientId: env.GOOGLE_CLIENT_ID,+ clientSecret: env.GOOGLE_CLIENT_SECRET,+ });+ auth.setCredentials({+ access_token: credentials.accessToken,+ refresh_token: credentials.refreshToken,+ });++ const meet = google.meet({ version: "v2", auth });+ const { data } = await meet.spaces.create({ requestBody: {} });++ return meetSpaceToConferencing(meetSpaceResponseSchema.parse(data));+}diff --git a/apps/web/src/features/conferencing/utils.test.ts b/apps/web/src/features/conferencing/utils.test.tsnew file mode 100644index 000000000..f48069504--- /dev/null+++ b/apps/web/src/features/conferencing/utils.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { conferencingSchema } from "./schema";+import {+ getConferencingUri,+ meetSpaceResponseSchema,+ meetSpaceToConferencing,+ zoomMeetingResponseSchema,+ zoomMeetingToConferencing,+} from "./utils";++describe("zoomMeetingToConferencing", () => {+ it("maps a Zoom meeting into the stored link shape", () => {+ const meeting = zoomMeetingResponseSchema.parse({+ id: 81234567890,+ join_url: "https://zoom.us/j/81234567890?pwd=abc",+ password: "abc",+ topic: "ignored",+ });+ const conferencing = zoomMeetingToConferencing(meeting);+ expect(conferencing).toEqual({+ provider: "zoom",+ uri: "https://zoom.us/j/81234567890?pwd=abc",+ meetingId: "81234567890",+ password: "abc",+ });+ expect(conferencingSchema.parse(conferencing)).toEqual(conferencing);+ expect(getConferencingUri(conferencing)).toBe(+ "https://zoom.us/j/81234567890?pwd=abc",+ );+ });++ it("drops an empty password", () => {+ const meeting = zoomMeetingResponseSchema.parse({+ id: 1,+ join_url: "https://zoom.us/j/1",+ password: "",+ });+ expect(zoomMeetingToConferencing(meeting)).toEqual({+ provider: "zoom",+ uri: "https://zoom.us/j/1",+ meetingId: "1",+ password: undefined,+ });+ });+});++describe("meetSpaceToConferencing", () => {+ it("maps a Meet space into the stored link shape", () => {+ const space = meetSpaceResponseSchema.parse({+ name: "spaces/abc",+ meetingUri: "https://meet.google.com/abc-defg-hij",+ meetingCode: "abc-defg-hij",+ });+ const conferencing = meetSpaceToConferencing(space);+ expect(conferencing).toEqual({+ provider: "meet",+ uri: "https://meet.google.com/abc-defg-hij",+ meetingId: "abc-defg-hij",+ });+ expect(conferencingSchema.parse(conferencing)).toEqual(conferencing);+ });++ it("rejects a space without a join link", () => {+ expect(+ meetSpaceResponseSchema.safeParse({ name: "spaces/abc" }).success,+ ).toBe(false);+ });+});diff --git a/apps/web/src/features/conferencing/utils.ts b/apps/web/src/features/conferencing/utils.tsindex 3f517dc90..d3f5e58fe 100644--- a/apps/web/src/features/conferencing/utils.ts+++ b/apps/web/src/features/conferencing/utils.ts@@ -1,4 +1,66 @@-import type { Conferencing } from "./schema";+import * as z from "zod";+import type { Conferencing, ConferencingProvider } from "./schema";++// Which OAuth integration backs each provider. Google Meet shares the Google+// OAuth app (and credential row) with Google Calendar.+export const conferencingProviderIntegrations: Record<+ ConferencingProvider,+ { integrationId: string; oauthProvider: string }+> = {+ zoom: { integrationId: "zoom", oauthProvider: "zoom" },+ meet: { integrationId: "google-meet", oauthProvider: "google" },+};++export function integrationIdToConferencingProvider(+ integrationId: string,+): ConferencingProvider | null {+ for (const [provider, integration] of Object.entries(+ conferencingProviderIntegrations,+ )) {+ if (integration.integrationId === integrationId) {+ return provider as ConferencingProvider;+ }+ }+ return null;+}++export const conferencingProviderLabels: Record<ConferencingProvider, string> =+ {+ zoom: "Zoom",+ meet: "Google Meet",+ };++export const zoomMeetingResponseSchema = z.object({+ id: z.number(),+ join_url: z.url(),+ password: z.string().optional(),+});++export function zoomMeetingToConferencing(+ meeting: z.infer<typeof zoomMeetingResponseSchema>,+): Conferencing {+ return {+ provider: "zoom",+ uri: meeting.join_url,+ meetingId: String(meeting.id),+ password: meeting.password || undefined,+ };+}++export const meetSpaceResponseSchema = z.object({+ meetingUri: z.url(),+ meetingCode: z.string().optional(),+});++export function meetSpaceToConferencing(+ space: z.infer<typeof meetSpaceResponseSchema>,+): Conferencing {+ return {+ provider: "meet",+ uri: space.meetingUri,+ meetingId: space.meetingCode,+ };+}// Returns the URI suitable for an href / ICS CONFERENCE value.// Phone numbers are formatted as `tel:` with DTMF pause + extension if present.@@ -10,3 +72,17 @@ export function getConferencingUri(conferencing: Conferencing): string {}return conferencing.uri;}++// What moderation sees of a pasted link: the origin and path only. A Zoom+// join link carries the meeting password in its query string.+export function moderatedLinkText(uri: string | undefined) {+ if (!uri) {+ return "";+ }+ try {+ const { origin, pathname } = new URL(uri);+ return `${origin}${pathname}`;+ } catch {+ return uri;+ }+}diff --git a/apps/web/src/features/credentials/mutations.ts b/apps/web/src/features/credentials/mutations.tsindex af37b8228..e309edc45 100644--- a/apps/web/src/features/credentials/mutations.ts+++ b/apps/web/src/features/credentials/mutations.ts@@ -54,3 +54,23 @@ export async function saveOAuthCredentials({return credential;}}++// A refresh replaces the tokens on a credential the caller already holds.+// Persisting by id keeps the write free of any further provider call, which+// matters for providers that revoke the old refresh token on rotation.+export async function updateOAuthCredentialTokens({+ id,+ tokens,+}: {+ id: string;+ tokens: OAuthTokens;+}) {+ return await prisma.credential.update({+ where: { id },+ data: {+ secret: encrypt(JSON.stringify(tokens), env.SECRET_PASSWORD),+ scopes: tokens.scopes,+ expiresAt: tokens.expiresAt,+ },+ });+}diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsxindex ce5ae35ad..97509cfdf 100644--- a/apps/web/src/features/poll/components/create-poll.tsx+++ b/apps/web/src/features/poll/components/create-poll.tsx@@ -18,6 +18,7 @@ import React from "react";import { useForm, useFormContext } from "react-hook-form";import useFormPersist from "react-hook-form-persist";import { Link } from "@/components/link";+import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";@@ -30,6 +31,29 @@ import { setFlash } from "@/lib/flash/client";import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";import { trpc } from "@/trpc/client";+const toPollConferencing = (+ data: Pick<+ NewEventData,+ "conferencingProvider" | "conferencingUrl" | "conferencingLabel"+ >,+) => {+ switch (data.conferencingProvider) {+ case "zoom":+ case "meet":+ return { provider: data.conferencingProvider };+ case "custom": {+ const uri = data.conferencingUrl?.trim();+ return {+ provider: "custom" as const,+ label: data.conferencingLabel?.trim() ?? "",+ ...(uri ? { uri } : {}),+ };+ }+ default:+ return undefined;+ }+};+const required = <T,>(v: T | undefined): T => {if (!v) {throw new Error("Required value is missing");@@ -126,7 +150,13 @@ const CreatePollActions = ({);};-export const CreatePoll = ({ nav }: { nav?: React.ReactNode }) => {+export const CreatePoll = ({+ nav,+ conferencing,+}: {+ nav?: React.ReactNode;+ conferencing?: ConferencingOptions | null;+}) => {const { t } = useTranslation();const router = useRouter();const { user, createGuestIfNeeded } = useUser();@@ -153,6 +183,9 @@ export const CreatePoll = ({ nav }: { nav?: React.ReactNode }) => {title: "",description: "",location: "",+ conferencingProvider: "",+ conferencingUrl: "",+ conferencingLabel: "",view: "month",options: [],hideScores: false,@@ -213,6 +246,7 @@ export const CreatePoll = ({ nav }: { nav?: React.ReactNode }) => {const res = await makePoll.mutateAsync({title: title,location: formData?.location?.trim(),+ conferencing: toPollConferencing(formData),description: formData?.description?.trim(),// Attach a time zone (times convert per viewer) unless the organizer// locked it to a single wall-clock time or the poll is all-day.@@ -275,7 +309,7 @@ export const CreatePoll = ({ nav }: { nav?: React.ReactNode }) => {</CardDescription></CardHeader><CardContent className="space-y-4">- <PollDetailsForm />+ <PollDetailsForm conferencing={conferencing} /></CardContent></Card>diff --git a/apps/web/src/features/poll/components/event-card.tsx b/apps/web/src/features/poll/components/event-card.tsxindex b86fc496f..e3c146ec7 100644--- a/apps/web/src/features/poll/components/event-card.tsx+++ b/apps/web/src/features/poll/components/event-card.tsx@@ -3,6 +3,7 @@ import { Card, CardContent } from "@rallly/ui/card";import { MapPinIcon, User2Icon } from "lucide-react";import { RandomGradientBar } from "@/components/random-gradient-bar";import { useBranding } from "@/features/branding/client";+import { PollConferencingSummary } from "@/features/conferencing/components/poll-conferencing-summary";import { useInstancePolicy } from "@/features/instance-policy/client";import { usePoll } from "@/features/poll/client";import {@@ -99,6 +100,11 @@ export function EventCard() {<TruncatedLinkify>{poll.location}</TruncatedLinkify></EventMetaItem>) : null}+ {poll.conferencing ? (+ <EventMetaItem>+ <PollConferencingSummary conferencing={poll.conferencing} />+ </EventMetaItem>+ ) : null}</EventMetaList><h2 className="mt-4 mb-1.5 font-medium text-sm"><Trans i18nKey="responseOptions" defaults="Response options" />diff --git a/apps/web/src/features/poll/components/forms/poll-details-form.tsx b/apps/web/src/features/poll/components/forms/poll-details-form.tsxindex 138daf23a..739f445ac 100644--- a/apps/web/src/features/poll/components/forms/poll-details-form.tsx+++ b/apps/web/src/features/poll/components/forms/poll-details-form.tsx@@ -1,9 +1,22 @@import { Button } from "@rallly/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";import { FormField, FormItem, FormLabel, FormMessage } from "@rallly/ui/form";import { Input } from "@rallly/ui/input";-import { PlusIcon } from "lucide-react";+import { BuildingIcon, PlusIcon } from "lucide-react";import * as React from "react";import { Controller, useFormContext } from "react-hook-form";+import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";+import {+ ConferencingField,+ ConferencingProviderMenuItems,+} from "@/features/conferencing/components/conferencing-field";import { MAX_POLL_DESCRIPTION_LENGTH } from "@/features/poll/schema";import { Trans, useTranslation } from "@/i18n/client";import { useFormValidation } from "@/lib/utils/form-validation";@@ -11,13 +24,34 @@ import { useFormValidation } from "@/lib/utils/form-validation";import { LazyRichTextEditor } from "./lazy-rich-text-editor";import type { NewEventData } from "./types";-export const PollDetailsForm = () => {+// `conferencing` is absent on forms that don't support video calls (the edit+// form); "Add location" then opens the address field directly.+export const PollDetailsForm = ({+ conferencing,+}: {+ conferencing?: ConferencingOptions | null;+}) => {const { t } = useTranslation();const form = useFormContext<NewEventData>();const { requiredString } = useFormValidation();const { register } = form;+ // Optional fields reveal themselves whenever they hold content — covering+ // values restored asynchronously (persisted drafts, the edit form) — or once+ // the user opens them. Remove clears the value and resets `opened`, so the+ // field collapses again.+ const [locationOpened, setLocationOpened] = React.useState(false);+ const hasLocation = !!form.watch("location")?.trim();+ const locationExpanded = locationOpened || hasLocation;++ const [descriptionOpened, setDescriptionOpened] = React.useState(false);+ const hasDescription = !!form.watch("description")?.trim();+ const descriptionExpanded = descriptionOpened || hasDescription;++ const canAddAddress = !locationExpanded;+ const canAddVideoCall = !!conferencing && !form.watch("conferencingProvider");+return (<div className="grid gap-4 py-1"><FormField@@ -42,56 +76,100 @@ export const PollDetailsForm = () => {</FormItem>)}/>-- <FormItem>- <div>- <FormLabel className="inline-block" htmlFor="location">- {t("location")}- </FormLabel>- <span className="ml-1 text-muted-foreground text-sm">- <Trans i18nKey="optionalLabel" defaults="(Optional)" />- </span>- </div>- <Input- type="text"- id="location"- className="w-full"- placeholder={t("locationPlaceholder")}- {...register("location")}+ {locationExpanded ? (+ <FormItem>+ <div className="flex items-center justify-between">+ <FormLabel htmlFor="location">{t("location")}</FormLabel>+ <Button+ type="button"+ variant="link"+ size="sm"+ className="h-auto p-0 text-muted-foreground hover:text-foreground"+ onClick={() => {+ form.setValue("location", "");+ setLocationOpened(false);+ }}+ >+ <Trans i18nKey="remove" defaults="Remove" />+ </Button>+ </div>+ <Input+ type="text"+ id="location"+ className="w-full"+ placeholder={t("locationPlaceholder")}+ {...register("location")}+ />+ </FormItem>+ ) : null}+ {conferencing ? (+ <ConferencingField connected={conferencing.connected} />+ ) : null}+ {descriptionExpanded ? (+ <DescriptionField+ onRemove={() => {+ form.setValue("description", "");+ setDescriptionOpened(false);+ }}/>- </FormItem>- <DescriptionField />+ ) : null}+ {canAddAddress || canAddVideoCall || !descriptionExpanded ? (+ <div className="flex flex-wrap gap-2">+ {canAddVideoCall ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Button type="button" className="rounded-full" />}+ >+ <PlusIcon data-icon="inline-start" />+ <Trans i18nKey="addLocation" defaults="Add location" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {canAddAddress ? (+ <DropdownMenuGroup>+ <DropdownMenuLabel>+ <Trans i18nKey="inPerson" defaults="In-person" />+ </DropdownMenuLabel>+ <DropdownMenuItem onClick={() => setLocationOpened(true)}>+ <BuildingIcon />+ <Trans i18nKey="address" defaults="Address" />+ </DropdownMenuItem>+ </DropdownMenuGroup>+ ) : null}+ <ConferencingProviderMenuItems+ available={conferencing.available}+ />+ </DropdownMenuContent>+ </DropdownMenu>+ ) : canAddAddress ? (+ <Button+ type="button"+ className="rounded-full"+ onClick={() => setLocationOpened(true)}+ >+ <PlusIcon data-icon="inline-start" />+ <Trans i18nKey="addLocation" defaults="Add location" />+ </Button>+ ) : null}+ {!descriptionExpanded ? (+ <Button+ type="button"+ className="rounded-full"+ onClick={() => setDescriptionOpened(true)}+ >+ <PlusIcon data-icon="inline-start" />+ <Trans i18nKey="addDescription" defaults="Add description" />+ </Button>+ ) : null}+ </div>+ ) : null}</div>);};-const DescriptionField = () => {+const DescriptionField = ({ onRemove }: { onRemove: () => void }) => {const { t } = useTranslation();const form = useFormContext<NewEventData>();- // Reveal the editor whenever the field holds content — this covers values- // restored asynchronously (persisted drafts, the edit form) that aren't yet- // present on first render — or once the user opens it via the button. Remove- // clears the value and resets `opened`, so it collapses again.- const [opened, setOpened] = React.useState(false);- const hasContent = !!form.watch("description")?.trim();- const expanded = opened || hasContent;-- if (!expanded) {- return (- <div>- <Button- type="button"- className="rounded-full"- onClick={() => setOpened(true)}- >- <PlusIcon data-icon="inline-start" />- <Trans i18nKey="addDescription" defaults="Add description" />- </Button>- </div>- );- }-return (<FormItem><div className="flex items-center justify-between">@@ -103,10 +181,7 @@ const DescriptionField = () => {variant="link"size="sm"className="h-auto p-0 text-muted-foreground hover:text-foreground"- onClick={() => {- form.setValue("description", "");- setOpened(false);- }}+ onClick={onRemove}><Trans i18nKey="remove" defaults="Remove" /></Button>diff --git a/apps/web/src/features/poll/components/forms/types.ts b/apps/web/src/features/poll/components/forms/types.tsindex abe12928b..2157ef12f 100644--- a/apps/web/src/features/poll/components/forms/types.ts+++ b/apps/web/src/features/poll/components/forms/types.ts@@ -1,9 +1,14 @@+import type { ConferencingProvider } from "@/features/conferencing/schema";import type { DateTimeOption } from "./poll-options-form/types";export interface PollDetailsData {title: string;location: string;description: string;+ // Empty string is "none"; the form persists to storage, which has no undefined.+ conferencingProvider?: ConferencingProvider | "custom" | "";+ conferencingUrl?: string;+ conferencingLabel?: string;}export type PollOptionsData = {diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.tsindex bf7b5aeff..845903dd7 100644--- a/apps/web/src/features/poll/data.ts+++ b/apps/web/src/features/poll/data.ts@@ -3,6 +3,7 @@ import "server-only";import type { PollStatus, Prisma, VoteType } from "@rallly/database";import { prisma } from "@rallly/database";import { shortUrl } from "@rallly/utils/absolute-url";+import { parsePollConferencing } from "@/features/conferencing/data";import { getInstancePolicy } from "@/features/instance-policy/data";import { VOTE_TYPES } from "@/features/poll/constants";import type {@@ -259,6 +260,7 @@ export async function listPolls({title: true,description: true,location: true,+ conferencing: true,timeZone: true,status: true,kind: true,@@ -302,8 +304,9 @@ export async function listPolls({const page = hasMore ? polls.slice(0, limit) : polls;return {- polls: page.map(({ _count, ...poll }) => ({+ polls: page.map(({ _count, conferencing, ...poll }) => ({...poll,+ conferencing: parsePollConferencing(conferencing, { pollId: poll.id }),participantCount: _count.participants,})),nextCursor: hasMore ? (page[page.length - 1]?.id ?? null) : null,@@ -600,6 +603,7 @@ export async function getPollWithOptions({title: true,description: true,location: true,+ conferencing: true,timeZone: true,status: true,kind: true,@@ -640,8 +644,12 @@ export async function getPollWithOptions({return null;}- const { _count, ...rest } = poll;- return { ...rest, participantCount: _count.participants };+ const { _count, conferencing, ...rest } = poll;+ return {+ ...rest,+ conferencing: parsePollConferencing(conferencing, { pollId: poll.id }),+ participantCount: _count.participants,+ };}/**@@ -701,6 +709,7 @@ export async function getPollDetails({timeZone: true,title: true,location: true,+ conferencing: true,description: true,createdAt: true,status: true,@@ -757,11 +766,13 @@ export async function getPollDetails({deleted: _deleted,user,space,+ conferencing,...pollFields} = poll;return {...pollFields,+ conferencing: parsePollConferencing(conferencing, { pollId: poll.id }),user: user ? { id: user.id, name: user.name, image: user.image } : null,space: space? {diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.tsindex 20b2d2e05..24bb3ce6a 100644--- a/apps/web/src/features/poll/mutations.test.ts+++ b/apps/web/src/features/poll/mutations.test.ts@@ -182,10 +182,16 @@ describe("closePoll", () => {expect(mockUpdate).not.toHaveBeenCalled();});- const openPoll = { id: "p1", status: "open", _count: { participants: 2 } };+ const openPoll = {+ id: "p1",+ status: "open",+ conferencing: null,+ _count: { participants: 2 },+ };const closedPoll = {id: "p1",status: "closed",+ conferencing: null,_count: { participants: 2 },};@@ -201,7 +207,12 @@ describe("closePoll", () => {data: { status: "closed", closedReason: "manual" },}),);- expect(result).toEqual({ id: "p1", status: "closed", participantCount: 2 });+ expect(result).toEqual({+ id: "p1",+ status: "closed",+ conferencing: null,+ participantCount: 2,+ });});it("is idempotent and does not update an already-closed poll", async () => {@@ -211,7 +222,12 @@ describe("closePoll", () => {expect(mockUpdate).not.toHaveBeenCalled();expect(mockActivityCreateMany).not.toHaveBeenCalled();- expect(result).toEqual({ id: "p1", status: "closed", participantCount: 2 });+ expect(result).toEqual({+ id: "p1",+ status: "closed",+ conferencing: null,+ participantCount: 2,+ });});it("records a poll_closed activity alongside the close", async () => {diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex e9e601e10..3250caf55 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -5,6 +5,8 @@ import { prisma } from "@rallly/database";import { nanoid } from "@rallly/utils/nanoid";import { revalidatePath } from "next/cache";import { recordPollActivities } from "@/features/activity/mutations";+import { parsePollConferencing } from "@/features/conferencing/data";+import type { PollConferencing } from "@/features/conferencing/schema";import type { AuthorizedSpaceId } from "@/features/space/types";import { scheduleWebhookDispatch } from "@/features/webhook/mutations";@@ -18,6 +20,7 @@ export type CreatePollParams = {title: string;description?: string;location?: string;+ conferencing?: PollConferencing;timeZone?: string;requireParticipantEmail?: boolean;hideParticipants?: boolean;@@ -35,6 +38,7 @@ const pollResponseSelect = {title: true,description: true,location: true,+ conferencing: true,timeZone: true,status: true,kind: true,@@ -70,16 +74,28 @@ const pollResponseSelect = {},} satisfies Prisma.PollSelect;-const toPollResponse = <T extends { _count: { participants: number } }>({+const toPollResponse = <+ T extends {+ id: string;+ conferencing: Prisma.JsonValue | null;+ _count: { participants: number };+ },+>({_count,+ conferencing,...poll-}: T) => ({ ...poll, participantCount: _count.participants });+}: T) => ({+ ...poll,+ conferencing: parsePollConferencing(conferencing, { pollId: poll.id }),+ participantCount: _count.participants,+});export const createPoll = async ({userId,title,description,location,+ conferencing,timeZone,requireParticipantEmail,hideParticipants,@@ -98,6 +114,7 @@ export const createPoll = async ({title,description,location,+ conferencing,timeZone,requireParticipantEmail,hideParticipants,diff --git a/apps/web/src/features/poll/types.ts b/apps/web/src/features/poll/types.tsindex 810c9bbd6..d4f3d1952 100644--- a/apps/web/src/features/poll/types.ts+++ b/apps/web/src/features/poll/types.ts@@ -1,3 +1,4 @@+import type { PollConferencing } from "@/features/conferencing/schema";import type { VoteType } from "@/features/poll/constants";import type { PollClosedReason, PollStatus } from "@/features/poll/schema";import type { SpaceTier } from "@/features/space/schema";@@ -8,6 +9,7 @@ export type PollDetails = {id: string;title: string;location: string | null;+ conferencing: PollConferencing | null;description: string | null;createdAt: Date;status: PollStatus;diff --git a/apps/web/src/features/scheduled-event/data.ts b/apps/web/src/features/scheduled-event/data.tsindex a1f605c36..010117539 100644--- a/apps/web/src/features/scheduled-event/data.ts+++ b/apps/web/src/features/scheduled-event/data.ts@@ -327,6 +327,23 @@ export async function getUpcomingEventCount({});}+// Everything a user hosts, across spaces: the account deletion dialog warns+// about events that would be lost, wherever they live.+export async function getUserUpcomingEventCount({+ userId,+ timeZone,+}: {+ userId: string;+ timeZone: string;+}) {+ return prisma.scheduledEvent.count({+ where: {+ userId,+ ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),+ },+ });+}+export const getUpcomingEvents = async ({search,member,diff --git a/apps/web/src/features/user/account-deletion/data.ts b/apps/web/src/features/user/account-deletion/data.tsindex a3d18b925..fbd6b9cef 100644--- a/apps/web/src/features/user/account-deletion/data.ts+++ b/apps/web/src/features/user/account-deletion/data.ts@@ -1,7 +1,6 @@import "server-only";import { prisma } from "@rallly/database";-import { upcomingScheduledEventWhere } from "@/features/scheduled-event/utils";export async function findUsersScheduledForRemoval({cutoff,@@ -27,26 +26,16 @@ export async function findUsersScheduledForRemoval({// dialog mentions those without numbers.export async function getAccountDeletionSummary({userId,- timeZone,}: {userId: string;- timeZone: string;}) {- const [activePollCount, upcomingEventCount, activeSubscriptionCount] =- await Promise.all([- prisma.poll.count({ where: { userId, deleted: false, status: "open" } }),- prisma.scheduledEvent.count({- where: {- userId,- ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),- },- }),- prisma.subscription.count({ where: { userId, active: true } }),- ]);+ const [activePollCount, activeSubscriptionCount] = await Promise.all([+ prisma.poll.count({ where: { userId, deleted: false, status: "open" } }),+ prisma.subscription.count({ where: { userId, active: true } }),+ ]);return {activePollCount,- upcomingEventCount,hasActiveSubscription: activeSubscriptionCount > 0,};}diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.tsindex 7fd470c1f..9c9ebd782 100644--- a/apps/web/src/features/user/mutations.ts+++ b/apps/web/src/features/user/mutations.ts@@ -220,6 +220,7 @@ export async function deleteOrphanedAnonymousUsers() {subscriptions: { none: {} },paymentMethods: { none: {} },calendarConnections: { none: {} },+ conferencingConnections: { none: {} },credentials: { none: {} },} satisfies Prisma.UserWhereInput;diff --git a/apps/web/src/lib/errors/app-error.ts b/apps/web/src/lib/errors/app-error.tsindex f4c59c7fd..d94e22e1b 100644--- a/apps/web/src/lib/errors/app-error.ts+++ b/apps/web/src/lib/errors/app-error.ts@@ -9,7 +9,9 @@ export type AppErrorCode =| "POLL_FULL"| "SERVICE_UNAVAILABLE"| "SETUP_REQUIRED"- | "TOO_MANY_REQUESTS";+ | "TOO_MANY_REQUESTS"+ | "CONFERENCING_NOT_CONNECTED"+ | "CONFERENCING_FAILED";export class AppError extends Error {code: AppErrorCode;diff --git a/apps/web/src/lib/feature-flags/config.ts b/apps/web/src/lib/feature-flags/config.tsindex 9fd01723d..05de63d8b 100644--- a/apps/web/src/lib/feature-flags/config.ts+++ b/apps/web/src/lib/feature-flags/config.ts@@ -2,6 +2,7 @@ import "server-only";import { env } from "@/env";import { isBillingEnabled } from "@/features/billing/constants";import { isCalendarsEnabled } from "@/features/calendars/constants";+import { isConferencingEnabled } from "@/features/conferencing/constants";import { isEventTypesEnabled } from "@/features/event-types/constants";import { isFeedbackEnabled } from "@/features/feedback/constants";import { isQuickCreateEnabled } from "@/features/quick-create/constants";@@ -26,6 +27,7 @@ export const featureFlagConfig: FeatureFlagConfig = {// on every path that mints an account, social callbacks included.registration: isRegistrationEnabled,calendars: isCalendarsEnabled,+ conferencing: isConferencingEnabled,eventTypes: isEventTypesEnabled,// The new poll admin at /polls/[pollId] is dev-only until it reaches// feature parity with the legacy admin and cuts over.diff --git a/apps/web/src/lib/feature-flags/types.ts b/apps/web/src/lib/feature-flags/types.tsindex ec8f9788b..361955f86 100644--- a/apps/web/src/lib/feature-flags/types.ts+++ b/apps/web/src/lib/feature-flags/types.ts@@ -6,6 +6,7 @@ export interface FeatureFlagConfig {captcha: boolean;registration: boolean;calendars: boolean;+ conferencing: boolean;eventTypes: boolean;pollAdmin: boolean;quickCreate: boolean;diff --git a/apps/web/src/lib/oauth/constants.ts b/apps/web/src/lib/oauth/constants.tsnew file mode 100644index 000000000..34f1fd761--- /dev/null+++ b/apps/web/src/lib/oauth/constants.ts@@ -0,0 +1,3 @@+// Flash key the OAuth callback writes and settings pages read (`lib/flash`).+// Value is `connected:<integrationId>` or `error:<code>`.+export const OAUTH_FLASH_KEY = "oauth";diff --git a/apps/web/src/lib/oauth/providers/google.ts b/apps/web/src/lib/oauth/providers/google.tsindex f90d6155c..addb046f1 100644--- a/apps/web/src/lib/oauth/providers/google.ts+++ b/apps/web/src/lib/oauth/providers/google.ts@@ -53,6 +53,10 @@ export class GoogleOAuthClient implements OAuthClient {authUrl.searchParams.set("access_type", "offline");authUrl.searchParams.set("prompt", "consent");+ // Calendar and Meet share one credential row per Google account, so a+ // later consent must return a token carrying every scope granted so far+ // rather than replacing them with only the newly requested ones.+ authUrl.searchParams.set("include_granted_scopes", "true");return authUrl;}diff --git a/apps/web/src/lib/oauth/providers/zoom.ts b/apps/web/src/lib/oauth/providers/zoom.tsnew file mode 100644index 000000000..7451b260c--- /dev/null+++ b/apps/web/src/lib/oauth/providers/zoom.ts@@ -0,0 +1,102 @@+import "server-only";++import { Zoom } from "arctic";+import * as z from "zod";+import type { OAuthClient, OAuthTokens, UserInfo } from "../types";+import { handleOAuthError } from "./base";++const zoomUserSchema = z.object({+ id: z.string(),+ email: z.string(),+ display_name: z.string().optional(),+ first_name: z.string().optional(),+ last_name: z.string().optional(),+});++interface ZoomOAuthClientConfig {+ clientId: string;+ clientSecret: string;+ callbackUrl?: string;+ scopes: string[];+ onConnect?: OAuthClient["onConnect"];+}++export class ZoomOAuthClient implements OAuthClient {+ provider = "zoom";+ private client: Zoom;+ scopes: string[];+ onConnect?: OAuthClient["onConnect"];++ constructor({+ clientId,+ clientSecret,+ scopes,+ callbackUrl = "",+ onConnect,+ }: ZoomOAuthClientConfig) {+ this.client = new Zoom(clientId, clientSecret, callbackUrl);+ this.scopes = scopes;+ this.onConnect = onConnect;+ }++ getAuthorizationUrl(state: string, codeVerifier: string): URL {+ return this.client.createAuthorizationURL(state, codeVerifier, this.scopes);+ }++ async exchangeCode(code: string, codeVerifier: string): Promise<OAuthTokens> {+ try {+ const tokens = await this.client.validateAuthorizationCode(+ code,+ codeVerifier,+ );+ return {+ accessToken: tokens.accessToken(),+ refreshToken: tokens.hasRefreshToken()+ ? tokens.refreshToken()+ : undefined,+ expiresAt: tokens.accessTokenExpiresAt(),+ scopes: tokens.hasScopes() ? tokens.scopes() : this.scopes,+ };+ } catch (error) {+ handleOAuthError(error);+ }+ }++ async getUserInfo(tokens: OAuthTokens): Promise<UserInfo> {+ try {+ const res = await fetch("https://api.zoom.us/v2/users/me", {+ headers: { Authorization: `Bearer ${tokens.accessToken}` },+ });+ if (!res.ok) {+ throw new Error(`Zoom user lookup failed with status ${res.status}`);+ }+ const user = zoomUserSchema.parse(await res.json());+ const name =+ user.display_name ||+ [user.first_name, user.last_name].filter(Boolean).join(" ");+ return {+ id: user.id,+ email: user.email,+ name: name || undefined,+ };+ } catch (error) {+ handleOAuthError(error);+ }+ }++ async refreshAccessToken(refreshToken: string): Promise<OAuthTokens> {+ try {+ const tokens = await this.client.refreshAccessToken(refreshToken);+ return {+ accessToken: tokens.accessToken(),+ refreshToken: tokens.hasRefreshToken()+ ? tokens.refreshToken()+ : refreshToken,+ expiresAt: tokens.accessTokenExpiresAt(),+ scopes: tokens.hasScopes() ? tokens.scopes() : this.scopes,+ };+ } catch (error) {+ handleOAuthError(error);+ }+ }+}diff --git a/apps/web/src/lib/oauth/server.ts b/apps/web/src/lib/oauth/server.tsindex fe271bf35..09ae387c3 100644--- a/apps/web/src/lib/oauth/server.ts+++ b/apps/web/src/lib/oauth/server.ts@@ -4,11 +4,14 @@ import { zValidator } from "@hono/zod-validator";import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { generateCodeVerifier, generateState } from "arctic";+import type { Context } from "hono";import { Hono } from "hono";import { getCookie, setCookie } from "hono/cookie";import { handle } from "hono/vercel";import * as z from "zod";+import { FLASH_MAX_AGE, flashCookieName } from "@/lib/flash/constants";import { validateRedirectUrl } from "@/lib/utils/redirect";+import { OAUTH_FLASH_KEY } from "./constants";import type { CreateOAuthOptions } from "./types";const logger = createLogger("oauth");@@ -32,6 +35,28 @@ export function OAuthIntegration<T extends string>(const REDIRECT_TO = `${prefix}redirect-to`;const STATE = `${prefix}state`;+ // Outcome travels as a one-shot flash (`lib/flash`), not a query param, so+ // a reload of the landing page never replays the toast.+ const setOutcome = (+ c: Context,+ outcome: { connected: string } | { error: string },+ ) => {+ setCookie(+ c,+ flashCookieName(OAUTH_FLASH_KEY),+ "connected" in outcome+ ? `connected:${outcome.connected}`+ : `error:${outcome.error}`,+ {+ httpOnly: false,+ secure: cookieOptions.secure,+ sameSite: "lax",+ maxAge: FLASH_MAX_AGE,+ path: "/",+ },+ );+ };+const app = new Hono().basePath(basePath);// Create schema with available provider names@@ -128,9 +153,8 @@ export function OAuthIntegration<T extends string>(state !== storedState ||!codeVerifier) {- const errorUrl = new URL(redirectTo, absoluteUrl());- errorUrl.searchParams.set("error", "invalid_request");- return c.redirect(errorUrl.toString());+ setOutcome(c, { error: "invalid_request" });+ return c.redirect(new URL(redirectTo, absoluteUrl()).toString());}// Exchange code for tokens@@ -145,19 +169,14 @@ export function OAuthIntegration<T extends string>(tokens,});- // Redirect with success- const successUrl = new URL(redirectTo, absoluteUrl());- successUrl.searchParams.set("connected", "true");- successUrl.searchParams.set("integration", id);-- return c.redirect(successUrl.toString());+ setOutcome(c, { connected: id });+ return c.redirect(new URL(redirectTo, absoluteUrl()).toString());} catch (error) {logger.error({ error }, "OAuth connection failed");const redirectTo = getCookie(c, REDIRECT_TO) || "/";- const errorUrl = new URL(redirectTo, absoluteUrl());- errorUrl.searchParams.set("error", "connection_failed");- return c.redirect(errorUrl.toString());+ setOutcome(c, { error: "connection_failed" });+ return c.redirect(new URL(redirectTo, absoluteUrl()).toString());}});diff --git a/apps/web/src/trpc/client/provider.tsx b/apps/web/src/trpc/client/provider.tsxindex ab939b429..2717eccce 100644--- a/apps/web/src/trpc/client/provider.tsx+++ b/apps/web/src/trpc/client/provider.tsx@@ -70,6 +70,24 @@ export function TRPCProvider(props: { children: React.ReactNode }) {},);break;+ // Finalizing a poll mints the meeting link first; these carry their+ // own remedy and must not be reported as a generic server error.+ case "CONFERENCING_NOT_CONNECTED":+ toast.error(+ t("actionErrorConferencingNotConnected", {+ defaultValue:+ "Your video call account is not connected. Connect it in Conferencing settings and try again.",+ }),+ );+ break;+ case "CONFERENCING_FAILED":+ toast.error(+ t("actionErrorConferencingFailed", {+ defaultValue:+ "We couldn't create the meeting link. Check your account in Conferencing settings and try again.",+ }),+ );+ break;case "UNAUTHORIZED":toast.error(t("actionErrorUnauthorized", {@@ -147,8 +165,10 @@ export function TRPCProvider(props: { children: React.ReactNode }) {}showErrorToast(- error.data.appError === "INVALID_SESSION"- ? "INVALID_SESSION"+ error.data.appError === "INVALID_SESSION" ||+ error.data.appError === "CONFERENCING_NOT_CONNECTED" ||+ error.data.appError === "CONFERENCING_FAILED"+ ? error.data.appError: error.data.code,);}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 5292cb5fd..0daa4407d 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -9,6 +9,21 @@ import { after } from "next/server";import * as z from "zod";import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";import { recordPollActivities } from "@/features/activity/mutations";+import {+ getConnectedConferencingProviders,+ parsePollConferencing,+} from "@/features/conferencing/data";+import type {+ Conferencing,+ PollConferencing,+} from "@/features/conferencing/schema";+import { pollConferencingSchema } from "@/features/conferencing/schema";+import { createConferencingMeeting } from "@/features/conferencing/service";+import {+ conferencingProviderLabels,+ getConferencingUri,+ moderatedLinkText,+} from "@/features/conferencing/utils";import { getInstancePolicy } from "@/features/instance-policy/data";import { moderateContent } from "@/features/moderation/mutations";import {@@ -25,6 +40,7 @@ import {} from "@/features/space/utils";import { scheduleWebhookDispatch } from "@/features/webhook/mutations";import { dayjs } from "@/lib/dayjs";+import { AppError } from "@/lib/errors/app-error";import { identifyGroup, track } from "@/lib/posthog";import { createIcsEvent } from "@/lib/utils/ics";import {@@ -50,6 +66,58 @@ const optionEndsInFuture = (option: { startTime: Date; duration: number }) =>.add(option.duration === 0 ? 24 * 60 : option.duration, "minute").isAfter(dayjs());+async function mintConferencing({+ userId,+ conferencing,+ title,+ start,+ end,+ timeZone,+}: {+ userId: string;+ conferencing: PollConferencing | null;+ title: string;+ start: Date;+ end: Date;+ timeZone: string | null | undefined;+}): Promise<Conferencing | null> {+ if (!conferencing) {+ return null;+ }++ // A pasted link is already the stored shape; nothing to mint. A call named+ // without a link has nothing the event can carry.+ if (conferencing.provider === "custom") {+ return conferencing.uri+ ? { provider: "custom", uri: conferencing.uri, label: conferencing.label }+ : null;+ }++ const result = await createConferencingMeeting({+ userId,+ provider: conferencing.provider,+ title,+ start,+ end,+ timeZone,+ });++ if (result.ok) {+ return result.conferencing;+ }++ const label = conferencingProviderLabels[conferencing.provider];+ const code =+ result.reason === "not_connected"+ ? "CONFERENCING_NOT_CONNECTED"+ : "CONFERENCING_FAILED";+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: `${label} meeting could not be created (${code})`,+ cause: new AppError({ code, message: `${label}: ${result.reason}` }),+ });+}+export const polls = router({invites,infiniteChronological: spaceProcedure@@ -95,6 +163,7 @@ export const polls = router({title: z.string().trim().min(1),timeZone: timeZoneInput,location: z.string().trim().optional(),+ conferencing: pollConferencingSchema.optional(),description: z.string().trim()@@ -136,6 +205,13 @@ export const polls = router({Title: input.title,Description: input.description || "",Location: input.location || "",+ // The pasted URL goes in with its label so a benign label cannot+ // hide a scam destination from moderation. Only the origin and+ // path: a Zoom join link carries the meeting password in its query.+ Conferencing:+ input.conferencing?.provider === "custom"+ ? `${input.conferencing.label} ${moderatedLinkText(input.conferencing.uri)}`+ : "",},});@@ -163,6 +239,23 @@ export const polls = router({const pollId = nanoid();const spaceId = activeSpace?.id;+ // The form blocks this client-side; the check here covers a stale form+ // after the account was disconnected in another tab. Guests can never+ // hold a connection, so they fail the same way. A pasted link needs+ // no account.+ const conferencing = input.conferencing;+ if (conferencing && conferencing.provider !== "custom") {+ const connected = ctx.user.isGuest+ ? []+ : await getConnectedConferencingProviders(ctx.user.id);+ if (!connected.includes(conferencing.provider)) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "Conferencing provider is not connected",+ });+ }+ }+// Date-only (all-day) options are floating: they are stored at UTC// midnight so they never shift across timezones. A falsy poll.timeZone// is the single source of truth for "floating", so date-only polls drop@@ -197,6 +290,7 @@ export const polls = router({title,timeZone,location,+ conferencing,description,userId: ctx.user.id,kind,@@ -754,6 +848,7 @@ export const polls = router({timeZone: true,title: true,location: true,+ conferencing: true,description: true,createdAt: true,status: true,@@ -896,6 +991,8 @@ export const polls = router({timeZone: true,title: true,location: true,+ conferencing: true,+ status: true,description: true,spaceId: true,hideParticipants: true,@@ -910,6 +1007,7 @@ export const polls = router({},user: {select: {+ id: true,name: true,email: true,locale: true,@@ -994,16 +1092,47 @@ export const polls = router({const eventId = nanoid();const uid = `${eventId}@rallly.co`;+ // A second booking would mint a second meeting and orphan the first+ // event, so a poll is booked once; reopen it to book again.+ if (poll.status === "scheduled") {+ throw new TRPCError({+ code: "CONFLICT",+ message: "Poll is already scheduled",+ });+ }++ // The meeting is minted before anything is written: a failed provider+ // call leaves the poll open so the organizer can fix the connection and+ // try again, instead of an event going out without a link. The poll+ // owner's account hosts the meeting, whichever member books it.+ const conferencing = await mintConferencing({+ userId: poll.user.id,+ conferencing: parsePollConferencing(poll.conferencing, {+ pollId: poll.id,+ }),+ title: poll.title,+ start: eventTimes.start,+ end: eventTimes.end,+ timeZone: eventTimes.timeZone,+ });+const attendees = poll.participants.filter((p) =>p.votes.some((v) => v.optionId === input.optionId && v.type !== "no"),);+ // The calendar entry carries the join link the same way the event API+ // does: as the location when there is no place, and in the description.+ const conferencingUri = conferencing+ ? getConferencingUri(conferencing)+ : undefined;const event = createIcsEvent({uid,sequence: 0,title: poll.title,- location: poll.location ?? undefined,- description: poll.description ?? undefined,+ location: poll.location || conferencingUri,+ description:+ [poll.description, conferencingUri].filter(Boolean).join("\n\n") ||+ undefined,start: eventTimes.start,end: eventTimes.end,allDay: eventTimes.allDay,@@ -1071,6 +1200,7 @@ export const polls = router({location: poll.location? { provider: "custom", address: poll.location }: undefined,+ conferencing: conferencing ?? undefined,timeZone: eventTimes.timeZone,userId: ctx.user.id,spaceId,diff --git a/apps/web/tests/conferencing.spec.ts b/apps/web/tests/conferencing.spec.tsnew file mode 100644index 000000000..01755aeb5--- /dev/null+++ b/apps/web/tests/conferencing.spec.ts@@ -0,0 +1,195 @@+import type { Page } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import { encrypt } from "@rallly/utils/encryption";+import { NewPollPage } from "./new-poll-page";+import { createUserInDb, loginWithEmail } from "./test-utils";++const runId = Date.now().toString(36);++// Seeds what the OAuth callback would have written, so the UI can be+// exercised without driving Zoom's consent screen.+async function seedZoomConnection(userId: string) {+ const secretPassword = process.env.SECRET_PASSWORD;+ if (!secretPassword) {+ throw new Error("SECRET_PASSWORD is required to seed a credential");+ }+ const credential = await prisma.credential.create({+ data: {+ userId,+ provider: "zoom",+ providerAccountId: `zoom-${runId}`,+ type: "OAUTH",+ secret: encrypt(+ JSON.stringify({+ accessToken: "test-token",+ scopes: ["meeting:write:meeting"],+ }),+ secretPassword,+ ),+ scopes: ["meeting:write:meeting"],+ },+ });+ return prisma.conferencingConnection.create({+ data: {+ userId,+ provider: "zoom",+ integrationId: "zoom",+ providerAccountId: `zoom-${runId}`,+ email: `organizer-${runId}@zoom.example`,+ displayName: "Zoom",+ credentialId: credential.id,+ },+ });+}++test.describe+ .serial("conferencing integrations", () => {+ let page: Page;+ let userId: string;++ test.beforeAll(async ({ browser }) => {+ page = await browser.newPage();+ const email = `organizer-${runId}@example.com`;+ const user = await createUserInDb({ email, name: "Organizer" });+ userId = user.id;+ await loginWithEmail(page, { email });+ });++ test.afterAll(async () => {+ await prisma.user.delete({ where: { id: userId } });+ });++ test("settings page starts empty and offers the configured providers", async () => {+ await page.goto("/settings/conferencing");+ await expect(+ page.getByRole("heading", { name: "Conferencing" }),+ ).toBeVisible();+ await expect(page.getByText("No accounts connected")).toBeVisible();++ await page.getByRole("button", { name: "Connect account" }).click();+ await expect(page.getByRole("menuitem", { name: "Zoom" })).toBeVisible();+ await page.keyboard.press("Escape");+ });++ test("poll form blocks a provider the organizer has not connected", async () => {+ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();++ await page.getByRole("button", { name: "Add location" }).click();+ await page.getByRole("menuitem", { name: "Zoom" }).click();++ const error = page.locator("#create-poll").getByRole("alert");+ await expect(error).toContainText("Zoom is not connected");+ await expect(+ error.getByRole("link", { name: "Conferencing settings" }),+ ).toHaveAttribute("href", "/settings/conferencing");++ await page.getByRole("button", { name: "Remove" }).click();+ await page.getByRole("button", { name: "Add location" }).click();+ await expect(page.getByRole("menuitem", { name: "Zoom" })).toBeVisible();+ await page.keyboard.press("Escape");+ });++ test("settings page lists a connected account", async () => {+ await seedZoomConnection(userId);+ await page.goto("/settings/conferencing");+ await expect(+ page.getByText(`organizer-${runId}@zoom.example`),+ ).toBeVisible();+ });++ test("poll form accepts a connected provider and stores it", async () => {+ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();++ await page.getByRole("button", { name: "Add location" }).click();+ await page.getByRole("menuitem", { name: "Zoom" }).click();+ await expect(page.locator("#create-poll").getByRole("alert")).toHaveCount(+ 0,+ );++ const pollPage = await newPollPage.create({ name: `Zoom poll ${runId}` });+ await pollPage.closeShareDialog();++ const poll = await prisma.poll.findFirstOrThrow({+ where: { title: `Zoom poll ${runId}` },+ select: { conferencing: true, location: true },+ });+ expect(poll.conferencing).toEqual({ provider: "zoom" });+ expect(poll.location).toBe("Online");+ });++ test("a pasted link needs no account", async () => {+ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();++ await page.getByRole("button", { name: "Add location" }).click();+ await page.getByRole("menuitem", { name: "Custom" }).click();+ await page.getByLabel("Video call").fill("Jitsi");+ await page+ .getByLabel("Link (optional)")+ .fill("https://meet.jit.si/rallly");++ const pollPage = await newPollPage.create({ name: `Link poll ${runId}` });+ await pollPage.closeShareDialog();++ const poll = await prisma.poll.findFirstOrThrow({+ where: { title: `Link poll ${runId}` },+ select: { conferencing: true },+ });+ expect(poll.conferencing).toEqual({+ provider: "custom",+ label: "Jitsi",+ uri: "https://meet.jit.si/rallly",+ });+ });++ test("a named call needs no link", async () => {+ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();++ await page.getByRole("button", { name: "Add location" }).click();+ await page.getByRole("menuitem", { name: "Custom" }).click();+ await page.getByLabel("Video call").fill("Microsoft Teams");++ const pollPage = await newPollPage.create({+ name: `Named poll ${runId}`,+ });+ await pollPage.closeShareDialog();++ const poll = await prisma.poll.findFirstOrThrow({+ where: { title: `Named poll ${runId}` },+ select: { conferencing: true },+ });+ expect(poll.conferencing).toEqual({+ provider: "custom",+ label: "Microsoft Teams",+ });+ });++ test("a pasted link must be a link", async () => {+ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();++ await page.getByRole("button", { name: "Add location" }).click();+ await page.getByRole("menuitem", { name: "Custom" }).click();+ await page.getByLabel("Video call").fill("Jitsi");+ await page.getByLabel("Link (optional)").fill("not a link");+ await page.getByLabel(/title|event/i).fill("Invalid link");+ await page.getByRole("button", { name: /^create poll$/i }).click();+ await expect(+ page.locator("#create-poll").getByRole("alert"),+ ).toContainText("That doesn't look like a link.");+ });++ test("disconnecting removes the account", async () => {+ await page.goto("/settings/conferencing");+ await page.getByRole("button", { name: "More options" }).click();+ await page.getByRole("menuitem", { name: "Disconnect" }).click();+ await expect(page.getByText("No accounts connected")).toBeVisible();+ expect(+ await prisma.conferencingConnection.count({ where: { userId } }),+ ).toBe(0);+ });+ });diff --git a/apps/web/tests/new-poll-page.ts b/apps/web/tests/new-poll-page.tsindex 8d77941ba..8b7f39b47 100644--- a/apps/web/tests/new-poll-page.ts+++ b/apps/web/tests/new-poll-page.ts@@ -19,7 +19,24 @@ export class NewPollPage {const page = this.page;await page.getByLabel(/title|event/i).fill(name);- await page.getByLabel("Location").fill("Online");++ // "Add location" is a menu when the organizer can add a video call and a+ // plain button otherwise; either way the address field appears after.+ // Exact label: the open menu is also named "Add location". A click that+ // lands before React hydrates is dropped, so retry until the field shows.+ const locationField = page.getByLabel("Location", { exact: true });+ await expect(async () => {+ await page+ .getByRole("button", { name: "Add location" })+ .click({ timeout: 2000 });+ const addressItem = page.getByRole("menuitem", { name: "Address" });+ await addressItem.or(locationField).first().waitFor({ timeout: 2000 });+ if (await addressItem.isVisible()) {+ await addressItem.click();+ }+ await expect(locationField).toBeVisible({ timeout: 2000 });+ }).toPass();+ await locationField.fill("Online");// The description is a rich text editor revealed on demand, so open it, then// type into its contenteditable (fill() doesn't work on contenteditable).diff --git a/packages/database/prisma/migrations/20260911150000_add_conferencing_connections/migration.sql b/packages/database/prisma/migrations/20260911150000_add_conferencing_connections/migration.sqlnew file mode 100644index 000000000..4c6dca9ec--- /dev/null+++ b/packages/database/prisma/migrations/20260911150000_add_conferencing_connections/migration.sql@@ -0,0 +1,31 @@+-- Conferencing integrations: a connection per linked Zoom / Google Meet+-- account, and what the organizer asked for on a poll (a provider to mint a+-- link with at finalize, or a link they pasted).++-- AlterTable+ALTER TABLE "polls" ADD COLUMN "conferencing" JSONB;++-- CreateTable+CREATE TABLE "conferencing_connections" (+ "id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "provider" TEXT NOT NULL,+ "integration_id" TEXT NOT NULL,+ "provider_account_id" TEXT NOT NULL,+ "email" TEXT NOT NULL,+ "display_name" TEXT,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,+ "credential_id" TEXT NOT NULL,++ CONSTRAINT "conferencing_connections_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "conferencing_connections_user_id_provider_provider_account_id_key" ON "conferencing_connections"("user_id", "provider", "provider_account_id");++-- AddForeignKey+ALTER TABLE "conferencing_connections" ADD CONSTRAINT "conferencing_connections_credential_id_fkey" FOREIGN KEY ("credential_id") REFERENCES "credentials"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "conferencing_connections" ADD CONSTRAINT "conferencing_connections_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/database/prisma/models/integrations.prisma b/packages/database/prisma/models/integrations.prismaindex a1fe65259..994f70439 100644--- a/packages/database/prisma/models/integrations.prisma+++ b/packages/database/prisma/models/integrations.prisma@@ -15,8 +15,9 @@ model Credential {updatedAt DateTime @updatedAt @map("updated_at")// Relationships- calendarConnections CalendarConnection[]- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ calendarConnections CalendarConnection[]+ conferencingConnections ConferencingConnection[]+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)// Constraints and indexes@@unique([userId, provider, providerAccountId], name: "user_provider_account_unique")@@ -83,3 +84,23 @@ model ProviderCalendar {@@index([lastSyncedAt], name: "sync_time_idx")@@map("provider_calendars")}++model ConferencingConnection {+ id String @id @default(cuid())+ userId String @map("user_id")+ provider String+ integrationId String @map("integration_id")+ providerAccountId String @map("provider_account_id")+ email String+ displayName String? @map("display_name")++ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @updatedAt @map("updated_at")++ credential Credential @relation(fields: [credentialId], references: [id], onDelete: Cascade)+ credentialId String @map("credential_id")+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@unique([userId, provider, providerAccountId], name: "user_provider_account_unique")+ @@map("conferencing_connections")+}diff --git a/packages/database/prisma/models/poll.prisma b/packages/database/prisma/models/poll.prismaindex 47dfb5532..8362efbcc 100644--- a/packages/database/prisma/models/poll.prisma+++ b/packages/database/prisma/models/poll.prisma@@ -37,6 +37,9 @@ model Poll {title Stringdescription String?location String?+ /// What the organizer asked for: a provider to mint a link with at+ /// finalize ("zoom" | "meet"), or a link they pasted themselves.+ conferencing Json?userId String? @map("user_id")timeZone String? @map("time_zone")status PollStatus @default(open)diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex 7a8f62989..fb2c53c7d 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -81,8 +81,9 @@ model User {hostedEventTypes EventType[]hostedSheets Sheet[]- calendarConnections CalendarConnection[]- credentials Credential[]+ calendarConnections CalendarConnection[]+ conferencingConnections ConferencingConnection[]+ credentials Credential[]// Default destination calendar for new eventsdefaultDestinationCalendarId String? @map("default_destination_calendar_id")