Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Record when an invite link is opened (#3163)
Luke Vellaaff24c001db2
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/page.tsxindex ea6975925..430693ea3 100644--- a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx+++ b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx@@ -7,6 +7,7 @@ import { cache } from "react";import { SessionRefresher } from "@/components/session-refresher";import { loadFooterLinks } from "@/features/instance-settings/loaders";import { PermissionProvider } from "@/features/poll/client";+import { InviteOpenRecorder } from "@/features/poll/invite/components/invite-open-recorder";import { UserProvider } from "@/features/user/client";import { getLocale } from "@/i18n/server/get-locale";import { getSession } from "@/lib/auth";@@ -41,7 +42,7 @@ const getPollMetadata = cache(async (urlId: string) => {export default async function Page(props: {params: Promise<{ urlId: string }>;- searchParams: Promise<{ token?: string }>;+ searchParams: Promise<{ token?: string; invite?: string }>;}) {const params = await props.params;@@ -49,7 +50,7 @@ export default async function Page(props: {const trpc = await createPublicSSRHelper();- const token = (await props.searchParams).token;+ const { token, invite: inviteToken } = await props.searchParams;const [locale, session, deviceDateTimeConfig, footerLinks] =await Promise.all([@@ -73,6 +74,9 @@ export default async function Page(props: {return (<HydrationBoundary state={dehydrate(trpc.queryClient)}><SessionRefresher />+ {inviteToken ? (+ <InviteOpenRecorder pollId={params.urlId} token={inviteToken} />+ ) : null}<UserProvider user={session?.user ?? null}><DeviceDateTimeProviderlocale={locale}diff --git a/apps/web/src/features/poll/invite/actions.ts b/apps/web/src/features/poll/invite/actions.tsindex ed74d2cf4..be0ce5b75 100644--- a/apps/web/src/features/poll/invite/actions.ts+++ b/apps/web/src/features/poll/invite/actions.ts@@ -1,11 +1,18 @@"use server";import { hasPollAdminAccess } from "@/features/poll/data";-import { sendPollInvite } from "@/features/poll/invite/mutations";-import { sendPollInviteSchema } from "@/features/poll/invite/schema";+import {+ recordPollInviteOpen,+ sendPollInvite,+} from "@/features/poll/invite/mutations";+import {+ recordPollInviteOpenSchema,+ sendPollInviteSchema,+} from "@/features/poll/invite/schema";import { AppError } from "@/lib/errors/app-error";import { track } from "@/lib/posthog";import {+ actionClient,authActionClient,createRateLimitMiddleware,} from "@/lib/safe-action/server";@@ -46,3 +53,12 @@ export const sendPollInviteAction = authActionClientreturn result;});++// Public: invitees are not users, and the token from the emailed link is the+// credential. The mutation ignores tokens it does not recognise.+export const recordPollInviteOpenAction = actionClient+ .metadata({ actionName: "record_poll_invite_open" })+ .inputSchema(recordPollInviteOpenSchema)+ .action(async ({ parsedInput }) => {+ await recordPollInviteOpen(parsedInput);+ });diff --git a/apps/web/src/features/poll/invite/components/invite-open-recorder.tsx b/apps/web/src/features/poll/invite/components/invite-open-recorder.tsxnew file mode 100644index 000000000..87a5336a1--- /dev/null+++ b/apps/web/src/features/poll/invite/components/invite-open-recorder.tsx@@ -0,0 +1,23 @@+"use client";++import * as React from "react";+import { recordPollInviteOpenAction } from "@/features/poll/invite/actions";++/**+ * Records that an emailed invite link was followed. Fired from the client so+ * that mail scanners fetching the link ahead of the reader never count as an+ * open. Renders nothing.+ */+export function InviteOpenRecorder({+ pollId,+ token,+}: {+ pollId: string;+ token: string;+}) {+ React.useEffect(() => {+ recordPollInviteOpenAction({ pollId, token });+ }, [pollId, token]);++ return null;+}diff --git a/apps/web/src/features/poll/invite/mutations.ts b/apps/web/src/features/poll/invite/mutations.tsindex fcd823113..4513a6de6 100644--- a/apps/web/src/features/poll/invite/mutations.ts+++ b/apps/web/src/features/poll/invite/mutations.ts@@ -260,3 +260,55 @@ export async function attachParticipantToInvite(return count > 0;}++/**+ * Marks an invite as opened the first time its emailed link is followed.+ * The token is the only credential, so an unknown, revoked or converted+ * token is a no-op rather than an error. First open wins: the claim on+ * `openedAt IS NULL` also serialises concurrent opens of the same link, so+ * the activity event is written exactly once.+ */+export async function recordPollInviteOpen({+ pollId,+ token,+}: {+ pollId: string;+ token: string;+}) {+ return prisma.$transaction(async (tx) => {+ const invite = await tx.pollInvite.findFirst({+ where: {+ pollId,+ token,+ revokedAt: null,+ participantId: null,+ openedAt: null,+ },+ select: { id: true, email: true },+ });++ if (!invite) {+ return false;+ }++ const { count } = await tx.pollInvite.updateMany({+ where: { id: invite.id, openedAt: null },+ data: { openedAt: new Date() },+ });++ if (count === 0) {+ return false;+ }++ await recordPollActivities(tx, [+ {+ pollId,+ type: "invite_opened",+ inviteId: invite.id,+ payload: { email: invite.email },+ },+ ]);++ return true;+ });+}diff --git a/apps/web/src/features/poll/invite/schema.ts b/apps/web/src/features/poll/invite/schema.tsindex 84cc09976..51f4a020a 100644--- a/apps/web/src/features/poll/invite/schema.ts+++ b/apps/web/src/features/poll/invite/schema.ts@@ -6,3 +6,8 @@ export const sendPollInviteSchema = z.object({// citext unique index the same way the stored row does.email: z.string().trim().toLowerCase().pipe(z.email()),});++export const recordPollInviteOpenSchema = z.object({+ pollId: z.string().min(1),+ token: z.string().min(1),+});diff --git a/apps/web/tests/email-invites.spec.ts b/apps/web/tests/email-invites.spec.tsindex 080376399..050ac772b 100644--- a/apps/web/tests/email-invites.spec.ts+++ b/apps/web/tests/email-invites.spec.ts@@ -1,5 +1,5 @@// apps/web/tests/email-invites.spec.ts-import type { Browser } from "@playwright/test";+import type { Browser, Page } from "@playwright/test";import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import { captureOne, deleteAllMessages } from "@rallly/test-helpers";@@ -29,19 +29,23 @@ async function cleanup() {});}-async function respondAsGuest(- browser: Browser,- inviteUrl: string,- name: string,-) {+async function openAsGuest(browser: Browser, inviteUrl: string) {const context = await browser.newContext();- try {- const guestPage = await context.newPage();- await guestPage.goto(inviteUrl.replace(/&/g, "&"));- await new InvitePage(guestPage).addParticipant(name);- } finally {- await context.close();- }+ const guestPage = await context.newPage();+ await guestPage.goto(inviteUrl.replace(/&/g, "&"));+ return { guestPage, close: () => context.close() };+}++async function reopenShareDialog(page: Page) {+ // Load the poll page without the post-creation `share` param: the dialog+ // strips it with a raw replaceState the router does not track, and a+ // router refresh (dev HMR, revalidation) can bring it back before a+ // reload, which would reopen the dialog and block the Share button.+ const url = new URL(page.url());+ url.searchParams.delete("share");+ await page.goto(url.toString());+ await page.getByRole("button", { name: "Share" }).click();+ return page.getByRole("dialog", { name: "Share" });}test.describe("Email invites", () => {@@ -94,28 +98,64 @@ test.describe("Email invites", () => {// Same address again is refused without sending.await field.fill(INVITEE);await field.press("Enter");- await expect(page.getByText(`${INVITEE} is already invited`)).toBeVisible();+ // Scoped to the dialog: the same message also lands in a toast.+ await expect(+ dialog.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.+ // Opening the emailed link records the open once: a second visit+ // neither moves the timestamp nor adds another activity event.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",- );+ const guest = await openAsGuest(browser as Browser, inviteUrl as string);+ const invite = await prisma.pollInvite.findFirstOrThrow({+ where: { email: INVITEE, poll: { title: POLL_TITLE } },+ select: { id: true },+ });+ await expect+ .poll(async () => {+ const row = await prisma.pollInvite.findUniqueOrThrow({+ where: { id: invite.id },+ select: { openedAt: true },+ });+ return row.openedAt;+ })+ .not.toBeNull();+ const { openedAt } = await prisma.pollInvite.findUniqueOrThrow({+ where: { id: invite.id },+ select: { openedAt: true },+ });- await page.reload();- await page.getByRole("button", { name: "Share" }).click();- const reopened = page.getByRole("dialog", { name: "Share" });- const respondedRow = reopened+ await guest.guestPage.reload();+ await expect(guest.guestPage.getByText(POLL_TITLE)).toBeVisible();++ const openedRow = (await reopenShareDialog(page))+ .getByRole("listitem")+ .filter({ hasText: INVITEE });+ await expect(openedRow.getByText("Opened")).toBeVisible();+ const reread = await prisma.pollInvite.findUniqueOrThrow({+ where: { id: invite.id },+ select: { openedAt: true },+ });+ expect(reread.openedAt).toEqual(openedAt);+ expect(+ await prisma.pollActivity.count({+ where: { inviteId: invite.id, type: "invite_opened" },+ }),+ ).toBe(1);++ // Responding through the emailed link joins the response to the invite.+ await new InvitePage(guest.guestPage).addParticipant("Invited Guest");+ await guest.close();++ const respondedRow = (await reopenShareDialog(page)).getByRole("listitem").filter({ hasText: INVITEE });await expect(respondedRow.getByText("Responded")).toBeVisible();