Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Redesign the poll share dialog with email invites (#3160)

Luke Vella3c8dbf81e647
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 676c9973f..78673f154 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -170,16 +170,12 @@
"continueToCheckout": "Continue to checkout",
"continueWithEmail": "Continue with email",
"controlPanel": "Control Panel",
- "cookieConsentAccept": "Accept",
- "cookieConsentIntro": "We use cookies to improve your experience.",
- "cookieConsentLabel": "Cookie consent",
- "cookieConsentOptOut": "Opt out",
- "cookieConsentPolicy": "Learn more in our <policyLink>cookie policy</policyLink>.",
"copied": "Copied",
"copiedToClipboard": "Copied to clipboard",
"copy": "Copy",
"copyLink": "Copy link",
"create": "Create",
+ "createAnAccount": "Create an account",
"createApiKey": "Create API key",
"createApiKeyDescription": "Create a new API key for programmatic access to your space",
"createdTime": "Created {relativeTime}",
@@ -280,6 +276,7 @@
"editSettings": "Edit settings",
"editVotes": "Edit votes",
"email": "Email",
+ "emailAddress": "Email address",
"emailChangeAddressTaken": "This email address is already in use by another account.",
"emailChangeRequestError": "We couldn't process this request. Please try again later.",
"emailChangeRequestSent": "Verify your new email address",
@@ -401,6 +398,7 @@
"inviteCanceledSuccess": "Invite canceled successfully",
"inviteFailed": "Failed to send invitation",
"inviteLink": "Invite link",
+ "inviteLinkCopied": "Invite link copied",
"inviteMember": "Invite member",
"inviteMemberDescription": "Invite a new member to your space",
"inviteMemberDialogPermissionAllowed": "Allowed:",
@@ -411,10 +409,13 @@
"inviteMemberFormSubmit": "Send invite",
"inviteMembersUpsellDescription": "Invite members to manage polls and events together in this space.",
"inviteNotEnoughSeats": "There are not enough seats available to send this invite",
- "inviteParticipantLinkInfo": "Anyone with this link will be able to vote on your poll.",
"inviteParticipantsDescription": "Copy and share the invite link to start gathering responses from your participants.",
"invitePending": "An invitation has already been sent to this email address",
"inviteSent": "Invitation sent",
+ "inviteStatusOpened": "Opened",
+ "inviteStatusResponded": "Responded",
+ "inviteStatusSending": "Sending",
+ "inviteStatusSent": "Sent",
"inviteUpdated": "Invitation updated with new role",
"jobTitle": "Your role",
"jobTitleAdministratorOrCoordinator": "Administrator or coordinator",
@@ -769,6 +770,19 @@
"setupPasswordAlertTitle": "Login quicker with a password",
"setupPasswordButton": "Set up password",
"share": "Share",
+ "shareDialogAlreadyInvited": "{email} is already invited",
+ "shareDialogAlreadyResponded": "{email} has already responded",
+ "shareDialogDailyLimit": "You've reached today's limit of 100 invites",
+ "shareDialogDescription": "Share the invite link, or invite people by email.",
+ "shareDialogGuestPrompt": "Create an account to invite people by email. Your invites and their responses stay attached to your account instead of this browser.",
+ "shareDialogInvalidEmail": "Enter a single valid email address",
+ "shareDialogInvitedCount": "{count, plural, one {# invited} other {# invited}}",
+ "shareDialogInviteSent": "Invite sent to {email}",
+ "shareDialogNoInvitesDescription": "Enter an address above to send the first invite.",
+ "shareDialogNoInvitesTitle": "No one invited yet",
+ "shareDialogPollClosed": "Reopen the poll to send invites",
+ "shareDialogSendFailed": "Couldn't send to {email}. Try again.",
+ "shareDialogSendInvite": "Send invite",
"showParticipantVotes": "Show participant votes",
"showPassword": "Show password",
"shrink": "Shrink",
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
index 2140f5623..f78f36164 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
@@ -5,6 +5,7 @@ import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { PollLayout } from "@/features/poll/components/poll-layout";
+import { loadPollInvites } from "@/features/poll/invite/loaders";
import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";
export default async function Layout(
@@ -29,14 +30,15 @@ export default async function Layout(
redirect(`/invite/${params.urlId}`);
}
- await Promise.all([
+ const [invites] = await Promise.all([
+ loadPollInvites(params.urlId),
trpc.polls.participants.list.prefetch({ pollId: params.urlId }),
trpc.polls.comments.list.prefetch({ pollId: params.urlId }),
]);
return (
<HydrationBoundary state={dehydrate(trpc.queryClient)}>
- <PollLayout>{children}</PollLayout>
+ <PollLayout invites={invites}>{children}</PollLayout>
</HydrationBoundary>
);
}
diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsx
index 1681d8c7b..b2f166bd6 100644
--- a/apps/web/src/features/billing/client.tsx
+++ b/apps/web/src/features/billing/client.tsx
@@ -40,7 +40,8 @@ export type PayWallTrigger = {
| "space-members"
| "space-collaboration"
| "billing-settings"
- | "sidebar";
+ | "sidebar"
+ | "invite-dialog";
setting?: string;
action?: string;
pollId?: string;
diff --git a/apps/web/src/features/poll/components/invite-by-email.tsx b/apps/web/src/features/poll/components/invite-by-email.tsx
new file mode 100644
index 000000000..4a700f0a5
--- /dev/null
+++ b/apps/web/src/features/poll/components/invite-by-email.tsx
@@ -0,0 +1,325 @@
+"use client";
+
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@rallly/ui/button";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@rallly/ui/input-group";
+import { toast } from "@rallly/ui/sonner";
+import { MailIcon } from "lucide-react";
+import React from "react";
+import { useForm } from "react-hook-form";
+import {
+ EmptyState,
+ EmptyStateDescription,
+ EmptyStateIcon,
+ EmptyStateTitle,
+} from "@/components/empty-state";
+import { LoginLink } from "@/components/login-link";
+import { RegisterLink } from "@/components/register-link";
+import { showPayWall, useIsFree } from "@/features/billing/client";
+import { ProBadge } from "@/features/billing/components/pro-badge";
+import { usePoll } from "@/features/poll/client";
+import type { InviteeRowStatus } from "@/features/poll/components/invitee-list";
+import {
+ InviteeListPreview,
+ InviteeRow,
+} from "@/features/poll/components/invitee-list";
+import { sendPollInviteAction } from "@/features/poll/invite/actions";
+import { sendPollInviteSchema } from "@/features/poll/invite/schema";
+import type { PollInviteListItem } from "@/features/poll/invite/types";
+import { useUser } from "@/features/user/client";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
+
+type Row = {
+ id: string;
+ email: string;
+ status: InviteeRowStatus;
+};
+
+// Same rule as the server, so a client accepted address is never refused
+const inviteFormSchema = sendPollInviteSchema.pick({ email: true });
+type InviteFormValues = { email: string };
+
+/**
+ * `invites` is server data passed down from the route; the send action's
+ * success handler refreshes the route, which is what replaces an optimistic
+ * "Sending" row with the real one.
+ */
+export function InviteByEmail({ invites }: { invites: PollInviteListItem[] }) {
+ const poll = usePoll();
+ const { user } = useUser();
+ const isFree = useIsFree();
+ const { t } = useTranslation();
+
+ const isGuest = !user || user.isGuest;
+ const isOpen = poll.status === "open";
+
+ const form = useForm<InviteFormValues>({
+ resolver: zodResolver(inviteFormSchema),
+ defaultValues: { email: "" },
+ });
+ const [sending, setSending] = React.useState<string[]>([]);
+ const [announcement, setAnnouncement] = React.useState("");
+ const announceTimeout = React.useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
+
+ const invitedEmails = React.useMemo(
+ () => new Set(invites.map((invite) => invite.email.toLowerCase())),
+ [invites],
+ );
+
+ // An optimistic row lives until the refreshed server list carries it.
+ React.useEffect(() => {
+ setSending((prev) => {
+ const next = prev.filter((address) => !invitedEmails.has(address));
+ return next.length === prev.length ? prev : next;
+ });
+ }, [invitedEmails]);
+
+ const rows: Row[] = [
+ ...sending
+ .filter((address) => !invitedEmails.has(address))
+ .map((address) => ({
+ id: `sending:${address}`,
+ email: address,
+ status: "sending" as const,
+ })),
+ ...invites,
+ ];
+
+ const announce = (message: string) => {
+ if (announceTimeout.current) {
+ clearTimeout(announceTimeout.current);
+ }
+ setAnnouncement("");
+ announceTimeout.current = setTimeout(() => setAnnouncement(message), 30);
+ };
+
+ React.useEffect(
+ () => () => {
+ if (announceTimeout.current) {
+ clearTimeout(announceTimeout.current);
+ }
+ },
+ [],
+ );
+
+ const countLabel = (count: number) =>
+ t("shareDialogInvitedCount", {
+ defaultValue: "{count, plural, one {# invited} other {# invited}}",
+ count,
+ });
+
+ const sendInvite = useSafeAction(sendPollInviteAction, {
+ onSuccess: async ({ data, input }) => {
+ if (!data) {
+ setSending((prev) => prev.filter((address) => address !== input.email));
+ return;
+ }
+ if (data.ok) {
+ announce(
+ t("shareDialogInviteSent", {
+ defaultValue: "Invite sent to {email}",
+ email: input.email,
+ }),
+ );
+ return;
+ }
+ setSending((prev) => prev.filter((address) => address !== input.email));
+ const messages = {
+ alreadyInvited: t("shareDialogAlreadyInvited", {
+ defaultValue: "{email} is already invited",
+ email: input.email,
+ }),
+ alreadyResponded: t("shareDialogAlreadyResponded", {
+ defaultValue: "{email} has already responded",
+ email: input.email,
+ }),
+ dailyLimit: t("shareDialogDailyLimit", {
+ defaultValue: "You've reached today's limit of 100 invites",
+ }),
+ pollClosed: t("shareDialogPollClosed", {
+ defaultValue: "Reopen the poll to send invites",
+ }),
+ sendFailed: t("shareDialogSendFailed", {
+ defaultValue: "Couldn't send to {email}. Try again.",
+ email: input.email,
+ }),
+ notFound: t("actionErrorNotFound", {
+ defaultValue: "The resource was not found",
+ }),
+ paymentRequired: t("actionErrorPaymentRequired", {
+ defaultValue: "You need to upgrade to perform this action",
+ }),
+ };
+ toast.error(messages[data.reason]);
+ announce(messages[data.reason]);
+ if (data.reason === "sendFailed") {
+ form.setValue("email", input.email);
+ }
+ },
+ onError: ({ input }) => {
+ setSending((prev) => prev.filter((address) => address !== input.email));
+ form.setValue("email", input.email);
+ },
+ });
+
+ const onInvalid = () => {
+ announce(
+ t("shareDialogInvalidEmail", {
+ defaultValue: "Enter a single valid email address",
+ }),
+ );
+ form.setFocus("email");
+ };
+
+ const onValid = ({ email: address }: InviteFormValues) => {
+ if (isFree) {
+ showPayWall({ from: "invite-dialog", pollId: poll.id });
+ return;
+ }
+ if (rows.some((row) => row.email.toLowerCase() === address)) {
+ const message = t("shareDialogAlreadyInvited", {
+ defaultValue: "{email} is already invited",
+ email: address,
+ });
+ toast(message);
+ announce(message);
+ form.setFocus("email");
+ return;
+ }
+ setSending((prev) => [address, ...prev]);
+ form.reset();
+ form.setFocus("email");
+ sendInvite.execute({ pollId: poll.id, email: address });
+ };
+
+ return (
+ <div className="min-w-0">
+ {isGuest ? (
+ <div className="space-y-2 rounded-lg bg-muted p-3 text-sm">
+ <p className="text-muted-foreground">
+ <Trans
+ i18nKey="shareDialogGuestPrompt"
+ defaults="Create an account to invite people by email. Your invites and their responses stay attached to your account instead of this browser."
+ />
+ </p>
+ <div className="flex gap-2">
+ <RegisterLink className="underline hover:text-foreground">
+ <Trans i18nKey="createAnAccount" defaults="Create an account" />
+ </RegisterLink>
+ <LoginLink className="underline hover:text-foreground">
+ <Trans i18nKey="login" defaults="Login" />
+ </LoginLink>
+ </div>
+ </div>
+ ) : (
+ <>
+ <form
+ onSubmit={form.handleSubmit(onValid, onInvalid)}
+ className="flex min-w-0 gap-2"
+ noValidate
+ >
+ <label htmlFor="share-dialog-email" className="sr-only">
+ <Trans i18nKey="emailAddress" defaults="Email address" />
+ </label>
+ <InputGroup className="min-w-0 flex-1">
+ <InputGroupAddon>
+ <MailIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ {...form.register("email")}
+ id="share-dialog-email"
+ type="email"
+ inputMode="email"
+ autoComplete="off"
+ placeholder="[email protected]"
+ disabled={!isOpen}
+ aria-invalid={form.formState.errors.email ? true : undefined}
+ aria-describedby={
+ isOpen ? undefined : "share-dialog-closed-reason"
+ }
+ />
+ </InputGroup>
+ <Button
+ type="submit"
+ variant="primary"
+ disabled={!isOpen}
+ aria-describedby={
+ isOpen ? undefined : "share-dialog-closed-reason"
+ }
+ >
+ <Trans i18nKey="shareDialogSendInvite" defaults="Send invite" />
+ {isFree ? (
+ <ProBadge className="ml-1.5 bg-primary-foreground/20 text-primary-foreground" />
+ ) : null}
+ </Button>
+ </form>
+ {!isOpen ? (
+ <p
+ id="share-dialog-closed-reason"
+ className="mt-3 text-muted-foreground text-sm"
+ >
+ <Trans
+ i18nKey="shareDialogPollClosed"
+ defaults="Reopen the poll to send invites"
+ />
+ </p>
+ ) : null}
+
+ <div className="mt-3">
+ {rows.length === 0 ? (
+ <div className="relative mt-2">
+ <InviteeListPreview />
+ <EmptyState className="absolute inset-0 py-0 backdrop-blur-[2px]">
+ <EmptyStateIcon>
+ <MailIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans
+ i18nKey="shareDialogNoInvitesTitle"
+ defaults="No one invited yet"
+ />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ <Trans
+ i18nKey="shareDialogNoInvitesDescription"
+ defaults="Enter an address above to send the first invite."
+ />
+ </EmptyStateDescription>
+ </EmptyState>
+ </div>
+ ) : (
+ <>
+ <h4 id="share-dialog-invited-heading" className="sr-only">
+ {countLabel(rows.length)}
+ </h4>
+ <ul
+ aria-labelledby="share-dialog-invited-heading"
+ className="-mx-1.5 max-h-72 min-h-0 overflow-y-auto px-1.5"
+ >
+ {rows.map((row) => (
+ <InviteeRow
+ key={row.id}
+ email={row.email}
+ status={row.status}
+ />
+ ))}
+ </ul>
+ </>
+ )}
+ </div>
+ </>
+ )}
+
+ <p className="sr-only" aria-live="polite">
+ {announcement}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/components/invite-dialog.tsx b/apps/web/src/features/poll/components/invite-dialog.tsx
deleted file mode 100644
index ad1eb806b..000000000
--- a/apps/web/src/features/poll/components/invite-dialog.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { buttonVariants } from "@rallly/ui";
-import { Button } from "@rallly/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@rallly/ui/dialog";
-
-import { ArrowUpRightIcon, Share2Icon } from "lucide-react";
-import Link from "next/link";
-import React from "react";
-import { useCopyToClipboard } from "react-use";
-
-import { usePoll } from "@/features/poll/client";
-import { Trans } from "@/i18n/client";
-
-export function CopyInviteLinkButton() {
- const [didCopy, setDidCopy] = React.useState(false);
- const [state, copyToClipboard] = useCopyToClipboard();
- const poll = usePoll();
- const inviteLinkWithoutProtocol = poll.inviteLink.replace(/^https?:\/\//, "");
-
- React.useEffect(() => {
- if (state.error) {
- console.error(`Unable to copy value: ${state.error.message}`);
- }
- }, [state]);
-
- return (
- <Button
- className="min-w-0 grow"
- onClick={() => {
- copyToClipboard(poll.inviteLink);
- setDidCopy(true);
- setTimeout(() => {
- setDidCopy(false);
- }, 1000);
- }}
- >
- {didCopy ? (
- <Trans i18nKey="copied" />
- ) : (
- <span className="min-w-0 truncate">{inviteLinkWithoutProtocol}</span>
- )}
- </Button>
- );
-}
-
-export const InviteDialog = () => {
- const [isOpen, setIsOpen] = React.useState(false);
- const poll = usePoll();
-
- return (
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
- <DialogTrigger render={<Button variant="primary" />}>
- <Share2Icon data-icon="inline-start" />
- <span className="sr-only sm:not-sr-only">
- <Trans i18nKey="share" defaults="Share" />
- </span>
- </DialogTrigger>
- <DialogContent data-testid="invite-participant-dialog">
- <div className="flex">
- <Share2Icon className="size-6 text-primary" />
- </div>
- <DialogHeader className="">
- <DialogTitle>
- <Trans i18nKey="share" defaults="Share" />
- </DialogTitle>
- <DialogDescription>
- <Trans
- i18nKey="inviteParticipantsDescription"
- defaults="Copy and share the invite link to start gathering responses from your participants."
- />
- </DialogDescription>
- </DialogHeader>
- <div className="min-w-0">
- <p className="mb-2 text-sm">
- <Trans i18nKey="inviteLink" defaults="Invite link" />
- </p>
- <div className="flex gap-2">
- <CopyInviteLinkButton />
- <div className="shrink-0">
- <Link
- target="_blank"
- href={`/invite/${poll.id}`}
- prefetch={false}
- className={buttonVariants()}
- >
- <ArrowUpRightIcon className="size-4" />
- </Link>
- </div>
- </div>
- </div>
- <p className="text-muted-foreground text-sm">
- <Trans
- i18nKey="inviteParticipantLinkInfo"
- defaults="Anyone with this link will be able to vote on your poll."
- />
- </p>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/apps/web/src/features/poll/components/invite-link-row.tsx b/apps/web/src/features/poll/components/invite-link-row.tsx
new file mode 100644
index 000000000..1b9c1b46e
--- /dev/null
+++ b/apps/web/src/features/poll/components/invite-link-row.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { posthog } from "@rallly/posthog/client";
+import { Button } from "@rallly/ui/button";
+import { CheckIcon, CopyIcon, LinkIcon } from "lucide-react";
+import React from "react";
+import { useCopyToClipboard } from "react-use";
+import { usePoll } from "@/features/poll/client";
+import { Trans, useTranslation } from "@/i18n/client";
+
+/**
+ * The invite link with its copy action. The URL is shown because hosts have
+ * learned to look for something that looks like a link.
+ */
+export function InviteLinkRow({ inviteLink }: { inviteLink: string }) {
+ const poll = usePoll();
+ const { t } = useTranslation();
+ const [didCopy, setDidCopy] = React.useState(false);
+ const [state, copyToClipboard] = useCopyToClipboard();
+
+ // react-use records a failed copy as `error` and a successful one as
+ // `value`; the button only claims success in the second case.
+ React.useEffect(() => {
+ if (state.error) {
+ console.error(`Unable to copy value: ${state.error.message}`);
+ return;
+ }
+ if (state.value) {
+ setDidCopy(true);
+ posthog?.capture("poll_share:invite_link_copy", { poll_id: poll.id });
+ }
+ }, [state, poll.id]);
+
+ React.useEffect(() => {
+ if (!didCopy) return;
+ const timer = setTimeout(() => setDidCopy(false), 1500);
+ return () => clearTimeout(timer);
+ }, [didCopy]);
+
+ return (
+ <div className="flex min-w-0 items-center gap-3 rounded-2xl border border-card-border bg-card p-3">
+ <span
+ aria-hidden="true"
+ className="grid size-9 shrink-0 place-items-center rounded-lg border border-card-border bg-card text-muted-foreground"
+ >
+ <LinkIcon className="size-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="font-medium text-sm">
+ <Trans i18nKey="inviteLink" defaults="Invite link" />
+ </p>
+ <p className="truncate text-muted-foreground text-xs">{inviteLink}</p>
+ </div>
+ <Button
+ variant="ghost"
+ className="shrink-0 text-primary"
+ onClick={() => copyToClipboard(inviteLink)}
+ >
+ {didCopy ? (
+ <CheckIcon data-icon="inline-start" />
+ ) : (
+ <CopyIcon data-icon="inline-start" />
+ )}
+ {didCopy ? (
+ <Trans i18nKey="copied" defaults="Copied" />
+ ) : (
+ <Trans i18nKey="copy" defaults="Copy" />
+ )}
+ </Button>
+ <p className="sr-only" aria-live="polite">
+ {didCopy
+ ? t("inviteLinkCopied", { defaultValue: "Invite link copied" })
+ : ""}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/components/invitee-list.tsx b/apps/web/src/features/poll/components/invitee-list.tsx
new file mode 100644
index 000000000..e51192741
--- /dev/null
+++ b/apps/web/src/features/poll/components/invitee-list.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { cn } from "@rallly/ui";
+import { MailIcon } from "lucide-react";
+import { Spinner } from "@/components/spinner";
+import type { PollInviteStatus } from "@/features/poll/invite/utils";
+import { Trans } from "@/i18n/client";
+
+export type InviteeRowStatus = PollInviteStatus | "sending";
+
+export function InviteeStatusPill({ status }: { status: InviteeRowStatus }) {
+ if (status === "sending") {
+ return (
+ <span className="inline-flex h-5 shrink-0 items-center">
+ <Spinner className="size-4" />
+ <span className="sr-only">
+ <Trans i18nKey="inviteStatusSending" defaults="Sending" />
+ </span>
+ </span>
+ );
+ }
+
+ const label = {
+ sent: <Trans i18nKey="inviteStatusSent" defaults="Sent" />,
+ opened: <Trans i18nKey="inviteStatusOpened" defaults="Opened" />,
+ responded: <Trans i18nKey="inviteStatusResponded" defaults="Responded" />,
+ }[status];
+
+ return (
+ <span
+ className={cn(
+ "inline-flex h-5 shrink-0 items-center rounded-full px-2 font-medium text-xs",
+ status === "responded" &&
+ "bg-green-500/10 text-green-700 dark:text-green-400",
+ status === "opened" && "bg-sky-500/10 text-sky-700 dark:text-sky-400",
+ status === "sent" &&
+ "bg-white text-muted-foreground ring-1 ring-black/10 ring-inset dark:bg-white/10 dark:ring-white/10",
+ )}
+ >
+ {label}
+ </span>
+ );
+}
+
+export function InviteeRow({
+ email,
+ status,
+}: {
+ email: string;
+ status: InviteeRowStatus;
+}) {
+ return (
+ <li className="flex h-11 items-center gap-2.5 rounded-lg px-1.5 hover:bg-accent has-[:focus-visible]:bg-accent">
+ <span
+ aria-hidden="true"
+ className="grid size-7 shrink-0 place-items-center rounded-full bg-white text-muted-foreground ring-1 ring-black/10 ring-inset dark:bg-white/10 dark:ring-white/10"
+ >
+ <MailIcon className="size-3.5" />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-sm">{email}</span>
+ <InviteeStatusPill status={status} />
+ </li>
+ );
+}
+
+const PREVIEW_ROWS: { email: string; status: InviteeRowStatus }[] = [
+ { email: "[email protected]", status: "responded" },
+ { email: "[email protected]", status: "opened" },
+ { email: "[email protected]", status: "sent" },
+ { email: "[email protected]", status: "sent" },
+];
+
+/**
+ * A faded, inert sample list rendered behind the empty state so the section
+ * shows what it will look like before anyone is invited.
+ */
+export function InviteeListPreview() {
+ return (
+ <ul
+ aria-hidden="true"
+ inert
+ className="pointer-events-none select-none [mask-image:radial-gradient(ellipse_at_center,transparent,rgba(0,0,0,0.1))]"
+ >
+ {PREVIEW_ROWS.map((row) => (
+ <InviteeRow key={row.email} email={row.email} status={row.status} />
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/web/src/features/poll/components/new-participant-modal.tsx b/apps/web/src/features/poll/components/new-participant-modal.tsx
index 02f503e0e..41b5c97c7 100644
--- a/apps/web/src/features/poll/components/new-participant-modal.tsx
+++ b/apps/web/src/features/poll/components/new-participant-modal.tsx
@@ -25,6 +25,7 @@ import { Textarea } from "@rallly/ui/textarea";
import { TRPCClientError } from "@trpc/client";
import { CircleCheckIcon, PlusIcon } from "lucide-react";
import Link from "next/link";
+import { useSearchParams } from "next/navigation";
import * as React from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
@@ -174,6 +175,9 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
const noteLength = watch("note")?.length ?? 0;
const [showNote, setShowNote] = React.useState(false);
const addParticipant = useAddParticipantMutation();
+ // The emailed invite link carries the invitee token; joining the response
+ // to it lets the host see who has responded.
+ const inviteToken = useSearchParams()?.get("invite") ?? undefined;
if (formState.isSubmitSuccessful) {
return (
@@ -267,6 +271,7 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
note: data.note,
pollId: poll.id,
timeZone,
+ inviteToken,
});
props.onSubmit?.(newParticipant);
} catch (error) {
diff --git a/apps/web/src/features/poll/components/poll-layout.tsx b/apps/web/src/features/poll/components/poll-layout.tsx
index b4154fa3d..c030b0386 100644
--- a/apps/web/src/features/poll/components/poll-layout.tsx
+++ b/apps/web/src/features/poll/components/poll-layout.tsx
@@ -12,23 +12,27 @@ import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import type React from "react";
import { usePoll } from "@/features/poll/client";
-import { InviteDialog } from "@/features/poll/components/invite-dialog";
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 type { PollInviteListItem } from "@/features/poll/invite/types";
import { Trans } from "@/i18n/client";
-const AdminControls = () => {
+const AdminControls = ({ invites }: { invites: PollInviteListItem[] }) => {
return (
<div className="flex items-center gap-x-2">
<NotificationToggle />
<ManagePoll />
- <InviteDialog />
+ <ShareDialog invites={invites} />
</div>
);
};
-const Layout = ({ children }: React.PropsWithChildren) => {
+const Layout = ({
+ children,
+ invites,
+}: React.PropsWithChildren<{ invites: PollInviteListItem[] }>) => {
const poll = usePoll();
const pollLink = `/poll/${poll.id}`;
const pathname = usePathname();
@@ -67,7 +71,7 @@ const Layout = ({ children }: React.PropsWithChildren) => {
</Breadcrumb>
</div>
<div>
- <AdminControls />
+ <AdminControls invites={invites} />
</div>
</div>
</div>
@@ -78,7 +82,10 @@ const Layout = ({ children }: React.PropsWithChildren) => {
);
};
-export const PollLayout = ({ children }: React.PropsWithChildren) => {
+export const PollLayout = ({
+ children,
+ invites,
+}: React.PropsWithChildren<{ invites: PollInviteListItem[] }>) => {
const params = useParams();
const urlId = params?.urlId as string;
@@ -90,7 +97,7 @@ export const PollLayout = ({ children }: React.PropsWithChildren) => {
return (
<LegacyPollContextProvider>
- <Layout>{children}</Layout>
+ <Layout invites={invites}>{children}</Layout>
</LegacyPollContextProvider>
);
};
diff --git a/apps/web/src/features/poll/components/share-dialog.tsx b/apps/web/src/features/poll/components/share-dialog.tsx
new file mode 100644
index 000000000..7031afb82
--- /dev/null
+++ b/apps/web/src/features/poll/components/share-dialog.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { posthog } from "@rallly/posthog/client";
+import { Button } from "@rallly/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ useDialog,
+} from "@rallly/ui/dialog";
+import { Separator } from "@rallly/ui/separator";
+import { Share2Icon } from "lucide-react";
+import React from "react";
+import { useIsFree } from "@/features/billing/client";
+import { usePoll } from "@/features/poll/client";
+import { InviteByEmail } from "@/features/poll/components/invite-by-email";
+import { InviteLinkRow } from "@/features/poll/components/invite-link-row";
+import type { PollInviteListItem } from "@/features/poll/invite/types";
+import { Trans } from "@/i18n/client";
+
+export function ShareDialog({ invites }: { invites: PollInviteListItem[] }) {
+ const poll = usePoll();
+ const dialog = useDialog();
+ const isFree = useIsFree();
+ const isOpen = dialog.dialogProps.open;
+
+ React.useEffect(() => {
+ if (!isOpen) return;
+ posthog?.capture("poll_share:dialog_open", {
+ poll_id: poll.id,
+ tier: isFree ? "free" : "pro",
+ });
+ }, [isOpen, poll.id, isFree]);
+
+ return (
+ <>
+ <Button variant="primary" {...dialog.triggerProps}>
+ <Share2Icon data-icon="inline-start" />
+ <span className="sr-only sm:not-sr-only">
+ <Trans i18nKey="share" defaults="Share" />
+ </span>
+ </Button>
+ <Dialog {...dialog.dialogProps}>
+ <DialogContent size="lg" data-testid="invite-participant-dialog">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="share" defaults="Share" />
+ </DialogTitle>
+ <DialogDescription>
+ <Trans
+ i18nKey="shareDialogDescription"
+ defaults="Share the invite link, or invite people by email."
+ />
+ </DialogDescription>
+ </DialogHeader>
+ <InviteLinkRow inviteLink={poll.inviteLink} />
+ <Separator />
+ <InviteByEmail invites={invites} />
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/apps/web/src/features/poll/invite/actions.ts b/apps/web/src/features/poll/invite/actions.ts
new file mode 100644
index 000000000..ed74d2cf4
--- /dev/null
+++ b/apps/web/src/features/poll/invite/actions.ts
@@ -0,0 +1,48 @@
+"use server";
+
+import { hasPollAdminAccess } from "@/features/poll/data";
+import { sendPollInvite } from "@/features/poll/invite/mutations";
+import { sendPollInviteSchema } from "@/features/poll/invite/schema";
+import { AppError } from "@/lib/errors/app-error";
+import { track } from "@/lib/posthog";
+import {
+ authActionClient,
+ createRateLimitMiddleware,
+} from "@/lib/safe-action/server";
+
+export const sendPollInviteAction = authActionClient
+ .metadata({ actionName: "send_poll_invite" })
+ // One email per call; the daily recipient cap lives in the mutation.
+ .use(createRateLimitMiddleware(30, "1 m"))
+ .inputSchema(sendPollInviteSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { pollId, email } = parsedInput;
+
+ if (!(await hasPollAdminAccess(pollId, ctx.user.id))) {
+ throw new AppError({ code: "NOT_FOUND", message: "Poll not found" });
+ }
+
+ const result = await sendPollInvite({ pollId, userId: ctx.user.id, email });
+
+ if (!result.ok && result.reason === "paymentRequired") {
+ throw new AppError({
+ code: "PAYMENT_REQUIRED",
+ message: "Email invites require a Pro subscription",
+ });
+ }
+
+ track(
+ { id: ctx.user.id, isGuest: false },
+ {
+ event: "poll_share:invite_send",
+ properties: {
+ poll_id: pollId,
+ ok: result.ok,
+ reason: result.ok ? undefined : result.reason,
+ },
+ groups: { poll: pollId },
+ },
+ );
+
+ return result;
+ });
diff --git a/apps/web/src/features/poll/invite/constants.ts b/apps/web/src/features/poll/invite/constants.ts
new file mode 100644
index 000000000..75a7f7b07
--- /dev/null
+++ b/apps/web/src/features/poll/invite/constants.ts
@@ -0,0 +1,3 @@
+// Per user, across all their polls, rolling 24h. Per poll caps don't stop
+// multi poll spam; this one does.
+export const MAX_POLL_INVITES_PER_DAY = 100;
diff --git a/apps/web/src/features/poll/invite/data.ts b/apps/web/src/features/poll/invite/data.ts
new file mode 100644
index 000000000..68249a00c
--- /dev/null
+++ b/apps/web/src/features/poll/invite/data.ts
@@ -0,0 +1,22 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+
+/**
+ * Non revoked invites for a poll, newest first. Revoked rows are kept in the
+ * table so their tokens still resolve, but they have no UI surface here.
+ * Callers prove poll access before calling.
+ */
+export async function listPollInvites({ pollId }: { pollId: string }) {
+ return prisma.pollInvite.findMany({
+ where: { pollId, revokedAt: null },
+ select: {
+ id: true,
+ email: true,
+ openedAt: true,
+ participantId: true,
+ createdAt: true,
+ },
+ orderBy: { createdAt: "desc" },
+ });
+}
diff --git a/apps/web/src/features/poll/invite/loaders.ts b/apps/web/src/features/poll/invite/loaders.ts
new file mode 100644
index 000000000..dc46cb106
--- /dev/null
+++ b/apps/web/src/features/poll/invite/loaders.ts
@@ -0,0 +1,31 @@
+import "server-only";
+
+import { cache } from "react";
+import { hasPollAdminAccess } from "@/features/poll/data";
+import { listPollInvites } from "@/features/poll/invite/data";
+import type { PollInviteListItem } from "@/features/poll/invite/types";
+import { derivePollInviteStatus } from "@/features/poll/invite/utils";
+import { getCurrentUser } from "@/features/user/loaders";
+
+/**
+ * The invites a viewer may see for a poll. Guests and non-admins get an
+ * empty list rather than a redirect: the poll page renders for them and the
+ * share dialog hides the email section itself.
+ */
+export const loadPollInvites = cache(
+ async (pollId: string): Promise<PollInviteListItem[]> => {
+ const user = await getCurrentUser();
+
+ if (!user || !(await hasPollAdminAccess(pollId, user.id))) {
+ return [];
+ }
+
+ const invites = await listPollInvites({ pollId });
+
+ return invites.map((invite) => ({
+ id: invite.id,
+ email: invite.email,
+ status: derivePollInviteStatus(invite),
+ }));
+ },
+);
diff --git a/apps/web/src/features/poll/invite/mutations.ts b/apps/web/src/features/poll/invite/mutations.ts
new file mode 100644
index 000000000..fcd823113
--- /dev/null
+++ b/apps/web/src/features/poll/invite/mutations.ts
@@ -0,0 +1,262 @@
+import "server-only";
+
+import { Prisma, prisma } from "@rallly/database";
+import { sendPollInviteEmail } from "@rallly/emails/templates/poll-invite";
+import { createLogger } from "@rallly/logger";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { customAlphabet } from "nanoid";
+import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
+import { resolveSpaceTier } from "@/features/billing/utils";
+import { recordPollActivities } from "@/features/poll/activity/mutations";
+import { MAX_POLL_INVITES_PER_DAY } from "@/features/poll/invite/constants";
+
+const logger = createLogger("poll/invite/mutations");
+
+// Alphanumeric only: url safe with no linkifier edge cases. 32 chars is the
+// floor documented on PollInvite.token.
+const generateInviteToken = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 32,
+);
+
+class InviteClaimedElsewhere extends Error {}
+
+export type SendPollInviteResult =
+ | { ok: true; invite: { id: string; email: string } }
+ | {
+ ok: false;
+ reason:
+ | "notFound"
+ | "pollClosed"
+ | "paymentRequired"
+ | "dailyLimit"
+ | "alreadyResponded"
+ | "alreadyInvited"
+ | "sendFailed";
+ };
+
+export async function sendPollInvite({
+ pollId,
+ userId,
+ email,
+}: {
+ pollId: string;
+ userId: string;
+ email: string;
+}): Promise<SendPollInviteResult> {
+ const [poll, sender] = await Promise.all([
+ prisma.poll.findFirst({
+ where: { id: pollId, deleted: false },
+ select: {
+ title: true,
+ status: true,
+ space: {
+ select: {
+ tier: true,
+ showBranding: true,
+ hideAttribution: true,
+ primaryColor: true,
+ image: true,
+ },
+ },
+ },
+ }),
+ prisma.user.findUnique({
+ where: { id: userId },
+ select: { name: true, locale: true },
+ }),
+ ]);
+
+ if (!poll || !sender) {
+ return { ok: false, reason: "notFound" };
+ }
+
+ if (poll.status !== "open") {
+ return { ok: false, reason: "pollClosed" };
+ }
+
+ if (resolveSpaceTier(poll.space?.tier ?? "hobby") !== "pro") {
+ return { ok: false, reason: "paymentRequired" };
+ }
+
+ // Counted against the sender, not the poll owner, so a co-member on a
+ // shared space poll spends their own quota. The activity log records who
+ // sent what; a failed send deletes its event, so it does not count.
+ const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
+ const sentToday = await prisma.pollActivity.count({
+ where: { type: "invite_sent", userId, createdAt: { gte: since } },
+ });
+
+ if (sentToday >= MAX_POLL_INVITES_PER_DAY) {
+ return { ok: false, reason: "dailyLimit" };
+ }
+
+ // Participant.email is plain text, so the match is made insensitive here;
+ // PollInvite.email is citext and its unique index handles it.
+ const participant = await prisma.participant.findFirst({
+ where: {
+ pollId,
+ deleted: false,
+ email: { equals: email, mode: "insensitive" },
+ },
+ select: { id: true },
+ });
+
+ if (participant) {
+ return { ok: false, reason: "alreadyResponded" };
+ }
+
+ const existing = await prisma.pollInvite.findUnique({
+ where: { pollId_email: { pollId, email } },
+ select: { id: true, revokedAt: true, participantId: true },
+ });
+
+ // A converted invite belongs to the response now, regardless of
+ // revokedAt: reactivating it here would clear revokedAt and rotate the
+ // token on a row that still points at a participant.
+ if (existing?.participantId) {
+ return { ok: false, reason: "alreadyResponded" };
+ }
+
+ if (existing && existing.revokedAt === null) {
+ return { ok: false, reason: "alreadyInvited" };
+ }
+
+ const token = generateInviteToken();
+
+ // A reactivated invite keeps its id and gains a second invite_sent event,
+ // so the rollback below must only touch events from this attempt.
+ const attemptStartedAt = new Date();
+
+ let invite: { id: string; email: string };
+ try {
+ invite = await prisma.$transaction(async (tx) => {
+ let row: { id: string; email: string };
+ if (existing) {
+ // A revoked row is reactivated with a fresh token so a leaked old
+ // link never regains access. The claim only succeeds while the row
+ // is still revoked, so two concurrent sends cannot both take it.
+ const { count } = await tx.pollInvite.updateMany({
+ where: { id: existing.id, revokedAt: { not: null } },
+ data: { revokedAt: null, token },
+ });
+ if (count === 0) {
+ throw new InviteClaimedElsewhere();
+ }
+ row = { id: existing.id, email };
+ } else {
+ row = await tx.pollInvite.create({
+ data: { pollId, email, token },
+ select: { id: true, email: true },
+ });
+ }
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "invite_sent",
+ userId,
+ inviteId: row.id,
+ payload: { email: row.email },
+ },
+ ]);
+
+ return row;
+ });
+ } catch (error) {
+ // A concurrent send for the same poll/email either claimed the revoked
+ // row first or raced the unique index on create.
+ if (
+ error instanceof InviteClaimedElsewhere ||
+ (error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002")
+ ) {
+ return { ok: false, reason: "alreadyInvited" };
+ }
+ throw error;
+ }
+
+ try {
+ await sendPollInviteEmail({
+ to: email,
+ locale: sender.locale ?? "en",
+ branding: poll.space
+ ? await getSpaceBranding(poll.space)
+ : await getInstanceBranding(),
+ props: {
+ hostName: sender.name,
+ pollTitle: poll.title,
+ inviteUrl: absoluteUrl(`/invite/${pollId}?invite=${token}`),
+ },
+ });
+ } catch (error) {
+ logger.error(
+ { error, pollId, inviteId: invite.id },
+ "Failed to send poll invite email",
+ );
+ // Undo the row and its activity so the list never shows an invite that
+ // was never delivered. A reactivated row goes back to revoked.
+ try {
+ await prisma.$transaction(async (tx) => {
+ await tx.pollActivity.deleteMany({
+ where: {
+ pollId,
+ inviteId: invite.id,
+ type: "invite_sent",
+ userId,
+ createdAt: { gte: attemptStartedAt },
+ },
+ });
+ // Matching the token as well as the id leaves a later send that
+ // re-rotated the row alone.
+ if (existing) {
+ await tx.pollInvite.updateMany({
+ where: { id: invite.id, token },
+ data: { revokedAt: new Date() },
+ });
+ } else {
+ await tx.pollInvite.deleteMany({ where: { id: invite.id, token } });
+ }
+ });
+ } catch (rollbackError) {
+ logger.error(
+ { error: rollbackError, pollId, inviteId: invite.id },
+ "Failed to roll back undelivered poll invite",
+ );
+ }
+ return { ok: false, reason: "sendFailed" };
+ }
+
+ return { ok: true, invite };
+}
+
+/**
+ * Joins a new response to the invite it answers, so the host's list flips
+ * from Sent to Responded. Only the token from the emailed link counts as
+ * proof: a typed address is unverified, so matching on it would let anyone
+ * claim someone else's invite. Runs inside the response's transaction so the
+ * join commits with the participant.
+ */
+export async function attachParticipantToInvite(
+ tx: Prisma.TransactionClient,
+ {
+ pollId,
+ participantId,
+ inviteToken,
+ }: {
+ pollId: string;
+ participantId: string;
+ inviteToken?: string;
+ },
+) {
+ if (!inviteToken) {
+ return false;
+ }
+
+ const { count } = await tx.pollInvite.updateMany({
+ where: { pollId, participantId: null, revokedAt: null, token: inviteToken },
+ data: { participantId },
+ });
+
+ return count > 0;
+}
diff --git a/apps/web/src/features/poll/invite/schema.ts b/apps/web/src/features/poll/invite/schema.ts
new file mode 100644
index 000000000..84cc09976
--- /dev/null
+++ b/apps/web/src/features/poll/invite/schema.ts
@@ -0,0 +1,8 @@
+import * as z from "zod";
+
+export const sendPollInviteSchema = z.object({
+ pollId: z.string().min(1),
+ // Normalized before validation so " [email protected] " matches the
+ // citext unique index the same way the stored row does.
+ email: z.string().trim().toLowerCase().pipe(z.email()),
+});
diff --git a/apps/web/src/features/poll/invite/types.ts b/apps/web/src/features/poll/invite/types.ts
new file mode 100644
index 000000000..c0011da68
--- /dev/null
+++ b/apps/web/src/features/poll/invite/types.ts
@@ -0,0 +1,7 @@
+import type { PollInviteStatus } from "@/features/poll/invite/utils";
+
+export type PollInviteListItem = {
+ id: string;
+ email: string;
+ status: PollInviteStatus;
+};
diff --git a/apps/web/src/features/poll/invite/utils.test.ts b/apps/web/src/features/poll/invite/utils.test.ts
new file mode 100644
index 000000000..4994e9711
--- /dev/null
+++ b/apps/web/src/features/poll/invite/utils.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { derivePollInviteStatus } from "./utils";
+
+describe("derivePollInviteStatus", () => {
+ it("is sent when nothing has happened", () => {
+ expect(
+ derivePollInviteStatus({ openedAt: null, participantId: null }),
+ ).toBe("sent");
+ });
+
+ it("is opened once the invite link was followed", () => {
+ expect(
+ derivePollInviteStatus({
+ openedAt: new Date("2026-09-03T10:00:00Z"),
+ participantId: null,
+ }),
+ ).toBe("opened");
+ });
+
+ it("is responded once a participant is joined, even without an open", () => {
+ expect(
+ derivePollInviteStatus({ openedAt: null, participantId: "p1" }),
+ ).toBe("responded");
+ });
+
+ it("responded wins over opened", () => {
+ expect(
+ derivePollInviteStatus({
+ openedAt: new Date("2026-09-03T10:00:00Z"),
+ participantId: "p1",
+ }),
+ ).toBe("responded");
+ });
+});
diff --git a/apps/web/src/features/poll/invite/utils.ts b/apps/web/src/features/poll/invite/utils.ts
new file mode 100644
index 000000000..8084eda30
--- /dev/null
+++ b/apps/web/src/features/poll/invite/utils.ts
@@ -0,0 +1,19 @@
+export type PollInviteStatus = "sent" | "opened" | "responded";
+
+/**
+ * Revoked invites are filtered out by the read, so they never reach here.
+ * Responding always consumes the invite, so a joined participant outranks an
+ * open that may or may not have happened first.
+ */
+export function derivePollInviteStatus(invite: {
+ openedAt: Date | null;
+ participantId: string | null;
+}): PollInviteStatus {
+ if (invite.participantId) {
+ return "responded";
+ }
+ if (invite.openedAt) {
+ return "opened";
+ }
+ return "sent";
+}
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index bb41a7d7a..011ffd32d 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -13,6 +13,7 @@ import { getNotificationRecipient } from "@/features/notifications/data";
import { createUnsubscribeToken } from "@/features/notifications/utils";
import { recordPollActivities } from "@/features/poll/activity/mutations";
import { hasPollAdminAccess } from "@/features/poll/data";
+import { attachParticipantToInvite } from "@/features/poll/invite/mutations";
import { AppError } from "@/lib/errors/app-error";
import { track } from "@/lib/posthog";
import {
@@ -300,6 +301,7 @@ export const participants = router({
email: z.string().optional(),
note: responseNoteInput,
timeZone: z.string().optional(),
+ inviteToken: z.string().optional(),
votes: z
.object({
optionId: z.string(),
@@ -311,7 +313,7 @@ export const participants = router({
.mutation(
async ({
ctx,
- input: { pollId, votes, name, email, note, timeZone },
+ input: { pollId, votes, name, email, note, timeZone, inviteToken },
}) => {
const participantCount = await prisma.participant.count({
where: {
@@ -346,69 +348,77 @@ export const participants = router({
existingOptionIds.has(optionId),
);
- const participant = await prisma.$transaction(async (tx) => {
- const participant = await tx.participant.create({
- data: {
- pollId: pollId,
- name: name,
- email,
- note,
- timeZone,
- userId: ctx.user.id,
- locale: ctx.locale,
- votes: {
- createMany: {
- data: validVotes.map(({ optionId, type }) => ({
- pollId,
- optionId,
- type,
- })),
+ const { participant, viaInvite } = await prisma.$transaction(
+ async (tx) => {
+ const participant = await tx.participant.create({
+ data: {
+ pollId: pollId,
+ name: name,
+ email,
+ note,
+ timeZone,
+ userId: ctx.user.id,
+ locale: ctx.locale,
+ votes: {
+ createMany: {
+ data: validVotes.map(({ optionId, type }) => ({
+ pollId,
+ optionId,
+ type,
+ })),
+ },
},
},
- },
- include: {
- votes: {
- select: {
- optionId: true,
- type: true,
+ include: {
+ votes: {
+ select: {
+ optionId: true,
+ type: true,
+ },
},
- },
- user: {
- select: {
- image: true,
+ user: {
+ select: {
+ image: true,
+ },
},
- },
- poll: {
- select: {
- id: true,
- title: true,
- space: {
- select: {
- id: true,
- tier: true,
- showBranding: true,
- hideAttribution: true,
- primaryColor: true,
- image: true,
+ poll: {
+ select: {
+ id: true,
+ title: true,
+ space: {
+ select: {
+ id: true,
+ tier: true,
+ showBranding: true,
+ hideAttribution: true,
+ primaryColor: true,
+ image: true,
+ },
},
},
},
},
- },
- });
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_created",
+ userId: ctx.user.id,
+ participantId: participant.id,
+ payload: { name: participant.name },
+ },
+ ]);
- await recordPollActivities(tx, [
- {
+ const viaInvite = await attachParticipantToInvite(tx, {
pollId,
- type: "response_created",
- userId: ctx.user.id,
participantId: participant.id,
- payload: { name: participant.name },
- },
- ]);
+ inviteToken,
+ });
- return participant;
- });
+ return { participant, viaInvite };
+ },
+ );
const totalResponses = participantCount + 1;
@@ -455,6 +465,7 @@ export const participants = router({
space_id: participant.poll.space?.id,
tier: participant.poll.space?.tier,
has_email: !!email,
+ via_invite: viaInvite,
has_note: !!participant.note,
note_length: participant.note?.length,
total_responses: totalResponses,
diff --git a/apps/web/tests/email-invites.spec.ts b/apps/web/tests/email-invites.spec.ts
new file mode 100644
index 000000000..be649d02e
--- /dev/null
+++ b/apps/web/tests/email-invites.spec.ts
@@ -0,0 +1,148 @@
+// apps/web/tests/email-invites.spec.ts
+import type { Browser } from "@playwright/test";
+import { expect, test } from "@playwright/test";
+import { prisma } from "@rallly/database";
+import { captureOne, deleteAllMessages } from "@rallly/test-helpers";
+import { InvitePage } from "./invite-page";
+import { NewPollPage } from "./new-poll-page";
+import {
+ createUserInDb,
+ loginWithEmail,
+ upgradeSpaceToPro,
+} from "./test-utils";
+
+/**
+ * The Share dialog sends one email invite per submit and lists every invite
+ * with its status. Free hosts see the pay wall instead of sending.
+ */
+
+const PRO_HOST = "[email protected]";
+const FREE_HOST = "[email protected]";
+const INVITEE = "[email protected]";
+const POLL_TITLE = "Email Invites Poll";
+
+test.describe.configure({ mode: "serial" });
+
+async function cleanup() {
+ await prisma.user.deleteMany({
+ where: { email: { in: [PRO_HOST, FREE_HOST] } },
+ });
+}
+
+async function respondAsGuest(
+ browser: Browser,
+ inviteUrl: string,
+ name: string,
+) {
+ const context = await browser.newContext();
+ try {
+ const guestPage = await context.newPage();
+ await guestPage.goto(inviteUrl.replace(/&amp;/g, "&"));
+ await new InvitePage(guestPage).addParticipant(name);
+ } finally {
+ await context.close();
+ }
+}
+
+test.describe("Email invites", () => {
+ test.beforeAll(async () => {
+ await cleanup();
+ await deleteAllMessages();
+ });
+
+ test.afterAll(async () => {
+ await cleanup();
+ });
+
+ test("pro host sends, sees status, and is stopped on duplicates", async ({
+ page,
+ }) => {
+ const user = await createUserInDb({ email: PRO_HOST, name: "Pro Host" });
+ const space = await prisma.space.findFirstOrThrow({
+ where: { ownerId: user.id },
+ });
+ await upgradeSpaceToPro({ spaceId: space.id, userId: user.id, seats: 1 });
+
+ await loginWithEmail(page, { email: PRO_HOST });
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ const created = await newPollPage.create({ name: POLL_TITLE });
+ await created.goToPollPage();
+ await deleteAllMessages();
+
+ await page.getByRole("button", { name: "Share" }).click();
+ const dialog = page.getByRole("dialog", { name: "Share" });
+ await expect(dialog.getByRole("button", { name: "Copy" })).toBeVisible();
+
+ const field = dialog.getByLabel("Email address");
+ await field.fill(INVITEE);
+ await field.press("Enter");
+
+ const row = dialog.getByRole("listitem").filter({ hasText: INVITEE });
+ await expect(row).toBeVisible();
+ await expect(row.getByText("Sent")).toBeVisible();
+ await expect(
+ dialog.getByRole("heading", { name: "1 invited" }),
+ ).toBeVisible();
+
+ const { email } = await captureOne(INVITEE);
+ expect(email.Subject).toBe(
+ `Pro Host invited you to respond to ${POLL_TITLE}`,
+ );
+ expect(email.HTML).toContain("/invite/");
+ expect(email.HTML).toContain("?invite=");
+
+ // Same address again is refused without sending.
+ await field.fill(INVITEE);
+ await field.press("Enter");
+ await expect(page.getByText(`${INVITEE} is already invited`)).toBeVisible();
+ await expect(
+ dialog.getByRole("heading", { name: "1 invited" }),
+ ).toBeVisible();
+
+ // Responding through the emailed link joins the response to the invite.
+ const inviteUrl = email.HTML.match(
+ /href="([^"]*\/invite\/[^"]*invite=[^"]*)"/,
+ )?.[1];
+ expect(inviteUrl).toBeTruthy();
+ const browser = page.context().browser();
+ expect(browser).toBeTruthy();
+ await respondAsGuest(
+ browser as Browser,
+ inviteUrl as string,
+ "Invited Guest",
+ );
+
+ await page.reload();
+ await page.getByRole("button", { name: "Share" }).click();
+ const reopened = page.getByRole("dialog", { name: "Share" });
+ const respondedRow = reopened
+ .getByRole("listitem")
+ .filter({ hasText: INVITEE });
+ await expect(respondedRow.getByText("Responded")).toBeVisible();
+ });
+
+ test("free host sees the pay wall and nothing is sent", async ({ page }) => {
+ await createUserInDb({ email: FREE_HOST, name: "Free Host" });
+ await loginWithEmail(page, { email: FREE_HOST });
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ const created = await newPollPage.create({ name: `${POLL_TITLE} Free` });
+ await created.goToPollPage();
+
+ await page.getByRole("button", { name: "Share" }).click();
+ const dialog = page.getByRole("dialog", { name: "Share" });
+ const sendButton = dialog.getByRole("button", { name: /Send invite/ });
+ await expect(sendButton).toBeEnabled();
+ await expect(sendButton.getByText("Pro")).toBeVisible();
+
+ await dialog.getByLabel("Email address").fill(INVITEE);
+ await sendButton.click();
+
+ await expect(page.getByText("Select plan:")).toBeVisible();
+ const count = await prisma.pollInvite.count({
+ where: { email: INVITEE, poll: { title: `${POLL_TITLE} Free` } },
+ });
+ expect(count).toBe(0);
+ });
+});
diff --git a/apps/web/tests/poll-page.ts b/apps/web/tests/poll-page.ts
index 3af99a132..5bbac93d2 100644
--- a/apps/web/tests/poll-page.ts
+++ b/apps/web/tests/poll-page.ts
@@ -41,8 +41,8 @@ export class PollPage {
}
async copyInviteLink() {
- this.openShareDialog();
- await this.page.getByRole("button", { name: "invite/" }).click();
+ const dialog = await this.openShareDialog();
+ await dialog.getByRole("button", { name: "Copy" }).click();
return (await this.page.evaluate(
"navigator.clipboard.readText()",
)) as string;
diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.json
index 781ba7293..8147aab25 100644
--- a/packages/emails/locales/en/emails.json
+++ b/packages/emails/locales/en/emails.json
@@ -81,6 +81,11 @@
"passwordAdded_preview": "A password was added to your account",
"passwordAdded_subject": "A password was added to your account",
"passwordAdded_text": "You can now sign in with your email address and password.",
+ "pollInvite_button": "Respond",
+ "pollInvite_content": "<b>{hostName}</b> is finding a time for <b>{pollTitle}</b> and wants to know when you're available.",
+ "pollInvite_heading": "You're invited",
+ "pollInvite_preview": "{hostName} wants to know when you're available",
+ "pollInvite_subject": "{hostName} invited you to respond to {pollTitle}",
"register_codeValid": "This code is valid for 15 minutes",
"register_heading": "Verify your email address",
"register_preview": "Your 6-digit code is: {code}",
diff --git a/packages/emails/src/templates/poll-invite.tsx b/packages/emails/src/templates/poll-invite.tsx
new file mode 100644
index 000000000..4e05581d8
--- /dev/null
+++ b/packages/emails/src/templates/poll-invite.tsx
@@ -0,0 +1,111 @@
+import { Head, Hr, Html, Img, Preview } from "@react-email/components";
+import { Trans } from "react-i18next/TransWithoutContext";
+
+import { resolveChrome } from "../chrome";
+import { PoweredBy } from "../components/powered-by";
+import { previewChrome } from "../components/preview-chrome";
+import {
+ Body,
+ Button,
+ Container,
+ Heading,
+ Text,
+} from "../components/styled-components";
+import { createEmailI18n } from "../i18n";
+import type { SendArgs } from "../send";
+import { sendRenderedEmail } from "../send";
+import type { EmailChrome } from "../types";
+
+export type PollInviteEmailProps = {
+ locale?: string;
+ chrome: EmailChrome;
+ hostName: string;
+ pollTitle: string;
+ inviteUrl: string;
+};
+
+async function PollInviteEmail({
+ hostName,
+ pollTitle,
+ inviteUrl,
+ locale = "en",
+ chrome,
+}: PollInviteEmailProps) {
+ const { t, i18n } = await createEmailI18n(locale);
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {t("pollInvite_preview", {
+ defaultValue: "{hostName} wants to know when you're available",
+ hostName,
+ })}
+ </Preview>
+ <Body>
+ <Container>
+ <Img
+ src={chrome.logoUrl}
+ height="42"
+ style={{ marginBottom: 32, borderRadius: 6 }}
+ alt={chrome.appName}
+ />
+ <Heading>
+ {t("pollInvite_heading", { defaultValue: "You're invited" })}
+ </Heading>
+ <Text>
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="emails"
+ i18nKey="pollInvite_content"
+ defaults="<b>{hostName}</b> is finding a time for <b>{pollTitle}</b> and wants to know when you're available."
+ values={{ hostName, pollTitle }}
+ components={{ b: <strong /> }}
+ />
+ </Text>
+ <Button href={inviteUrl} id="inviteUrl" color={chrome.primaryColor}>
+ {t("pollInvite_button", { defaultValue: "Respond" })}
+ </Button>
+ <Hr style={{ margin: "16px 0" }} />
+ <PoweredBy chrome={chrome} locale={locale} />
+ </Container>
+ </Body>
+ </Html>
+ );
+}
+
+PollInviteEmail.PreviewProps = {
+ hostName: "Jessie Smith",
+ pollTitle: "Team offsite dates",
+ inviteUrl: "https://rallly.co/invite/abc123?invite=token",
+ locale: "en",
+ chrome: previewChrome,
+} as PollInviteEmailProps;
+
+export default PollInviteEmail;
+
+export async function sendPollInviteEmail({
+ to,
+ locale = "en",
+ branding,
+ props,
+ ...rest
+}: SendArgs<PollInviteEmailProps>) {
+ const { t } = await createEmailI18n(locale);
+ await sendRenderedEmail({
+ to,
+ subject: t("pollInvite_subject", {
+ defaultValue: "{hostName} invited you to respond to {pollTitle}",
+ hostName: props.hostName,
+ pollTitle: props.pollTitle,
+ }),
+ element: (
+ <PollInviteEmail
+ {...props}
+ locale={locale}
+ chrome={resolveChrome(branding)}
+ />
+ ),
+ ...rest,
+ });
+}