Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Send confirmation email after RSVP submission (#2647)
Luke Vella34c355070529
diff --git a/apps/web/src/features/scheduled-event/actions.ts b/apps/web/src/features/scheduled-event/actions.tsindex b1e0936d4..9ffeff48b 100644--- a/apps/web/src/features/scheduled-event/actions.ts+++ b/apps/web/src/features/scheduled-event/actions.ts@@ -1,16 +1,35 @@"use server";+import { sendEventRsvpConfirmationEmail } from "@rallly/emails/templates/event-rsvp-confirmation";+import { createLogger } from "@rallly/logger";import { headers } from "next/headers";+import { after } from "next/server";import * as z from "zod";+import { getSpaceBranding } from "@/emails/branding";+import { parseConferencing } from "@/features/conferencing/data";+import { getConferencingUri } from "@/features/conferencing/utils";+import { parseLocation } from "@/features/location/data";+import { formatLocationText } from "@/features/location/utils";import {getEventAcceptedCount,getPublicScheduledEvent,+ getScheduledEventRsvpEmailData,} from "@/features/scheduled-event/data";import { cancelRsvp, createRsvp } from "@/features/scheduled-event/mutations";-import { getEventPhase, isEventFull } from "@/features/scheduled-event/utils";+import {+ formatEventDateTime,+ getEventPhase,+ isEventFull,+} from "@/features/scheduled-event/utils";+import { getLocale } from "@/i18n/server/get-locale";import { authLib, getSession } from "@/lib/auth";+import { getDeviceDateTimeConfig } from "@/lib/datetime/server";+import type { TimeFormat } from "@/lib/datetime/types";import { AppError } from "@/lib/errors/app-error";import { actionClient, authActionClient } from "@/lib/safe-action/server";+import { createIcsEvent } from "@/lib/utils/ics";++const logger = createLogger("scheduled-event");// Re-validates the registration gate server-side — never trust that the client// only offered registration when the event was actually open.@@ -42,6 +61,120 @@ async function assertRegistrationOpen(eventId: string) {}}+// Runs inside `after()` so the form response never waits on it. A missing+// event or a failed ICS build downgrades gracefully — the email still goes+// out, just without the attachment.+async function sendRsvpConfirmation({+ eventId,+ name,+ email,+ status,+ locale,+ timeZone,+ timeFormat,+}: {+ eventId: string;+ name: string;+ email: string;+ status: "accepted" | "declined";+ locale: string;+ timeZone?: string;+ timeFormat?: TimeFormat;+}) {+ const event = await getScheduledEventRsvpEmailData(eventId);++ if (!event) {+ return;+ }++ const location = parseLocation(event.location, {+ scheduledEventId: event.id,+ });+ const conferencing = parseConferencing(event.conferencing, {+ scheduledEventId: event.id,+ });+ const locationText = location ? formatLocationText(location) : undefined;+ const conferencingUri = conferencing+ ? getConferencingUri(conferencing)+ : undefined;++ const descriptionParts: string[] = [];+ if (event.description) {+ descriptionParts.push(event.description);+ }+ if (conferencingUri) {+ descriptionParts.push(conferencingUri);+ }++ const icsEvent = createIcsEvent({+ uid: event.uid,+ sequence: event.sequence,+ title: event.title,+ description:+ descriptionParts.length > 0 ? descriptionParts.join("\n\n") : undefined,+ location: locationText ?? conferencingUri,+ start: event.start,+ end: event.end,+ allDay: event.allDay,+ timeZone: event.timeZone ?? undefined,+ organizer: {+ name: event.user.name,+ email: event.user.email,+ },+ attendees: [+ {+ name,+ email,+ partstat: status === "accepted" ? "ACCEPTED" : "DECLINED",+ },+ ],+ method: "request",+ status: "CONFIRMED",+ });++ if (icsEvent.error) {+ logger.error(+ { error: icsEvent.error, eventId },+ "Failed to generate RSVP confirmation ICS",+ );+ }++ const { day, dow, date, time } = formatEventDateTime({+ start: event.start,+ end: event.end,+ allDay: event.allDay,+ timeZone: event.timeZone,+ inviteeTimeZone: timeZone,+ locale,+ timeFormat,+ });++ await sendEventRsvpConfirmationEmail({+ to: email,+ locale,+ branding: await getSpaceBranding(event.space),+ ...(icsEvent.value+ ? {+ icalEvent: {+ filename: "invite.ics",+ method: "request" as const,+ content: icsEvent.value,+ },+ }+ : {}),+ props: {+ title: event.title,+ hostName: event.user.name,+ response: status,+ day,+ dow,+ date,+ time,+ location: locationText ?? conferencingUri,+ },+ });+}+export const submitRsvpAction = actionClient.metadata({ actionName: "submit_rsvp" }).inputSchema(@@ -71,7 +204,38 @@ export const submitRsvpAction = actionClientinviteeId = user.id;}- return await createRsvp({ eventId, name, email, status, inviteeId });+ // Request APIs are unavailable inside after(), so resolve the invitee's+ // locale and zone here and pass them through.+ const [locale, { timeZone, timeFormat }] = await Promise.all([+ getLocale(),+ getDeviceDateTimeConfig(),+ ]);++ const result = await createRsvp({+ eventId,+ name,+ email,+ status,+ inviteeId,+ locale,+ timeZone,+ });++ if (result.ok) {+ after(() =>+ sendRsvpConfirmation({+ eventId,+ name,+ email,+ status,+ locale,+ timeZone,+ timeFormat,+ }),+ );+ }++ return result;});export const registerForEventAction = authActionClient@@ -82,13 +246,36 @@ export const registerForEventAction = authActionClientawait assertRegistrationOpen(eventId);- return await createRsvp({+ const [locale, { timeZone, timeFormat }] = await Promise.all([+ getLocale(),+ getDeviceDateTimeConfig(),+ ]);++ const result = await createRsvp({eventId,name: ctx.user.name,email: ctx.user.email,status: "accepted",inviteeId: ctx.user.id,+ locale,+ timeZone,});++ if (result.ok) {+ after(() =>+ sendRsvpConfirmation({+ eventId,+ name: ctx.user.name,+ email: ctx.user.email,+ status: "accepted",+ locale,+ timeZone,+ timeFormat,+ }),+ );+ }++ return result;});export const cancelRsvpAction = actionClientdiff --git a/apps/web/src/features/scheduled-event/data.ts b/apps/web/src/features/scheduled-event/data.tsindex c32a6485b..308c2f2a7 100644--- a/apps/web/src/features/scheduled-event/data.ts+++ b/apps/web/src/features/scheduled-event/data.ts@@ -32,6 +32,31 @@ export function getPublicScheduledEvent(id: string) {});}+// Everything the RSVP confirmation email needs: ICS identity (uid/sequence),+// event details, the host as organizer, and the space's branding fields.+export function getScheduledEventRsvpEmailData(eventId: string) {+ return prisma.scheduledEvent.findUnique({+ where: { id: eventId },+ select: {+ id: true,+ uid: true,+ sequence: true,+ title: true,+ description: true,+ location: true,+ conferencing: true,+ start: true,+ end: true,+ allDay: true,+ timeZone: true,+ user: { select: { name: true, email: true } },+ space: {+ select: { showBranding: true, primaryColor: true, image: true },+ },+ },+ });+}+// Live count of accepted registrations. Kept separate from the event read so// the (stable) event can be cached while this churns on every RSVP, and so the// capacity gate always sees a fresh count.diff --git a/apps/web/src/features/scheduled-event/mutations.ts b/apps/web/src/features/scheduled-event/mutations.tsindex 0e9eb0132..d65993dba 100644--- a/apps/web/src/features/scheduled-event/mutations.ts+++ b/apps/web/src/features/scheduled-event/mutations.ts@@ -12,6 +12,8 @@ export async function createRsvp({email,status,inviteeId,+ locale,+ timeZone,}: {eventId: string;name: string;@@ -19,6 +21,10 @@ export async function createRsvp({status: Extract<ScheduledEventInviteStatus, "accepted" | "declined">;// Links the registration to a user account when the registrant is logged in.inviteeId?: string;+ // Captured at registration time so later emails (confirmation, cancellation)+ // can render in the invitee's language and zone.+ locale?: string;+ timeZone?: string;}) {let invite: { uid: string };try {@@ -32,6 +38,8 @@ export async function createRsvp({inviteeName: name,inviteeEmail: email,inviteeId,+ inviteeLocale: locale,+ inviteeTimeZone: timeZone,status,},select: { uid: true },diff --git a/apps/web/src/lib/utils/ics.ts b/apps/web/src/lib/utils/ics.tsindex 1a2ed0f18..f9b562068 100644--- a/apps/web/src/lib/utils/ics.ts+++ b/apps/web/src/lib/utils/ics.ts@@ -19,6 +19,7 @@ export interface CreateIcsEventOptions {attendees?: Array<{name: string;email: string;+ partstat?: ics.ParticipationStatus;}>;method?: "request" | "publish" | "cancel";status?: ics.EventStatus;diff --git a/apps/web/tests/rsvp-confirmation-email.spec.ts b/apps/web/tests/rsvp-confirmation-email.spec.tsnew file mode 100644index 000000000..2e514e296--- /dev/null+++ b/apps/web/tests/rsvp-confirmation-email.spec.ts@@ -0,0 +1,174 @@+import type { Page } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import {+ captureOne,+ deleteAllMessages,+ getAttachmentText,+ getMessages,+} from "@rallly/test-helpers";++/**+ * The public event page sends the invitee a confirmation email after they+ * register, with an .ics attachment whose PARTSTAT reflects their response.+ * These tests drive the real registration form and assert on the email that+ * lands in mailpit, plus the invite row the action wrote.+ */++const HOST_EMAIL = "[email protected]";+const EVENT_ID = "rsvp-email-event";+const EVENT_UID = "rsvp-email-event-uid";+const EVENT_TITLE = "RSVP Email Test Event";++// Next year, September to dodge DST in the seeded zone.+const YEAR = new Date().getFullYear() + 1;+const EVENT_START = new Date(`${YEAR}-09-10T16:00:00.000Z`);+const EVENT_END = new Date(`${YEAR}-09-10T17:00:00.000Z`);++async function seed() {+ await cleanup();++ const user = await prisma.user.create({+ data: {+ email: HOST_EMAIL,+ name: "RSVP Email Host",+ locale: "en",+ timeZone: "Europe/London",+ emailVerified: true,+ },+ });++ const space = await prisma.space.create({+ data: { name: "RSVP Email Space", ownerId: user.id, tier: "hobby" },+ });++ await prisma.scheduledEvent.create({+ data: {+ id: EVENT_ID,+ uid: EVENT_UID,+ userId: user.id,+ spaceId: space.id,+ title: EVENT_TITLE,+ timeZone: "Europe/London",+ location: { provider: "custom", address: "100 Fish Street, London" },+ start: EVENT_START,+ end: EVENT_END,+ allDay: false,+ },+ });+}++async function cleanup() {+ await prisma.scheduledEvent.deleteMany({ where: { id: EVENT_ID } });+ await prisma.user.deleteMany({ where: { email: HOST_EMAIL } });+}++async function register(+ page: Page,+ { name, email }: { name: string; email: string },+) {+ await page.goto(`/e/${EVENT_ID}`);+ await page.getByRole("button", { name: "Register" }).click();+ await page.getByLabel("Name").fill(name);+ await page.getByLabel("Email").fill(email);+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Register" })+ .click();+}++test.describe("RSVP confirmation email", () => {+ test.beforeEach(async () => {+ await seed();+ await deleteAllMessages();+ });++ test.afterAll(async () => {+ await cleanup();+ await deleteAllMessages();+ });++ test("sends a confirmation email with an accepted .ics after registering", async ({+ browser,+ }) => {+ const context = await browser.newContext({+ locale: "en-US",+ timezoneId: "America/New_York",+ });+ const page = await context.newPage();+ const email = "[email protected]";++ await register(page, { name: "Attendee One", email });++ // Confirmation of success in the UI before we look at the email.+ await expect(page.getByText("You're registered")).toBeVisible();++ const { email: message } = await captureOne(email);+ expect(message.Subject).toBe(`You responded to ${EVENT_TITLE}`);+ // Body copy names the response, the event, and the host. (The heading is+ // upper-cased in the plaintext render, so assert on the sentence instead.)+ expect(message.Text).toContain(+ `You accepted the invitation to ${EVENT_TITLE}`,+ );+ expect(message.Text).toContain("RSVP Email Host");++ // Exactly one .ics attachment, and its PARTSTAT matches the response.+ expect(message.Attachments).toHaveLength(1);+ const part = message.Attachments[0];+ expect(part.FileName).toBe("invite.ics");+ // Unfold RFC 5545 continuation lines ("\r\n " / "\r\n\t") so long values+ // like the attendee mailto aren't split mid-token.+ const ics = (await getAttachmentText(message.ID, part.PartID)).replace(+ /\r?\n[ \t]/g,+ "",+ );+ expect(ics).toContain("METHOD:request");+ expect(ics).toContain(`UID:${EVENT_UID}`);+ expect(ics).toContain('PARTSTAT="ACCEPTED"');+ expect(ics).toContain(`mailto:${email}`);++ // The action persisted the invitee's locale and zone for future emails.+ const invite = await prisma.scheduledEventInvite.findFirstOrThrow({+ where: { scheduledEventId: EVENT_ID, inviteeEmail: email },+ });+ expect(invite.status).toBe("accepted");+ expect(invite.inviteeLocale).toBe("en");+ expect(invite.inviteeTimeZone).toBe("America/New_York");++ await context.close();+ });++ test("does not send a second email when the same email registers twice", async ({+ browser,+ }) => {+ const email = "[email protected]";++ // First registration, from its own session.+ const firstContext = await browser.newContext({ locale: "en-US" });+ const firstPage = await firstContext.newPage();+ await register(firstPage, { name: "Attendee Two", email });+ await expect(firstPage.getByText("You're registered")).toBeVisible();+ await captureOne(email); // first email arrives+ await firstContext.close();++ await deleteAllMessages();++ // A second, unrelated visitor tries the same email. (A fresh context: the+ // first session would render as already-registered and hide the form.)+ const secondContext = await browser.newContext({ locale: "en-US" });+ const secondPage = await secondContext.newPage();+ await register(secondPage, { name: "Someone Else", email });+ await expect(+ secondPage.getByText("This email has already been used to respond"),+ ).toBeVisible();++ // Give any (incorrectly-fired) after() email time to land, then assert none.+ await secondPage.waitForTimeout(2000);+ const { messages } = await getMessages();+ expect(+ messages.filter((m) => m.To.some((t) => t.Address === email)),+ ).toHaveLength(0);++ await secondContext.close();+ });+});diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.jsonindex 202dc9061..5f1be0935 100644--- a/packages/emails/locales/en/emails.json+++ b/packages/emails/locales/en/emails.json@@ -13,6 +13,14 @@"eventCanceledHeading": "Event canceled","eventCanceledPreview": "Event canceled","eventCanceledSubject": "Canceled: {title}",+ "eventRsvpConfirmationAcceptedContent": "You accepted the invitation to <b>{title}</b> hosted by <b>{hostName}</b>. The event is scheduled for:",+ "eventRsvpConfirmationAcceptedHeading": "You're going",+ "eventRsvpConfirmationAcceptedPreview": "You accepted {title}",+ "eventRsvpConfirmationAttachmentNote": "Please find attached a calendar invite for this event.",+ "eventRsvpConfirmationDeclinedContent": "You declined the invitation to <b>{title}</b> hosted by <b>{hostName}</b>. The event is scheduled for:",+ "eventRsvpConfirmationDeclinedHeading": "Response received",+ "eventRsvpConfirmationDeclinedPreview": "You declined {title}",+ "eventRsvpConfirmationSubject": "You responded to {title}","finalizeHost_button": "View Event","finalizeHost_content": "<b>{title}</b> has been booked for:","finalizeHost_content2": "We've notified participants and sent them calendar invites.",diff --git a/packages/emails/src/templates/event-rsvp-confirmation.tsx b/packages/emails/src/templates/event-rsvp-confirmation.tsxnew file mode 100644index 000000000..8ffa4528a--- /dev/null+++ b/packages/emails/src/templates/event-rsvp-confirmation.tsx@@ -0,0 +1,207 @@+import {+ Column,+ Head,+ Hr,+ Html,+ Img,+ Preview,+ Row,+ Section,+} 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,+ borderColor,+ 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 EventRsvpConfirmationEmailProps = {+ locale?: string;+ chrome: EmailChrome;+ title: string;+ hostName: string;+ response: "accepted" | "declined";+ day: string;+ dow: string;+ date: string;+ time?: string;+ location?: string;+};++async function EventRsvpConfirmationEmail({+ title,+ hostName,+ response,+ day,+ dow,+ date,+ time,+ location,+ locale = "en",+ chrome,+}: EventRsvpConfirmationEmailProps) {+ const { t, i18n } = await createEmailI18n(locale);+ return (+ <Html>+ <Head />+ <Preview>+ {response === "accepted"+ ? t("eventRsvpConfirmationAcceptedPreview", {+ defaultValue: "You accepted {title}",+ title,+ })+ : t("eventRsvpConfirmationDeclinedPreview", {+ defaultValue: "You declined {title}",+ title,+ })}+ </Preview>+ <Body>+ <Container>+ <Img+ src={chrome.logoUrl}+ height="42"+ style={{ marginBottom: 32, borderRadius: 6 }}+ alt={chrome.appName}+ />+ <Heading>+ {response === "accepted"+ ? t("eventRsvpConfirmationAcceptedHeading", {+ defaultValue: "You're going",+ })+ : t("eventRsvpConfirmationDeclinedHeading", {+ defaultValue: "Response received",+ })}+ </Heading>+ <Text>+ {response === "accepted" ? (+ <Trans+ t={t}+ i18n={i18n}+ ns="emails"+ i18nKey="eventRsvpConfirmationAcceptedContent"+ defaults="You accepted the invitation to <b>{title}</b> hosted by <b>{hostName}</b>. The event is scheduled for:"+ values={{ hostName, title }}+ components={{+ b: <strong />,+ }}+ />+ ) : (+ <Trans+ t={t}+ i18n={i18n}+ ns="emails"+ i18nKey="eventRsvpConfirmationDeclinedContent"+ defaults="You declined the invitation to <b>{title}</b> hosted by <b>{hostName}</b>. The event is scheduled for:"+ values={{ hostName, title }}+ components={{+ b: <strong />,+ }}+ />+ )}+ </Text>+ <Section data-testid="date-section">+ <Row>+ <Column style={{ width: 48 }}>+ <Section+ style={{+ borderRadius: 5,+ margin: 0,+ width: 48,+ height: 48,+ textAlign: "center",+ border: `1px solid ${borderColor}`,+ }}+ >+ <Text+ style={{ margin: "0 0 4px 0", fontSize: 10, lineHeight: 1 }}+ >+ {dow}+ </Text>+ <Text+ style={{+ fontSize: 20,+ lineHeight: 1,+ fontWeight: "bold",+ margin: 0,+ }}+ >+ {day}+ </Text>+ </Section>+ </Column>+ <Column style={{ paddingLeft: 16 }} align="left">+ <Text style={{ margin: 0, fontWeight: "bold" }}>{date}</Text>+ <Text light={true} style={{ margin: 0 }}>+ {time ?? t("allDay", { defaultValue: "All day" })}+ </Text>+ </Column>+ </Row>+ </Section>+ {location ? (+ <Text light={true} style={{ margin: "8px 0 0 0" }}>+ {location}+ </Text>+ ) : null}+ <Text>+ {t("eventRsvpConfirmationAttachmentNote", {+ defaultValue:+ "Please find attached a calendar invite for this event.",+ })}+ </Text>+ <Hr style={{ margin: "16px 0" }} />+ <PoweredBy chrome={chrome} locale={locale} />+ </Container>+ </Body>+ </Html>+ );+}++EventRsvpConfirmationEmail.PreviewProps = {+ title: "Team Offsite",+ hostName: "Host",+ response: "accepted",+ day: "12",+ dow: "Fri",+ date: "Friday, 12th June 2020",+ time: "6:00 PM to 11:00 PM BST",+ location: "Codfather, 100 Fish Street, London",+ locale: "en",+ chrome: previewChrome,+} as EventRsvpConfirmationEmailProps;++export default EventRsvpConfirmationEmail;++export async function sendEventRsvpConfirmationEmail({+ to,+ locale = "en",+ branding,+ props,+ ...rest+}: SendArgs<EventRsvpConfirmationEmailProps>) {+ const { t } = await createEmailI18n(locale);+ await sendRenderedEmail({+ to,+ subject: t("eventRsvpConfirmationSubject", {+ defaultValue: "You responded to {title}",+ title: props.title,+ }),+ element: (+ <EventRsvpConfirmationEmail+ {...props}+ locale={locale}+ chrome={resolveChrome(branding)}+ />+ ),+ ...rest,+ });+}diff --git a/packages/test-helpers/src/index.ts b/packages/test-helpers/src/index.tsindex 5beecb409..24c2bbd66 100644--- a/packages/test-helpers/src/index.ts+++ b/packages/test-helpers/src/index.ts@@ -4,6 +4,7 @@ export {captureEmailHTML,captureOne,deleteAllMessages,+ getAttachmentText,getMessage,getMessages,type MailpitAttachment,diff --git a/packages/test-helpers/src/mailpit.ts b/packages/test-helpers/src/mailpit.tsindex c1a21a808..93bb63aeb 100644--- a/packages/test-helpers/src/mailpit.ts+++ b/packages/test-helpers/src/mailpit.ts@@ -28,9 +28,12 @@ export interface MailpitMessageSummary {To: MailpitEmailAddress[];}-export interface MailpitMessage extends MailpitMessageSummary {+export interface MailpitMessage+ extends Omit<MailpitMessageSummary, "Attachments"> {HTML: string;Text: string;+ // The full-message endpoint returns attachment objects, not the summary's count.+ Attachments: MailpitAttachment[];Inline: MailpitAttachment[];ReturnPath: string;Date: string;@@ -105,6 +108,16 @@ export async function captureOne(throw new Error(`No email received for ${to} within ${timeout}ms`);}+export async function getAttachmentText(+ messageId: string,+ partId: string,+): Promise<string> {+ const response = await fetch(+ `${MAILPIT_API_URL}/v1/message/${messageId}/part/${partId}`,+ );+ return await response.text();+}+export async function captureEmailHTML(to: string): Promise<string> {const { email } = await captureOne(to);if (!email.HTML) {