Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Finalize polls with a free three-step wizard and a header CTA (#3424)
Luke Vella03d0c3505700
diff --git a/apps/docs/images/workflow/finalize-notify.png b/apps/docs/images/workflow/finalize-notify.pngnew file mode 100644index 000000000..77ebef859Binary files /dev/null and b/apps/docs/images/workflow/finalize-notify.png differdiff --git a/apps/docs/images/workflow/finalize-summary.png b/apps/docs/images/workflow/finalize-summary.pngnew file mode 100644index 000000000..307bf5b89Binary files /dev/null and b/apps/docs/images/workflow/finalize-summary.png differdiff --git a/apps/docs/images/workflow/finalize.png b/apps/docs/images/workflow/finalize.pngindex bf0a8e2c7..24632c137 100644Binary files a/apps/docs/images/workflow/finalize.png and b/apps/docs/images/workflow/finalize.png differdiff --git a/apps/docs/integrations/google-meet.mdx b/apps/docs/integrations/google-meet.mdxindex c3b489f14..b11d07df6 100644--- a/apps/docs/integrations/google-meet.mdx+++ b/apps/docs/integrations/google-meet.mdx@@ -18,7 +18,7 @@ The meeting space belongs to the Google account you connected, so it follows tha- A Google account. A personal Google account or a Google Workspace account both work. On Google Workspace, your administrator must allow Google Meet and let you connect third party apps.- The Google Meet integration must be enabled on the Rallly instance you use. On rallly.co it is available to all accounts; on a self-hosted instance the administrator turns it on.-- Finalizing a poll is a Pro feature on rallly.co. Connecting Google Meet and choosing it for a poll works on every plan; the link is created when the poll is finalized.+- Google Meet works on every plan, on rallly.co and self-hosted alike; the link is created when the poll is finalized.## Adding the appdiff --git a/apps/docs/workflow/schedule.mdx b/apps/docs/workflow/schedule.mdxindex f60842556..a5e7eed7e 100644--- a/apps/docs/workflow/schedule.mdx+++ b/apps/docs/workflow/schedule.mdx@@ -1,30 +1,57 @@---icon: "circle-3"-title: "Schedule"-description: "Pick a final date for your event"+title: "Finalize"+description: "Pick the final date, notify your participants and close the poll"----<Note>Scheduling requires a [Pro subscription](https://rallly.co/pricing) on Rallly Cloud.</Note>+Finalizing is available on every plan. It locks in a date, emails a calendar+invite to the participants you choose and closes the poll to new responses.<Steps>- <Step title="Open the schedule dialog">- Click **Manage** and select **Schedule** from the dropdown menu.+ <Step title="Pick the date">+ Click **Finalize** in the poll header. The dates are listed from most to+ least popular, with the top three marked. Each row shows how many+ participants can make it and a breakdown of their votes. Click a date to+ continue.<Frame>- <img src="/images/workflow/finalize.png" alt="Schedule dialog"/>+ <img src="/images/workflow/finalize.png" alt="Finalize dialog listing the dates by popularity"/></Frame></Step>- <Step title="Pick the final date">- Each option shows how many participants are available and a breakdown of- their votes. Select your preferred date and click **Schedule**.+ <Step title="Choose who to notify">+ Everyone who left an email address is selected. Untick anyone you would+ rather tell yourself, or use the checkbox in the header to select or clear+ everyone at once. Participants without an email address are listed but+ cannot be notified.++ This step is skipped when the poll has no participants yet.++ <Frame>+ <img src="/images/workflow/finalize-notify.png" alt="Notify participants step with the participant list"/>+ </Frame>++ </Step>+ <Step title="Check the summary and finalize">+ The summary shows the date, the location and the video call the event will+ carry. A Zoom, Google Meet or Microsoft Teams link is created at this+ point. Click **Finalize**.++ <Note>+ Zoom and Microsoft Teams links require a [Pro subscription](https://rallly.co/pricing)+ on rallly.co. Google Meet works on every plan.+ </Note>This will:1. Send a calendar invite to you by email.- 2. Send a calendar invite to your participants by email.+ 2. Send a calendar invite to the participants you selected.3. Close the poll to new responses.+ <Frame>+ <img src="/images/workflow/finalize-summary.png" alt="Summary step before finalizing"/>+ </Frame>+The final date is displayed on your poll for everyone to see and can beadded to a calendar with one click.diff --git a/apps/landing/public/locales/en/home.json b/apps/landing/public/locales/en/home.jsonindex 521f6628e..c89fe7701 100644--- a/apps/landing/public/locales/en/home.json+++ b/apps/landing/public/locales/en/home.json@@ -57,7 +57,7 @@"ericJobTitle": "Executive Assistant at MIT","ericQuote": "“If your scheduling workflow lives in emails, I strongly encourage you to try and let Rallly simplify your scheduling tasks for a more organized and less stressful workday.”","faqAfterVoting": "What happens after everyone votes?",- "faqAfterVotingAnswer": "The results show which times work for the most people. With Rallly Pro you can finalize the poll, which notifies participants of the chosen time by email.",+ "faqAfterVotingAnswer": "The results show which times work for the most people. Finalize the poll to lock in the chosen time and notify participants by email with a calendar invite.","faqDoodleDifference": "How is Rallly different from Doodle?","faqDoodleDifferenceAnswer": "Rallly gives you professional, ad-free meeting polls in a clean and easy to use interface. Participants can vote without creating an account, and if you want full control of your data you can even host Rallly on your own server.","faqIsFree": "Is Rallly free?",@@ -279,6 +279,5 @@"when2meetComparisonNoAccount": "Vote without creating an account","when2meetComparisonNotifications": "Email notifications when people respond","when2meetComparisonOpenSource": "Open-source and self-hostable",- "when2meetComparisonTitle": "When2meet vs Rallly",- "when2meetComparisonWithPro": "With Rallly Pro"+ "when2meetComparisonTitle": "When2meet vs Rallly"}diff --git a/apps/landing/public/locales/en/pricing.json b/apps/landing/public/locales/en/pricing.jsonindex 77e0750a5..1a840ed3a 100644--- a/apps/landing/public/locales/en/pricing.json+++ b/apps/landing/public/locales/en/pricing.json@@ -29,8 +29,6 @@"emailInvitesDescription": "Track who opened and responded with personal invite links","faq": "Frequently asked questions","featureNameExtendedPollLifetime": "Extended poll lifetime",- "finalizeDate": "Finalize date",- "finalizeDateDescription": "Select a final date for your event","getPro": "Get Pro","howToUpgrade": "How do I upgrade to a paid plan?","howToUpgradeAnswer": "To upgrade, you can go to your <a>billing settings</a> and click on <b>Upgrade</b>.",diff --git a/apps/landing/src/app/[locale]/(main)/(seo)/best-doodle-alternative/page.tsx b/apps/landing/src/app/[locale]/(main)/(seo)/best-doodle-alternative/page.tsxindex 8bac08db9..6324f67a7 100644--- a/apps/landing/src/app/[locale]/(main)/(seo)/best-doodle-alternative/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/(seo)/best-doodle-alternative/page.tsx@@ -394,7 +394,7 @@ export default async function Page(props: {t={t}ns="home"i18nKey="faqAfterVotingAnswer"- defaults="The results show which times work for the most people. With Rallly Pro you can finalize the poll, which notifies participants of the chosen time by email."+ defaults="The results show which times work for the most people. Finalize the poll to lock in the chosen time and notify participants by email with a calendar invite."/></FaqItem><FaqItemdiff --git a/apps/landing/src/app/[locale]/(main)/(seo)/free-scheduling-poll/page.tsx b/apps/landing/src/app/[locale]/(main)/(seo)/free-scheduling-poll/page.tsxindex 0d7503b41..0e9962920 100644--- a/apps/landing/src/app/[locale]/(main)/(seo)/free-scheduling-poll/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/(seo)/free-scheduling-poll/page.tsx@@ -268,7 +268,7 @@ export default async function Page(props: {t={t}ns="home"i18nKey="faqAfterVotingAnswer"- defaults="The results show which times work for the most people. With Rallly Pro you can finalize the poll, which notifies participants of the chosen time by email."+ defaults="The results show which times work for the most people. Finalize the poll to lock in the chosen time and notify participants by email with a calendar invite."/></FaqItem><FaqItemdiff --git a/apps/landing/src/app/[locale]/(main)/(seo)/when2meet-alternative/page.tsx b/apps/landing/src/app/[locale]/(main)/(seo)/when2meet-alternative/page.tsxindex b2977c5ca..d5dc7db06 100644--- a/apps/landing/src/app/[locale]/(main)/(seo)/when2meet-alternative/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/(seo)/when2meet-alternative/page.tsx@@ -225,12 +225,7 @@ export default async function Page(props: {/></CompareTableFeature><CompareTableCell>- <Trans- t={t}- ns="home"- i18nKey="when2meetComparisonWithPro"- defaults="With Rallly Pro"- />+ <CompareTableCheck label={included} /></CompareTableCell><CompareTableCell><CompareTableDash label={notIncluded} />@@ -449,7 +444,7 @@ export default async function Page(props: {t={t}ns="home"i18nKey="faqAfterVotingAnswer"- defaults="The results show which times work for the most people. With Rallly Pro you can finalize the poll, which notifies participants of the chosen time by email."+ defaults="The results show which times work for the most people. Finalize the poll to lock in the chosen time and notify participants by email with a calendar invite."/></FaqItem><FaqItemdiff --git a/apps/landing/src/app/[locale]/(main)/page.tsx b/apps/landing/src/app/[locale]/(main)/page.tsxindex a3043934a..88be8668a 100644--- a/apps/landing/src/app/[locale]/(main)/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/page.tsx@@ -176,7 +176,7 @@ export default async function Page(props: {t={t}ns="home"i18nKey="faqAfterVotingAnswer"- defaults="The results show which times work for the most people. With Rallly Pro you can finalize the poll, which notifies participants of the chosen time by email."+ defaults="The results show which times work for the most people. Finalize the poll to lock in the chosen time and notify participants by email with a calendar invite."/></FaqItem><FaqItemdiff --git a/apps/landing/src/app/[locale]/(main)/pricing/page.tsx b/apps/landing/src/app/[locale]/(main)/pricing/page.tsxindex 0c3979d44..0d415227a 100644--- a/apps/landing/src/app/[locale]/(main)/pricing/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/pricing/page.tsx@@ -5,7 +5,6 @@ import { PLAN_NAMES, yearlySavingsPercent } from "@rallly/billing";import { buttonVariants } from "@rallly/ui";import { Badge } from "@rallly/ui/badge";import {- CalendarCheckIcon,CalendarSearchIcon,ClockIcon,CopyIcon,@@ -337,16 +336,6 @@ export default async function Page(props: {/></PlanBenefitName></PlanBenefit>- <PlanBenefit icon={<CalendarCheckIcon />}>- <PlanBenefitName>- <Trans- t={t}- ns="pricing"- i18nKey="finalizeDate"- defaults="Finalize date"- />- </PlanBenefitName>- </PlanBenefit><PlanBenefit icon={<ClockIcon />}><PlanBenefitName><Trans@@ -561,32 +550,6 @@ export default async function Page(props: {/></CompareTableCell></tr>- <tr>- <CompareTableFeature>- <CompareTableFeatureName>- <Trans- t={t}- ns="pricing"- i18nKey="finalizeDate"- defaults="Finalize date"- />- </CompareTableFeatureName>- <CompareTableFeatureDescription>- <Trans- t={t}- ns="pricing"- i18nKey="finalizeDateDescription"- defaults="Select a final date for your event"- />- </CompareTableFeatureDescription>- </CompareTableFeature>- <CompareTableCell>- <CompareTableDash label={notIncluded} />- </CompareTableCell>- <CompareTableCell>- <CompareTableCheck label={included} />- </CompareTableCell>- </tr><tr><CompareTableFeature><CompareTableFeatureName>diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 889eea663..e1b543a22 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -380,10 +380,20 @@"exportToCsv": "Export to CSV","extendedPollLifetimeDescription": "Keep polls indefinitely","featureNameExtendedPollLifetime": "Extended poll lifetime",- "featureNameSchedule": "Schedule poll","feedback": "Feedback","feedbackDialogEnterFeedback": "Enter your feedback","fileTooLarge": "File too large",+ "finalize": "Finalize",+ "finalizeAndNotify": "{count, plural, =0 {Finalize} one {Finalize and notify # participant} other {Finalize and notify # participants}}",+ "finalizePoll": "Finalize poll",+ "finalizePollDescription": "Pick the date that works best.",+ "finalizePollError": "Failed to finalize poll",+ "finalizeSuccessDate": "Your event is booked for <date></date>.",+ "finalizeSuccessNotified": "{count, plural, =0 {No participants were notified.} one {# participant has been notified.} other {# participants have been notified.}}",+ "finalizeSuccessTitle": "Date scheduled",+ "finalizeSummaryDescription": "Check the details before you finalize.",+ "finalizeSummaryTitle": "Summary",+ "finalizeViewMoreOptions": "{count, plural, one {View # more option} other {View # more options}}","footerLinkAdd": "Add link","footerLinkLabel": "Label","footerLinkLabelPlaceholder": "Privacy policy",@@ -606,7 +616,8 @@"newParticipantFormSubmitError": "Your response could not be saved. Please check your connection and try again.","newPassword": "New password","newPoll": "New poll",- "nextMonth": "Next month",+ "next": "Next",+ "nextMonth": "Go to the next month","nextWeek": "Next week","no": "No","noApiKeys": "No API keys found",@@ -618,6 +629,7 @@"noDatesSelected": "No dates selected","noDatesSelectedDescription": "Click on a date to add a time slot","noDeliveriesYet": "No deliveries yet",+ "noEmail": "No email","noKeepCurrentTimezone": "No, keep the current time zone","noLicenseKey": "No license key found","noLicenseKeyDescription": "This instance doesn’t have a license key yet.",@@ -643,6 +655,9 @@"notifyNewCommentDescription": "Receive an email when someone comments on your poll.","notifyNewResponse": "New response","notifyNewResponseDescription": "Receive an email when a participant submits a response.",+ "notifyParticipants": "Notify participants",+ "notifyParticipantsDescription": "Email the final date and a calendar invite to the people you select.",+ "notifySelectedCount": "{count, plural, =0 {Select all} one {# selected} other {# selected}}","noTimes": "No times to vote on","noTimesShort": "None","noUsers": "No users found",@@ -807,7 +822,6 @@"pollResponsesListEmptyDescription": "Responses will show up here once participants vote.","pollResponsesListNote": "Note","polls": "Polls",- "pollScheduled": "Poll scheduled","pollsListActions": "Actions","pollsListDates": "Dates","pollsListOrganizer": "Organizer",@@ -821,7 +835,7 @@"preferences": "Preferences","preferencesDescription": "Manage your preferences","preview": "Preview",- "previousMonth": "Previous month",+ "previousMonth": "Go to the previous month","previousWeek": "Previous week","priceFree": "Free","primaryColor": "Primary color",@@ -909,10 +923,6 @@"saving": "Saving...","scheduledPollLockedDescription": "A scheduled poll can no longer be edited.","scheduledPollLockedTitle": "This poll is scheduled",- "schedulePoll": "Schedule",- "schedulePollDescription": "Select a final date for your event.",- "schedulePollError": "Failed to schedule poll",- "schedulingPoll": "Scheduling...","scrollLeft": "Scroll left","scrollRight": "Scroll right","searchEventsPlaceholder": "Search events by title...",diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/polls/[pollId]/layout.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/polls/[pollId]/layout.tsxindex 9ceeb373e..3cae203fb 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/polls/[pollId]/layout.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/polls/[pollId]/layout.tsx@@ -16,7 +16,7 @@ import {import { PollProvider } from "@/features/poll/client";import { PollAdminMenu } from "@/features/poll/components/poll-admin-menu";import { LegacyPollContextProvider } from "@/features/poll/components/poll-context-provider";-import { ShareDialog } from "@/features/poll/components/share-dialog";+import { PollPrimaryActions } from "@/features/poll/components/poll-primary-actions";import { loadAdminPoll, loadPoll } from "@/features/poll/loaders";import { Trans } from "@/i18n/client";import { isFeatureEnabled } from "@/lib/feature-flags/server";@@ -40,7 +40,7 @@ async function PollHeaderActions({}) {const { pollId } = await params;await loadPoll(pollId);- // The schedule dialog and CSV export read the whole poll, votes included,+ // The finalize dialog and CSV export read the whole poll, votes included,// from the poll context the legacy admin page provides.const { poll, participants, comments } = await loadAdminPoll(pollId);return (@@ -52,11 +52,7 @@ async function PollHeaderActions({><LegacyPollContextProvider><PollAdminMenu />- <ShareDialog- pollId={poll.id}- pollStatus={poll.status}- inviteLink={poll.inviteLink}- />+ <PollPrimaryActions /></LegacyPollContextProvider></PollProvider>);diff --git a/apps/web/src/components/data-list.tsx b/apps/web/src/components/data-list.tsxindex 4b4a83a2f..68dfab072 100644--- a/apps/web/src/components/data-list.tsx+++ b/apps/web/src/components/data-list.tsx@@ -14,7 +14,47 @@ declare module "@tanstack/react-table" {type DataListGroup = { id: string; label: React.ReactNode };-function DataListRow<TData>({+/**+ * The grid every row lines up on. `className` sets `grid-cols-*` once and+ * each row is a subgrid of it, so cells align down the list.+ */+export function DataListRoot({+ className,+ ...props+}: React.ComponentProps<"ul">) {+ return <ul className={cn("grid gap-x-5 px-4 py-2", className)} {...props} />;+}++/**+ * One row of the grid. To make a whole row clickable, render a link or+ * button in one cell with an `after:absolute after:inset-0` overlay and give+ * other interactive cells `relative z-10` so they sit above it.+ */+export function DataListRow({+ className,+ ...props+}: React.ComponentProps<"li">) {+ return (+ <li+ className={cn(+ "relative col-span-full grid h-12 grid-cols-subgrid items-center rounded-lg pr-3 pl-4 hover:bg-accent/60 has-[:is(a,button):focus-visible]:bg-accent/60 has-[a[aria-current=page]]:bg-accent",+ className,+ )}+ {...props}+ />+ );+}++export function DataListCell({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div className={cn("flex min-w-0 items-center", className)} {...props} />+ );+}++function DataListTableRow<TData>({row,className,}: {@@ -22,41 +62,27 @@ function DataListRow<TData>({className?: string;}) {return (- <li- className={cn(- "relative col-span-full grid h-12 grid-cols-subgrid items-center rounded-lg pr-3 pl-4 hover:bg-accent/60 has-[a:focus-visible]:bg-accent/60 has-[a[aria-current=page]]:bg-accent",- className,- )}- >+ <DataListRow className={className}>{row.getVisibleCells().map((cell) => (- <div+ <DataListCellkey={cell.id}- className={cn(- "flex min-w-0 items-center",- cell.column.columnDef.meta?.className,- )}+ className={cell.column.columnDef.meta?.className}>{flexRender(cell.column.columnDef.cell, cell.getContext())}- </div>+ </DataListCell>))}- </li>+ </DataListRow>);}/**- * Renders a TanStack table as a list laid out on a CSS grid. Rows are- * subgrids of the root, so `className` sets `grid-cols-*` once and every- * row's columns line up. A cell hidden with `display: none` gives up its- * track, so the template must list only the columns visible at each- * breakpoint.+ * Renders a TanStack table on the DataList grid. A cell hidden with+ * `display: none` gives up its track, so the template must list only the+ * columns visible at each breakpoint.** `getGroup` splits the rows into labelled groups. Rows are grouped where* they are adjacent, so sort them by group first.*- * To make a whole row clickable, render a link in one cell with an- * `after:absolute after:inset-0` overlay and give other interactive cells- * `relative z-10` so they sit above it.- ** `getRowClassName` styles a row from its data, e.g. to tint it by state.*/export function DataList<TData>({@@ -77,15 +103,15 @@ export function DataList<TData>({if (!getGroup) {return (- <ul className={cn("grid gap-x-5 px-4 py-2", rowGapClassName, className)}>+ <DataListRoot className={cn(rowGapClassName, className)}>{rows.map((row) => (- <DataListRow+ <DataListTableRowkey={row.id}row={row}className={getRowClassName?.(row.original)}/>))}- </ul>+ </DataListRoot>);}@@ -101,7 +127,7 @@ export function DataList<TData>({}return (- <ul className={cn("grid gap-x-5 px-4 py-2", className)}>+ <DataListRoot className={className}>{groups.map(({ group, rows }) => (<likey={group.id}@@ -117,7 +143,7 @@ export function DataList<TData>({)}>{rows.map((row) => (- <DataListRow+ <DataListTableRowkey={row.id}row={row}className={getRowClassName?.(row.original)}@@ -126,6 +152,6 @@ export function DataList<TData>({</ul></li>))}- </ul>+ </DataListRoot>);}diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsxindex 3a14f5094..e994664c1 100644--- a/apps/web/src/features/billing/client.tsx+++ b/apps/web/src/features/billing/client.tsx@@ -47,30 +47,46 @@ export type PayWallTrigger = {| "billing-settings"| "sidebar"| "invite-dialog"+ | "finalize-dialog"| "poll-footer";setting?: string;action?: string;pollId?: string;};+export type PayWallPricing = {+ prices: PricesByCurrency;+ defaultCurrency: string;+};+type PayWallStore = {isOpen: boolean;trigger: PayWallTrigger | null;+ /** Loaded once by the app-wide instance; nested instances read it here. */+ pricing: PayWallPricing | null;+ /** Records the trigger without opening the app-wide dialog, for a pay+ * wall a dialog nests inside itself. */+ prime: (trigger: PayWallTrigger) => void;show: (trigger: PayWallTrigger) => void;hide: () => void;};-export const usePayWallStore = create<PayWallStore>((set) => ({+export const usePayWallStore = create<PayWallStore>((set, get) => ({isOpen: false,trigger: null,- show: (trigger) => {+ pricing: null,+ prime: (trigger) => {posthog?.capture("trigger paywall", {from: trigger.from,setting: trigger.setting,action: trigger.action,poll_id: trigger.pollId,});- set({ isOpen: true, trigger });+ set({ trigger });+ },+ show: (trigger) => {+ get().prime(trigger);+ set({ isOpen: true });},hide: () => set({ isOpen: false }),}));@@ -78,10 +94,8 @@ export const usePayWallStore = create<PayWallStore>((set) => ({export const showPayWall = (trigger: PayWallTrigger) =>usePayWallStore.getState().show(trigger);-export type PayWallPricing = {- prices: PricesByCurrency;- defaultCurrency: string;-};+export const primePayWall = (trigger: PayWallTrigger) =>+ usePayWallStore.getState().prime(trigger);// Same cookie the pricing page writes, so a currency picked in either place// is what the other opens in. Shared across subdomains via the cookie domain.diff --git a/apps/web/src/features/billing/components/pay-wall-dialog.tsx b/apps/web/src/features/billing/components/pay-wall-dialog.tsxindex cde1ef221..8574e0375 100644--- a/apps/web/src/features/billing/components/pay-wall-dialog.tsx+++ b/apps/web/src/features/billing/components/pay-wall-dialog.tsx@@ -23,7 +23,6 @@ import { Switch } from "@rallly/ui/switch";import { Tabs, TabsContent } from "@rallly/ui/tabs";import {BadgePercentIcon,- CalendarCheckIcon,CalendarSearchIcon,ClockIcon,EyeOffIcon,@@ -145,17 +144,6 @@ const proBenefitsList = [/>),},- {- key: "schedulePoll",- icon: <CalendarCheckIcon />,- title: <Trans i18nKey="featureNameSchedule" defaults="Schedule poll" />,- description: (- <Trans- i18nKey="schedulePollDescription"- defaults="Select a final date for your event."- />- ),- },{key: "extendedPollLifetime",icon: <ClockIcon />,diff --git a/apps/web/src/features/billing/components/pay-wall.tsx b/apps/web/src/features/billing/components/pay-wall.tsxindex 6706bba3b..c61def77a 100644--- a/apps/web/src/features/billing/components/pay-wall.tsx+++ b/apps/web/src/features/billing/components/pay-wall.tsx@@ -1,5 +1,6 @@"use client";+import React from "react";import type { PayWallPricing } from "../client";import { usePayWallStore } from "../client";import { PayWallDialog } from "./pay-wall-dialog";@@ -12,6 +13,10 @@ export function PayWall({ pricing }: { pricing: PayWallPricing | null }) {const isOpen = usePayWallStore((state) => state.isOpen);const hide = usePayWallStore((state) => state.hide);+ React.useEffect(() => {+ usePayWallStore.setState({ pricing });+ }, [pricing]);+return (<PayWallDialogpricing={pricing}diff --git a/apps/web/src/features/poll/components/finalize-poll-dialog.tsx b/apps/web/src/features/poll/components/finalize-poll-dialog.tsxnew file mode 100644index 000000000..b066207ea--- /dev/null+++ b/apps/web/src/features/poll/components/finalize-poll-dialog.tsx@@ -0,0 +1,603 @@+"use client";++import { cn } from "@rallly/ui";+import { Button } from "@rallly/ui/button";+import { Checkbox } from "@rallly/ui/checkbox";+import type { DialogProps } from "@rallly/ui/dialog";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import { Label } from "@rallly/ui/label";+import { toast } from "@rallly/ui/sonner";+import { SuccessCheck, SuccessCheckIcon } from "@rallly/ui/success-check";+import { CalendarIcon, MapPinIcon, StarIcon, VideoIcon } from "lucide-react";+import { useRouter } from "next/navigation";+import React from "react";+import {+ DataListCell,+ DataListRoot,+ DataListRow,+} from "@/components/data-list";+import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";+import { primePayWall, usePayWallStore } from "@/features/billing/client";+import { PayWallDialog } from "@/features/billing/components/pay-wall-dialog";+import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";+import { conferencingProviderLabels } from "@/features/conferencing/utils";+import { useParticipants, usePoll } from "@/features/poll/client";+import { ConnectedScoreSummary } from "@/features/poll/components/score-summary";+import { VoteSummaryProgressBar } from "@/features/poll/components/vote-summary-progress-bar";+import type { PollParticipant } from "@/features/poll/types";+import type { OptionVotes } from "@/features/poll/utils";+import { rankOptionsByPopularity } from "@/features/poll/utils";+import {+ EventDate,+ EventTimeRange,+} from "@/features/scheduled-event/components/event-date-time";+import { Trans } from "@/i18n/client";+import { trpc } from "@/trpc/client";++type RankedOption = {+ id: string;+ startTime: Date;+ duration: number;+ votes: OptionVotes;+};++function OptionCell({+ option,+ onPick,+}: {+ option: RankedOption;+ onPick: () => void;+}) {+ const poll = usePoll();+ return (+ // The button is the row's click target; the overlay makes the whole row+ // pick the option.+ <button+ type="button"+ onClick={onPick}+ className="block min-w-0 truncate text-left text-sm after:absolute after:inset-0 after:rounded-lg focus-visible:outline-none"+ >+ <EventDate+ value={option.startTime}+ allDay={option.duration === 0}+ timeZone={poll.timeZone}+ preset="dateFull"+ />+ </button>+ );+}++function OptionTimeCell({ option }: { option: RankedOption }) {+ const poll = usePoll();+ const allDay = option.duration === 0;+ return (+ <span className="whitespace-nowrap text-muted-foreground text-sm">+ <EventTimeRange+ start={option.startTime}+ end={new Date(option.startTime.getTime() + option.duration * 60_000)}+ allDay={allDay}+ timeZone={poll.timeZone}+ />+ </span>+ );+}++function OptionVotesCell({ votes }: { votes: OptionVotes }) {+ const poll = usePoll();+ const { participants } = useParticipants();+ return (+ <div className="relative z-10 flex w-32">+ <VoteSummaryProgressBar+ {...votes}+ total={participants.length}+ showTentative={poll.allowTentativeVotes}+ />+ </div>+ );+}++const TOP_OPTIONS = 5;++const medalClassName: Record<number, string> = {+ 1: "bg-amber-400",+ 2: "bg-zinc-400",+ 3: "bg-amber-700",+};++function RankMedal({ rank }: { rank: number }) {+ const className = medalClassName[rank];+ return (+ <span+ className={cn(+ "flex size-4 items-center justify-center rounded-full text-white",+ className,+ )}+ >+ {className ? (+ <StarIcon aria-hidden className="size-2.5" fill="currentColor" />+ ) : null}+ <span className="sr-only">#{rank}</span>+ </span>+ );+}++function PickDateStep({+ options,+ onPick,+}: {+ options: RankedOption[];+ onPick: (optionId: string) => void;+}) {+ const [showAll, setShowAll] = React.useState(false);+ const visible = showAll ? options : options.slice(0, TOP_OPTIONS);+ // A date poll has no times to show.+ const hasTimes = options.some((option) => option.duration > 0);++ return (+ <div className="-mx-4 max-h-96 overflow-y-auto">+ <DataListRoot+ className={+ hasTimes+ ? "grid-cols-[auto_minmax(0,1fr)_auto_auto] sm:grid-cols-[auto_minmax(0,1fr)_auto_auto_auto]"+ : "grid-cols-[auto_minmax(0,1fr)_auto] sm:grid-cols-[auto_minmax(0,1fr)_auto_auto]"+ }+ >+ {visible.map((option, index) => (+ <DataListRow key={option.id}>+ <DataListCell>+ <RankMedal rank={index + 1} />+ </DataListCell>+ <DataListCell>+ <OptionCell option={option} onPick={() => onPick(option.id)} />+ </DataListCell>+ {hasTimes ? (+ <DataListCell>+ <OptionTimeCell option={option} />+ </DataListCell>+ ) : null}+ <DataListCell className="hidden sm:flex">+ <OptionVotesCell votes={option.votes} />+ </DataListCell>+ <DataListCell>+ <div className="relative z-10">+ <ConnectedScoreSummary optionId={option.id} />+ </div>+ </DataListCell>+ </DataListRow>+ ))}+ </DataListRoot>+ {options.length > TOP_OPTIONS && !showAll ? (+ <div className="px-4 pb-2">+ <Button+ variant="ghost"+ className="w-full"+ onClick={() => setShowAll(true)}+ >+ <Trans+ i18nKey="finalizeViewMoreOptions"+ defaults="{count, plural, one {View # more option} other {View # more options}}"+ values={{ count: options.length - TOP_OPTIONS }}+ />+ </Button>+ </div>+ ) : null}+ </div>+ );+}++function PickedDate({ option }: { option: RankedOption }) {+ const poll = usePoll();+ const allDay = option.duration === 0;+ return (+ <div className="flex items-start gap-3">+ {/* The icon centers on the first line, not the block. */}+ <CalendarIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0">+ <div className="truncate text-sm leading-5">+ <EventDate+ value={option.startTime}+ allDay={allDay}+ timeZone={poll.timeZone}+ preset="dateFull"+ />+ </div>+ <div className="truncate text-muted-foreground text-sm">+ <EventTimeRange+ start={option.startTime}+ end={+ new Date(option.startTime.getTime() + option.duration * 60_000)+ }+ allDay={allDay}+ timeZone={poll.timeZone}+ />+ </div>+ </div>+ </div>+ );+}++function ParticipantCell({ participant }: { participant: PollParticipant }) {+ return (+ <Label+ htmlFor={`notify-${participant.id}`}+ className="flex min-w-0 items-center gap-3 after:absolute after:inset-0 after:rounded-lg"+ >+ <OptimizedAvatarImage+ size="sm"+ name={participant.name}+ src={participant.image ?? undefined}+ className="shrink-0"+ />+ <span className="truncate text-sm">{participant.name}</span>+ </Label>+ );+}++function NotifyStep({+ selectedIds,+ onChange,+}: {+ selectedIds: Set<string>;+ onChange: (next: Set<string>) => void;+}) {+ const { participants } = useParticipants();+ const notifiableIds = React.useMemo(+ () => participants.filter((p) => p.email).map((p) => p.id),+ [participants],+ );+ const allSelected =+ notifiableIds.length > 0 &&+ notifiableIds.every((id) => selectedIds.has(id));+ const someSelected = notifiableIds.some((id) => selectedIds.has(id));++ return (+ <div className="overflow-hidden rounded-xl border">+ <div className="flex h-12 items-center gap-3 border-b bg-muted/40 pr-5 pl-6">+ <Checkbox+ id="notify-all"+ checked={allSelected}+ indeterminate={!allSelected && someSelected}+ disabled={notifiableIds.length === 0}+ onCheckedChange={(checked) =>+ onChange(new Set(checked ? notifiableIds : []))+ }+ />+ <Label htmlFor="notify-all" className="text-sm">+ <Trans+ i18nKey="notifySelectedCount"+ defaults="{count, plural, =0 {Select all} one {# selected} other {# selected}}"+ values={{+ count: notifiableIds.filter((id) => selectedIds.has(id)).length,+ }}+ />+ </Label>+ </div>+ <DataListRoot className="max-h-72 grid-cols-[auto_minmax(0,1fr)_minmax(0,1fr)] overflow-y-auto px-2">+ {participants.map((participant) => (+ <DataListRow key={participant.id}>+ <DataListCell>+ <Checkbox+ id={`notify-${participant.id}`}+ className="relative z-10"+ checked={selectedIds.has(participant.id)}+ disabled={!participant.email}+ onCheckedChange={(checked) => {+ const next = new Set(selectedIds);+ if (checked) {+ next.add(participant.id);+ } else {+ next.delete(participant.id);+ }+ onChange(next);+ }}+ />+ </DataListCell>+ <DataListCell>+ <ParticipantCell participant={participant} />+ </DataListCell>+ <DataListCell>+ <span className="truncate text-muted-foreground text-sm">+ {participant.email ?? (+ <Trans i18nKey="noEmail" defaults="No email" />+ )}+ </span>+ </DataListCell>+ </DataListRow>+ ))}+ </DataListRoot>+ </div>+ );+}++type Step = "date" | "notify" | "summary" | "done";++// Each step sets its own width and the dialog eases between them. The wide+// steps match a 2xl dialog's content box; the success step is narrower.+const wideStepClassName = "grid w-[calc(100vw-4rem)] gap-4 sm:w-[40rem]";+const narrowStepClassName = "grid w-[calc(100vw-4rem)] gap-4 sm:w-[26rem]";++function PickedDateText({ option }: { option: RankedOption }) {+ const poll = usePoll();+ const allDay = option.duration === 0;+ return (+ <>+ <EventDate+ value={option.startTime}+ allDay={allDay}+ timeZone={poll.timeZone}+ preset="dateFull"+ />+ {allDay ? null : (+ <>+ {", "}+ <EventTimeRange+ start={option.startTime}+ end={+ new Date(option.startTime.getTime() + option.duration * 60_000)+ }+ allDay={allDay}+ timeZone={poll.timeZone}+ />+ </>+ )}+ </>+ );+}++function DetailRow({+ icon,+ children,+}: {+ icon: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <div className="flex min-w-0 items-start gap-3">+ <span className="mt-0.5 flex size-4 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4">+ {icon}+ </span>+ <div className="min-w-0 break-words text-sm leading-5">{children}</div>+ </div>+ );+}++// What the event will carry, laid out as the confirmation email shows it.+function SummaryStep({ option }: { option: RankedOption }) {+ const poll = usePoll();+ const conferencing = poll.conferencing;+ return (+ <div className="grid min-w-0 grid-cols-[minmax(0,1fr)] gap-4">+ <PickedDate option={option} />+ {poll.location ? (+ <DetailRow icon={<MapPinIcon />}>{poll.location}</DetailRow>+ ) : null}+ {conferencing ? (+ <DetailRow+ icon={+ conferencing.provider === "custom" ? (+ <VideoIcon />+ ) : (+ <ConferencingProviderIcon+ provider={conferencing.provider}+ size={16}+ />+ )+ }+ >+ <div>+ {conferencing.provider === "custom"+ ? conferencing.label+ : conferencingProviderLabels[conferencing.provider]}+ </div>+ {conferencing.provider === "custom" && conferencing.uri ? (+ <div className="break-all text-muted-foreground">+ <a+ href={conferencing.uri}+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ {conferencing.uri}+ </a>+ </div>+ ) : null}+ </DetailRow>+ ) : null}+ </div>+ );+}++// Mounted fresh with each open, so the wizard starts at step one with+// nothing carried over from a previous run.+function FinalizeWizard({ onClose }: { onClose: () => void }) {+ const poll = usePoll();+ const { participants } = useParticipants();+ const router = useRouter();+ // The pay wall nests inside the wizard so it stacks above it and the+ // wizard survives it; the app-wide instance would sit underneath.+ const payWall = useDialog();+ const payWallPricing = usePayWallStore((state) => state.pricing);+ const openPayWall = (action: string) => {+ primePayWall({ from: "finalize-dialog", action, pollId: poll.id });+ payWall.trigger();+ };+ const options = React.useMemo(+ () => rankOptionsByPopularity({ options: poll.options, participants }),+ [poll.options, participants],+ );+ const [step, setStep] = React.useState<Step>("date");+ const [optionId, setOptionId] = React.useState<string | null>(null);+ const [notifyIds, setNotifyIds] = React.useState(+ () => new Set(participants.filter((p) => p.email).map((p) => p.id)),+ );+ const option = options.find((o) => o.id === optionId);++ const finalize = trpc.polls.book.useMutation({+ onSuccess: () => {+ setStep("done");+ // The page behind the dialog picks up the scheduled status.+ router.refresh();+ },+ onError: (error) => {+ if (error.data?.code === "PAYMENT_REQUIRED") {+ openPayWall("finalize");+ return;+ }+ toast.error(+ <Trans+ i18nKey="finalizePollError"+ defaults="Failed to finalize poll"+ />,+ );+ },+ });++ if (step === "date" || !option) {+ return (+ <div className={wideStepClassName}>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="finalizePoll" defaults="Finalize poll" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="finalizePollDescription"+ defaults="Pick the date that works best."+ />+ </DialogDescription>+ </DialogHeader>+ <PickDateStep+ options={options}+ onPick={(id) => {+ setOptionId(id);+ // With nobody to notify, the notify step has nothing to ask.+ setStep(participants.length > 0 ? "notify" : "summary");+ }}+ />+ </div>+ );+ }++ if (step === "done") {+ return (+ <div className={narrowStepClassName}>+ <div className="flex flex-col items-center gap-4 py-4 text-center">+ <SuccessCheck state="in">+ <SuccessCheckIcon />+ </SuccessCheck>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="finalizeSuccessTitle" defaults="Date scheduled" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="finalizeSuccessDate"+ defaults="Your event is booked for <date></date>."+ components={{ date: <PickedDateText option={option} /> }}+ />{" "}+ <Trans+ i18nKey="finalizeSuccessNotified"+ defaults="{count, plural, =0 {No participants were notified.} one {# participant has been notified.} other {# participants have been notified.}}"+ values={{ count: notifyIds.size }}+ />+ </DialogDescription>+ </DialogHeader>+ </div>+ <Button className="w-full" onClick={onClose}>+ <Trans i18nKey="backToPoll" defaults="Back to poll" />+ </Button>+ </div>+ );+ }++ if (step === "summary") {+ return (+ <div className={narrowStepClassName}>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="finalizeSummaryTitle" defaults="Summary" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="finalizeSummaryDescription"+ defaults="Check the details before you finalize."+ />+ </DialogDescription>+ </DialogHeader>+ <SummaryStep option={option} />+ <PayWallDialog+ pricing={payWallPricing}+ isOpen={payWall.dialogProps.open}+ onOpenChange={payWall.dialogProps.onOpenChange}+ />+ <DialogFooter>+ <Button+ onClick={() => setStep(participants.length > 0 ? "notify" : "date")}+ >+ <Trans i18nKey="back" defaults="Back" />+ </Button>+ <Button+ variant="primary"+ loading={finalize.isPending}+ onClick={() => {+ finalize.mutate({+ pollId: poll.id,+ optionId: option.id,+ notifyParticipantIds: Array.from(notifyIds),+ });+ }}+ >+ <Trans+ i18nKey="finalizeAndNotify"+ defaults="{count, plural, =0 {Finalize} one {Finalize and notify # participant} other {Finalize and notify # participants}}"+ values={{ count: notifyIds.size }}+ />+ </Button>+ </DialogFooter>+ </div>+ );+ }++ return (+ <div className={wideStepClassName}>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="notifyParticipants" defaults="Notify participants" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="notifyParticipantsDescription"+ defaults="Email the final date and a calendar invite to the people you select."+ />+ </DialogDescription>+ </DialogHeader>+ <NotifyStep selectedIds={notifyIds} onChange={setNotifyIds} />+ <DialogFooter>+ <Button onClick={() => setStep("date")}>+ <Trans i18nKey="back" defaults="Back" />+ </Button>+ <Button variant="primary" onClick={() => setStep("summary")}>+ <Trans i18nKey="next" defaults="Next" />+ </Button>+ </DialogFooter>+ </div>+ );+}++export function FinalizePollDialog(props: DialogProps) {+ return (+ <Dialog {...props}>+ <DialogContent className="w-auto sm:max-w-none">+ <FinalizeWizard onClose={() => props.onOpenChange?.(false)} />+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/features/poll/components/manage-poll.tsx b/apps/web/src/features/poll/components/manage-poll.tsxindex cfdd3b053..f3e8af220 100644--- a/apps/web/src/features/poll/components/manage-poll.tsx+++ b/apps/web/src/features/poll/components/manage-poll.tsx@@ -8,7 +8,6 @@ import {DropdownMenuTrigger,} from "@rallly/ui/dropdown-menu";import {- CalendarCheck2Icon,ChevronDownIcon,CircleStopIcon,CopyIcon,@@ -24,7 +23,6 @@ import { showPayWall, useIsFree } from "@/features/billing/client";import { ProBadge } from "@/features/billing/components/pro-badge";import { usePoll } from "@/features/poll/client";import { DuplicateDialog } from "@/features/poll/components/duplicate-dialog";-import { SchedulePollDialog } from "@/features/poll/components/manage-poll/schedule-poll-dialog";import { Trans } from "@/i18n/client";import { trpc } from "@/trpc/client";import { DeletePollDialog } from "./manage-poll/delete-poll-dialog";@@ -74,7 +72,6 @@ const ManagePoll: React.FunctionComponent<{const [showDeletePollDialog, setShowDeletePollDialog] = React.useState(false);const duplicateDialog = useDialog();- const scheduleDialog = useDialog();const isFree = useIsFree();const { exportToCsv } = useCsvExporter();// Edits made after booking would never reach the booked event.@@ -107,24 +104,6 @@ const ManagePoll: React.FunctionComponent<{) : null}{canChangeStatus ? (<>- <DropdownMenuItem- disabled={!!poll.event}- onClick={() => {- if (isFree) {- showPayWall({- from: "manage-poll",- action: "schedule",- pollId: poll.id,- });- } else {- scheduleDialog.trigger();- }- }}- >- <CalendarCheck2Icon />- <Trans i18nKey="schedulePoll" defaults="Schedule" />- {isFree ? <ProBadge /> : null}- </DropdownMenuItem><OpenCloseToggle /><DropdownMenuSeparator /></>@@ -172,7 +151,6 @@ const ManagePoll: React.FunctionComponent<{pollTitle={poll.title}{...duplicateDialog.dialogProps}/>- <SchedulePollDialog {...scheduleDialog.dialogProps} /></>);};diff --git a/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx b/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsxdeleted file mode 100644index f30449be2..000000000--- a/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx+++ /dev/null@@ -1,283 +0,0 @@-import { zodResolver } from "@hookform/resolvers/zod";-import { cn } from "@rallly/ui";-import { Button } from "@rallly/ui/button";-import type { DialogProps } from "@rallly/ui/dialog";-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@rallly/ui/dialog";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,-} from "@rallly/ui/form";-import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";-import { toast } from "@rallly/ui/sonner";-import { useRouter } from "next/navigation";-import React from "react";-import { useForm } from "react-hook-form";-import * as z from "zod";-import { DateIconInner } from "@/components/date-icon";-import { useParticipants, usePoll } from "@/features/poll/client";-import { ConnectedScoreSummary } from "@/features/poll/components/score-summary";-import { VoteSummaryProgressBar } from "@/features/poll/components/vote-summary-progress-bar";-import {- EventDate,- EventTimeRange,-} from "@/features/scheduled-event/components/event-date-time";-import { Trans } from "@/i18n/client";-import { useDateTimeConfig } from "@/lib/datetime/client";-import { formatDateParts } from "@/lib/datetime/format";-import { trpc } from "@/trpc/client";--const formSchema = z.object({- selectedOptionId: z.string(),- notify: z.enum(["none", "all", "attendees"]),-});--type ScheduleFormData = z.infer<typeof formSchema>;--type OptionScore = {- yes: string[];- ifNeedBe: string[];- no: string[];-};--const useScoreByOptionId = () => {- const { participants: responses } = useParticipants();- const { options } = usePoll();-- return React.useMemo(() => {- const scoreByOptionId: Record<string, OptionScore> = {};- options.forEach((option) => {- scoreByOptionId[option.id] = {- yes: [],- ifNeedBe: [],- no: [],- };- });-- responses?.forEach((response) => {- response.votes.forEach((vote) => {- scoreByOptionId[vote.optionId]?.[vote.type].push(response.id);- });- });-- return scoreByOptionId;- }, [responses, options]);-};--function DateIcon({ start }: { start: Date }) {- const poll = usePoll();- const config = useDateTimeConfig();- const parts = formatDateParts(start, {- locale: config.locale,- // Floating times are stored as UTC wall times; read them unshifted.- timeZone: poll.timeZone ? config.timeZone : "UTC",- });- return <DateIconInner dow={parts.weekday} day={parts.day} />;-}--export const SchedulePollForm = ({- name,- onSubmit,-}: {- name: string;- onSubmit?: (data: ScheduleFormData) => void;-}) => {- const poll = usePoll();-- const scoreByOptionId = useScoreByOptionId();- const { participants } = useParticipants();-- const options = [...poll.options]- .sort((a, b) => {- const aYes = scoreByOptionId[a.id].yes.length;- const bYes = scoreByOptionId[b.id].yes.length;- const aIfNeedBe = scoreByOptionId[a.id].ifNeedBe.length;- const bIfNeedBe = scoreByOptionId[b.id].ifNeedBe.length;-- const aTotal = aYes + aIfNeedBe;- const bTotal = bYes + bIfNeedBe;-- if (aTotal !== bTotal) {- return bTotal - aTotal;- }-- if (aYes !== bYes) {- return bYes - aYes;- }-- return bIfNeedBe - aIfNeedBe;- })- .map((option) => {- return { ...option, votes: scoreByOptionId[option.id] };- });-- const form = useForm({- defaultValues: {- selectedOptionId: options[0].id,- notify: "all" as const,- },- resolver: zodResolver(formSchema),- });-- return (- <Form {...form}>- <form- id={name}- className="space-y-4"- onSubmit={form.handleSubmit((data) => {- onSubmit?.(data);- })}- >- <FormField- control={form.control}- name="selectedOptionId"- render={({ field }) => {- return (- <FormItem className="relative">- <FormLabel htmlFor={field.name}>- <Trans i18nKey="dates" defaults="Dates" />- </FormLabel>- <FormControl>- <RadioGroup- onValueChange={field.onChange}- value={field.value}- className="grid max-h-96 gap-2 overflow-y-auto rounded-xl bg-gray-100 p-2 dark:bg-gray-900"- >- {options.map((option) => {- const allDay = option.duration === 0;-- return (- <label- key={option.id}- htmlFor={option.id}- className={cn(- "group flex select-none items-start gap-4 rounded-lg border bg-card p-3 text-base",- field.value === option.id ? "" : "",- )}- >- <RadioGroupItem id={option.id} value={option.id} />- <div className="grow">- <div className="flex gap-x-4">- <DateIcon start={option.startTime} />- <div className="grow whitespace-nowrap">- <div className="font-medium text-sm">- <EventDate- value={option.startTime}- allDay={allDay}- timeZone={poll.timeZone}- />- </div>- <div className="text-muted-foreground text-sm">- <EventTimeRange- start={option.startTime}- end={- new Date(- option.startTime.getTime() +- option.duration * 60_000,- )- }- allDay={allDay}- timeZone={poll.timeZone}- />- </div>- </div>- <div>- <ConnectedScoreSummary optionId={option.id} />- </div>- </div>- <div className="mt-4">- <VoteSummaryProgressBar- {...scoreByOptionId[option.id]}- total={participants.length}- showTentative={poll.allowTentativeVotes}- />- </div>- </div>- </label>- );- })}- </RadioGroup>- </FormControl>- </FormItem>- );- }}- />- </form>- </Form>- );-};--export function SchedulePollDialog(props: DialogProps) {- const poll = usePoll();- const router = useRouter();- const scheduleEvent = trpc.polls.book.useMutation({- onSuccess: () => router.refresh(),- });- return (- <Dialog {...props}>- <DialogContent size="2xl">- <DialogHeader>- <DialogTitle>- <Trans i18nKey="schedulePoll" defaults="Schedule" />- </DialogTitle>- <DialogDescription>- <Trans- i18nKey="schedulePollDescription"- defaults="Select a final date for your event."- />- </DialogDescription>- </DialogHeader>- <SchedulePollForm- name="schedule-form"- onSubmit={(data) => {- toast.promise(- scheduleEvent.mutateAsync({- pollId: poll.id,- optionId: data.selectedOptionId,- notify: data.notify,- }),- {- loading: (- <Trans i18nKey="schedulingPoll" defaults="Scheduling..." />- ),- success: (- <Trans i18nKey="pollScheduled" defaults="Poll scheduled" />- ),- error: (- <Trans- i18nKey="schedulePollError"- defaults="Failed to schedule poll"- />- ),- },- );- props.onOpenChange?.(false);- }}- />- <DialogFooter>- <DialogClose render={<Button />}>- <Trans i18nKey="cancel" />- </DialogClose>- <Button- loading={scheduleEvent.isPending}- type="submit"- form="schedule-form"- variant="primary"- >- <Trans i18nKey="schedulePoll" defaults="Schedule" />- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}diff --git a/apps/web/src/features/poll/components/poll-admin-menu.tsx b/apps/web/src/features/poll/components/poll-admin-menu.tsxindex d5cccaf84..bc5cd5f34 100644--- a/apps/web/src/features/poll/components/poll-admin-menu.tsx+++ b/apps/web/src/features/poll/components/poll-admin-menu.tsx@@ -10,7 +10,6 @@ import {DropdownMenuTrigger,} from "@rallly/ui/dropdown-menu";import {- CalendarCheck2Icon,CircleStopIcon,CopyIcon,DownloadIcon,@@ -26,15 +25,13 @@ import { ProBadge } from "@/features/billing/components/pro-badge";import { usePoll } from "@/features/poll/client";import { DuplicateDialog } from "@/features/poll/components/duplicate-dialog";import { DeletePollDialog } from "@/features/poll/components/manage-poll/delete-poll-dialog";-import { SchedulePollDialog } from "@/features/poll/components/manage-poll/schedule-poll-dialog";import { useCsvExporter } from "@/features/poll/components/manage-poll/use-csv-exporter";import { Trans, useTranslation } from "@/i18n/client";import { trpc } from "@/trpc/client";/*** The poll admin header's overflow menu. Reads the poll from the legacy- * poll context because the schedule dialog and CSV export need every- * response's votes.+ * poll context because the CSV export needs every response's votes.*/export function PollAdminMenu() {const poll = usePoll();@@ -42,7 +39,6 @@ export function PollAdminMenu() {const router = useRouter();const isFree = useIsFree();const { exportToCsv } = useCsvExporter();- const scheduleDialog = useDialog();const duplicateDialog = useDialog();const deleteDialog = useDialog();// These pages are server rendered, so a status change shows once they are@@ -54,8 +50,6 @@ export function PollAdminMenu() {onSuccess: () => router.refresh(),});- const canSchedule = poll.status === "open" || poll.status === "closed";-return (<><DropdownMenu modal={false}>@@ -86,25 +80,6 @@ export function PollAdminMenu() {<DownloadIcon /><Trans i18nKey="exportToCsv" defaults="Export to CSV" /></DropdownMenuItem>- {canSchedule ? (- <DropdownMenuItem- onClick={() => {- if (isFree) {- showPayWall({- from: "manage-poll",- action: "schedule",- pollId: poll.id,- });- } else {- scheduleDialog.trigger();- }- }}- >- <CalendarCheck2Icon />- <Trans i18nKey="schedulePoll" defaults="Schedule" />- {isFree ? <ProBadge /> : null}- </DropdownMenuItem>- ) : null}<DropdownMenuItemonClick={() => {if (isFree) {@@ -148,7 +123,6 @@ export function PollAdminMenu() {</DropdownMenuItem></DropdownMenuContent></DropdownMenu>- <SchedulePollDialog {...scheduleDialog.dialogProps} /><DuplicateDialogpollId={poll.id}pollTitle={poll.title}diff --git a/apps/web/src/features/poll/components/poll-layout.tsx b/apps/web/src/features/poll/components/poll-layout.tsxindex b7133d0ca..3b257e1a2 100644--- a/apps/web/src/features/poll/components/poll-layout.tsx+++ b/apps/web/src/features/poll/components/poll-layout.tsx@@ -15,20 +15,15 @@ import { usePoll } from "@/features/poll/client";import ManagePoll from "@/features/poll/components/manage-poll";import { NotificationToggle } from "@/features/poll/components/notification-toggle";import { LegacyPollContextProvider } from "@/features/poll/components/poll-context-provider";-import { ShareDialog } from "@/features/poll/components/share-dialog";+import { PollPrimaryActions } from "@/features/poll/components/poll-primary-actions";import { Trans } from "@/i18n/client";const AdminControls = () => {- const poll = usePoll();return (<div className="flex items-center gap-x-2"><NotificationToggle /><ManagePoll />- <ShareDialog- pollId={poll.id}- pollStatus={poll.status}- inviteLink={poll.inviteLink}- />+ <PollPrimaryActions /></div>);};diff --git a/apps/web/src/features/poll/components/poll-primary-actions.tsx b/apps/web/src/features/poll/components/poll-primary-actions.tsxnew file mode 100644index 000000000..4ac113c7f--- /dev/null+++ b/apps/web/src/features/poll/components/poll-primary-actions.tsx@@ -0,0 +1,40 @@+"use client";++import { Button } from "@rallly/ui/button";+import { useDialog } from "@rallly/ui/dialog";+import { CalendarCheck2Icon } from "lucide-react";+import { usePoll } from "@/features/poll/client";+import { FinalizePollDialog } from "@/features/poll/components/finalize-poll-dialog";+import { ShareDialog } from "@/features/poll/components/share-dialog";+import { Trans } from "@/i18n/client";++/**+ * The header's two actions. Finalize is the call to action for as long as+ * there is something to finalize; a new poll opens the share dialog on its+ * own, so Share stays secondary here.+ */+export function PollPrimaryActions() {+ const poll = usePoll();+ const finalizeDialog = useDialog();+ const canFinalize = poll.status === "open" || poll.status === "closed";++ return (+ <>+ <ShareDialog+ pollId={poll.id}+ pollStatus={poll.status}+ inviteLink={poll.inviteLink}+ variant={canFinalize ? "default" : "primary"}+ />+ {canFinalize ? (+ <Button variant="primary" {...finalizeDialog.triggerProps}>+ <CalendarCheck2Icon data-icon="inline-start" />+ <span className="sr-only sm:not-sr-only">+ <Trans i18nKey="finalize" defaults="Finalize" />+ </span>+ </Button>+ ) : null}+ <FinalizePollDialog {...finalizeDialog.dialogProps} />+ </>+ );+}diff --git a/apps/web/src/features/poll/components/share-dialog.tsx b/apps/web/src/features/poll/components/share-dialog.tsxindex 4b1125483..f373a9a1d 100644--- a/apps/web/src/features/poll/components/share-dialog.tsx+++ b/apps/web/src/features/poll/components/share-dialog.tsx@@ -27,10 +27,12 @@ export function ShareDialog({pollId,pollStatus,inviteLink,+ variant = "primary",}: {pollId: string;pollStatus: PollStatus;inviteLink: string;+ variant?: "primary" | "default";}) {const dialog = useDialog();const sharePollFlash = useFlash(SHARE_POLL_FLASH_KEY);@@ -50,7 +52,7 @@ export function ShareDialog({return (<><Button- variant="primary"+ variant={variant}{...dialog.triggerProps}onClick={() => {setSource("manual");diff --git a/apps/web/src/features/poll/utils.test.ts b/apps/web/src/features/poll/utils.test.tsindex 9506aa537..4c178b2fb 100644--- a/apps/web/src/features/poll/utils.test.ts+++ b/apps/web/src/features/poll/utils.test.ts@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";import {filterCommentsForViewer,filterParticipantsByVote,+ getFinalizePlanGate,maskParticipantsForViewer,+ rankOptionsByPopularity,toAvailabilitySpans,} from "./utils";@@ -202,3 +204,107 @@ describe("toAvailabilitySpans", () => {]);});});++describe("rankOptionsByPopularity", () => {+ const options = [+ { id: "a", startTime: new Date("2026-03-01T10:00:00Z"), duration: 60 },+ { id: "b", startTime: new Date("2026-03-02T10:00:00Z"), duration: 60 },+ { id: "c", startTime: new Date("2026-03-03T10:00:00Z"), duration: 60 },+ ];+ const vote = (optionId: string, type: "yes" | "ifNeedBe" | "no") => ({+ optionId,+ type,+ });++ it("orders by yes plus ifNeedBe, then yes, then ifNeedBe", () => {+ const participants = [+ {+ id: "p1",+ votes: [vote("a", "no"), vote("b", "yes"), vote("c", "yes")],+ },+ {+ id: "p2",+ votes: [vote("a", "yes"), vote("b", "ifNeedBe"), vote("c", "yes")],+ },+ {+ id: "p3",+ votes: [vote("a", "yes"), vote("b", "yes"), vote("c", "no")],+ },+ ];++ const ranked = rankOptionsByPopularity({ options, participants });++ expect(ranked.map((r) => r.id)).toEqual(["b", "a", "c"]);+ expect(ranked[0].votes).toEqual({+ yes: ["p1", "p3"],+ ifNeedBe: ["p2"],+ no: [],+ });+ });++ it("keeps option order for ties", () => {+ const ranked = rankOptionsByPopularity({ options, participants: [] });+ expect(ranked.map((r) => r.id)).toEqual(["a", "b", "c"]);+ });++ it("ignores votes for options that no longer exist", () => {+ const participants = [{ id: "p1", votes: [vote("gone", "yes")] }];+ const ranked = rankOptionsByPopularity({ options, participants });+ expect(ranked.every((r) => r.votes.yes.length === 0)).toBe(true);+ });+});++describe("getFinalizePlanGate", () => {+ it("lets a pro space notify and mint a meeting", () => {+ expect(+ getFinalizePlanGate({+ tier: "pro",+ conferencing: { provider: "meet" },+ }),+ ).toBeNull();+ });++ it("lets a free space finalize silently without a provider link", () => {+ expect(+ getFinalizePlanGate({+ tier: "hobby",+ conferencing: null,+ }),+ ).toBeNull();+ expect(+ getFinalizePlanGate({+ tier: "hobby",+ conferencing: { provider: "custom" },+ }),+ ).toBeNull();+ });++ it("lets a free space notify participants", () => {+ expect(+ getFinalizePlanGate({+ tier: "hobby",+ conferencing: null,+ }),+ ).toBeNull();+ });++ it("gates Zoom and Teams links on a free space", () => {+ for (const provider of ["zoom", "teams"] as const) {+ expect(+ getFinalizePlanGate({+ tier: "hobby",+ conferencing: { provider },+ }),+ ).toBe("conferencing");+ }+ });++ it("lets a free space mint a Google Meet link", () => {+ expect(+ getFinalizePlanGate({+ tier: "hobby",+ conferencing: { provider: "meet" },+ }),+ ).toBeNull();+ });+});diff --git a/apps/web/src/features/poll/utils.ts b/apps/web/src/features/poll/utils.tsindex 22e07a185..d9c45a253 100644--- a/apps/web/src/features/poll/utils.ts+++ b/apps/web/src/features/poll/utils.ts@@ -1,6 +1,9 @@import { customAlphabet } from "nanoid";+import type { PollConferencing } from "@/features/conferencing/schema";+import { isProConferencingProvider } from "@/features/conferencing/utils";import type { VoteType } from "@/features/poll/constants";import type { PollComment, PollParticipant } from "@/features/poll/types";+import type { SpaceTier } from "@/features/space/schema";// Alphanumeric only: url safe with no linkifier edge cases. 32 chars is the// floor documented on Participant.token and PollInvite.token.@@ -135,3 +138,76 @@ export function toAvailabilitySpans({modifiers: type === "ifNeedBe" ? ["ifNeedBe"] : [],}));}++export type OptionVotes = {+ yes: string[];+ ifNeedBe: string[];+ no: string[];+};++/**+ * Options in the order a host picks from: most available first, with a+ * firm yes outranking an ifNeedBe at the same total. Ties keep option order.+ */+export function rankOptionsByPopularity<T extends { id: string }>({+ options,+ participants,+}: {+ options: T[];+ participants: { id: string; votes: { optionId: string; type: VoteType }[] }[];+}): (T & { votes: OptionVotes })[] {+ const votesByOptionId = new Map<string, OptionVotes>(+ options.map((option) => [option.id, { yes: [], ifNeedBe: [], no: [] }]),+ );+ for (const participant of participants) {+ for (const vote of participant.votes) {+ votesByOptionId.get(vote.optionId)?.[vote.type].push(participant.id);+ }+ }+ const score = (votes: OptionVotes) => [+ votes.yes.length + votes.ifNeedBe.length,+ votes.yes.length,+ votes.ifNeedBe.length,+ ];+ return options+ .map((option) => ({+ ...option,+ votes: votesByOptionId.get(option.id) ?? {+ yes: [],+ ifNeedBe: [],+ no: [],+ },+ }))+ .sort((a, b) => {+ const sa = score(a.votes);+ const sb = score(b.votes);+ for (let i = 0; i < sa.length; i++) {+ if (sa[i] !== sb[i]) return sb[i] - sa[i];+ }+ return 0;+ });+}++export type FinalizePlanGate = "conferencing";++/**+ * Finalizing and notifying participants are free. What a free space cannot+ * do at finalize is mint a meeting with a Pro provider.+ */+export function getFinalizePlanGate({+ tier,+ conferencing,+}: {+ tier: SpaceTier;+ conferencing: { provider: PollConferencing["provider"] } | null;+}): FinalizePlanGate | null {+ if (tier === "pro") return null;+ if (+ conferencing &&+ conferencing.provider !== "custom" &&+ isProConferencingProvider(conferencing.provider)+ ) {+ return "conferencing";+ }+ return null;+}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex dfc1ae650..3006fed59 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -34,6 +34,7 @@ import {hasPollAdminAccess,} from "@/features/poll/data";import { MAX_POLL_DESCRIPTION_LENGTH } from "@/features/poll/schema";+import { getFinalizePlanGate } from "@/features/poll/utils";import { formatEventDateTime } from "@/features/scheduled-event/utils";import { getActiveSpaceForUser } from "@/features/space/data";import {@@ -1058,12 +1059,12 @@ export const polls = router({event,};}),- book: proProcedure+ book: spaceProcedure.input(z.object({pollId: z.string(),optionId: z.string(),- notify: z.enum(["none", "all", "attendees"]),+ notifyParticipantIds: z.array(z.string()),}),).mutation(async ({ input, ctx }) => {@@ -1196,15 +1197,31 @@ export const polls = router({});}+ const pollConferencing = parsePollConferencing(poll.conferencing, {+ pollId: poll.id,+ });++ // Finalizing and notifying are free; a Zoom or Teams meeting is what+ // the plan pays for. ctx.space is the coerced DTO, the same tier the+ // client gates on.+ const planGate = getFinalizePlanGate({+ tier: ctx.space.tier,+ conferencing: pollConferencing,+ });+ if (planGate) {+ throw new TRPCError({+ code: "PAYMENT_REQUIRED",+ message: "Creating a video meeting requires a paid plan",+ });+ }+// 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,- }),+ conferencing: pollConferencing,title: poll.title,start: eventTimes.start,end: eventTimes.end,@@ -1354,38 +1371,19 @@ export const polls = router({message: "Failed to generate ics",});} else {- const participantsToEmail: Array<{- name: string;- email: string;- locale: string | undefined;- timeZone: string | null;- }> = [];-- if (input.notify === "all") {- poll.participants.forEach((p) => {- if (p.email) {- participantsToEmail.push({- name: p.name,- email: p.email,- locale: p.locale ?? undefined,- timeZone: p.timeZone,- });- }- });- }-- if (input.notify === "attendees") {- attendees.forEach((p) => {- if (p.email) {- participantsToEmail.push({- name: p.name,- email: p.email,- locale: p.locale ?? undefined,- timeZone: p.timeZone,- });- }- });- }+ const notifyIds = new Set(input.notifyParticipantIds);+ const participantsToEmail = poll.participants.flatMap((p) =>+ notifyIds.has(p.id) && p.email+ ? [+ {+ name: p.name,+ email: p.email,+ locale: p.locale ?? undefined,+ timeZone: p.timeZone,+ },+ ]+ : [],+ );const hostEmail = poll.user.email;const hostName = poll.user.name;diff --git a/packages/ui/src/checkbox.tsx b/packages/ui/src/checkbox.tsxindex 6ff8fb264..fa8e4b0ec 100644--- a/packages/ui/src/checkbox.tsx+++ b/packages/ui/src/checkbox.tsx@@ -1,7 +1,7 @@"use client";import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";-import { CheckIcon } from "lucide-react";+import { CheckIcon, MinusIcon } from "lucide-react";import { cn } from "./lib/utils";@@ -15,7 +15,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {nativeButtondata-slot="checkbox"className={cn(- "peer flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-[4px] border border-input bg-background/80 shadow-xs outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-disabled:cursor-not-allowed data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground data-disabled:opacity-50 dark:bg-foreground/5 dark:aria-invalid:ring-destructive/40",+ "group peer flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-[4px] border border-input bg-background/80 shadow-xs outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-disabled:cursor-not-allowed data-checked:border-primary data-indeterminate:border-primary data-checked:bg-primary data-indeterminate:bg-primary data-checked:text-primary-foreground data-indeterminate:text-primary-foreground data-disabled:opacity-50 dark:bg-foreground/5 dark:aria-invalid:ring-destructive/40",className,)}{...props}@@ -24,7 +24,8 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {data-slot="checkbox-indicator"className="flex items-center justify-center text-current">- <CheckIcon className="size-3.5" />+ <CheckIcon className="size-3.5 group-data-indeterminate:hidden" />+ <MinusIcon className="hidden size-3.5 group-data-indeterminate:block" /></CheckboxPrimitive.Indicator></CheckboxPrimitive.Root>);