From 43f3328dab19fe115a46cc9a4ef36d31b5919ce4 Mon Sep 17 00:00:00 2001 From: Kuutti Niku <206612000+sleeeski@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:09:01 +0300 Subject: [PATCH 1/2] Add calendar options and registration email invitations Send an iCalendar invitation with registration confirmation emails and when a waitlisted registration is promoted into a place. After a successful signup, the event page shows a temporary confirmation toast (replacing the brief signup message) with Google Calendar, Microsoft 365 / Outlook, Outlook.com and .ics download options. The toast stays open once the user interacts with it and is shown once per registration. Add Swedish calendar strings. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + .../src/components/RegistrationCalendar.tsx | 162 ++++++++++++++++++ @app/client/src/pages/event/[slug]/index.tsx | 5 + .../event/[slug]/register/[quotaId]/index.tsx | 10 ++ .../src/translations/en/register_event.json | 8 + .../src/translations/fi/register_event.json | 8 + .../src/translations/se/register_event.json | 8 + @app/components/src/EventRegistrationForm.tsx | 12 +- .../e2e/create_event_registration.spec.ts | 56 ++++++ @app/lib/src/calendar.ts | 132 ++++++++++++++ @app/lib/src/index.ts | 1 + @app/server/__tests__/utils/calendar.test.ts | 98 +++++++++++ @app/worker/README.md | 24 +++ @app/worker/__tests__/calendarEmail.test.ts | 93 ++++++++++ @app/worker/__tests__/localDelivery.test.ts | 85 +++++++++ .../__tests__/registrationEmails.test.ts | 98 +++++++++++ @app/worker/email.local.example.json | 4 + @app/worker/jest.config.ts | 3 + @app/worker/src/calendarInvitation.ts | 42 +++++ @app/worker/src/localEmail.ts | 66 +++++++ .../src/tasks/registration__process_queue.ts | 15 +- .../registration__send_confirmation_email.ts | 30 ++-- @app/worker/src/tasks/send_email.ts | 18 +- @app/worker/src/transport.ts | 41 +++-- .../templates/event_registration.mjml.njk | 14 ++ @app/worker/tsconfig.json | 2 +- 26 files changed, 998 insertions(+), 38 deletions(-) create mode 100644 @app/client/src/components/RegistrationCalendar.tsx create mode 100644 @app/lib/src/calendar.ts create mode 100644 @app/server/__tests__/utils/calendar.test.ts create mode 100644 @app/worker/__tests__/calendarEmail.test.ts create mode 100644 @app/worker/__tests__/localDelivery.test.ts create mode 100644 @app/worker/__tests__/registrationEmails.test.ts create mode 100644 @app/worker/email.local.example.json create mode 100644 @app/worker/jest.config.ts create mode 100644 @app/worker/src/calendarInvitation.ts create mode 100644 @app/worker/src/localEmail.ts diff --git a/.gitignore b/.gitignore index 917a71f44..a8a7201de 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,5 @@ cache .agignore *.tsbuildinfo .ethereal +/@app/worker/email.local.json .DS_Store diff --git a/@app/client/src/components/RegistrationCalendar.tsx b/@app/client/src/components/RegistrationCalendar.tsx new file mode 100644 index 000000000..5dfe24caf --- /dev/null +++ b/@app/client/src/components/RegistrationCalendar.tsx @@ -0,0 +1,162 @@ +import { useEffect, useRef, useState } from "react" +import { useIsMobile, useTranslation } from "@app/components" +import { EventPage_EventFragment } from "@app/graphql" +import { + calendarDescription, + createCalendarLinks, + createEventCalendar, +} from "@app/lib" +import { Button, message, notification, Space } from "antd" + +import type { ArgsProps } from "antd/es/notification/interface" + +const NOTIFICATION_KEY = "registration-calendar" +// Long enough to read the confirmation and reach the calendar options. +// Interacting with the toast keeps it open until the user closes it. +export const REGISTRATION_CALENDAR_DURATION_SECONDS = 12 + +export function RegistrationCalendar({ + event, +}: { + event: EventPage_EventFragment +}) { + const { t, lang } = useTranslation("register_event") + const isMobile = useIsMobile() + const [api, contextHolder] = notification.useNotification({ + placement: isMobile ? "top" : "topRight", + maxCount: 1, + }) + const [registrationId, setRegistrationId] = useState(null) + const eventRef = useRef(event) + eventRef.current = event + + useEffect(() => { + try { + const key = `registered-event:${event.id}` + const savedId = sessionStorage.getItem(key) + if (savedId) { + // Show the confirmation once; reloading the event page should not + // bring it back. + sessionStorage.removeItem(key) + setRegistrationId(savedId) + } + } catch { + // Browsers may disable storage. Registration itself still succeeds. + } + }, [event.id]) + + useEffect(() => { + if (!registrationId) return + const event = eventRef.current + const name = event.name[lang] || Object.values(event.name)[0] || "" + const description = + event.description[lang] || Object.values(event.description)[0] + const calendarEvent = { + id: event.id, + name, + location: event.location || "", + description: calendarDescription(description), + start: event.eventStartTime, + end: event.eventEndTime, + url: new URL( + `/event/${encodeURIComponent(event.slug)}`, + window.location.origin + ).href, + } + const links = createCalendarLinks(calendarEvent) + const downloadUrl = URL.createObjectURL( + new Blob([createEventCalendar(calendarEvent)], { + type: "text/calendar;charset=utf-8", + }) + ) + const status = event.registrations.nodes.find( + (registration) => registration.id === registrationId + )?.status + const emailMessage = + status === "IN_QUOTA" || status === "IN_OPEN_QUOTA" + ? "calendar.emailSent" + : status === "IN_QUEUE" + ? "calendar.waitlistEmailSent" + : "calendar.emailConfirmation" + + let pinned = false + const open = (duration: number) => + api.success({ + key: NOTIFICATION_KEY, + message: t("eventSignupComplete"), + description: content, + duration, + showProgress: duration > 0, + pauseOnHover: true, + role: "status", + props: { "data-cy": "registration-calendar" } as ArgsProps["props"], + }) + // Once the user starts using the calendar options (touch, click or + // keyboard), keep the toast open so it does not vanish mid-action. + const keepOpen = () => { + if (pinned) return + pinned = true + open(0) + } + const content = ( +
+

{t(emailMessage)}

+
+ + {t("calendar.addAnother")} + + + + + + + +
+
+ ) + + // This toast replaces the brief signup message shown by the form. + message.destroy("registration-signup-complete") + open(REGISTRATION_CALENDAR_DURATION_SECONDS) + return () => { + api.destroy(NOTIFICATION_KEY) + URL.revokeObjectURL(downloadUrl) + } + }, [api, lang, registrationId, t]) + + return contextHolder +} diff --git a/@app/client/src/pages/event/[slug]/index.tsx b/@app/client/src/pages/event/[slug]/index.tsx index 4d5918f31..d9fb6dd88 100644 --- a/@app/client/src/pages/event/[slug]/index.tsx +++ b/@app/client/src/pages/event/[slug]/index.tsx @@ -25,6 +25,8 @@ import dayjs from "dayjs" import * as NextImage from "next/image" import { useRouter } from "next/router" +import { RegistrationCalendar } from "../../../components/RegistrationCalendar" + import type { NextPage } from "next" // See SharedLayout.tsx — namespace-then-default access works around a @@ -216,6 +218,9 @@ const EventPageInner: React.FC = ({ onBack={() => router.push("/")} /> + + + { quotaId={quota?.id} // Used to delete an unfinished registration setUpdateToken={setUpdateToken} + submitAction={(registrationId) => { + try { + sessionStorage.setItem( + `registered-event:${event.id}`, + registrationId || "1" + ) + } catch { + // Storage is optional; do not interrupt a successful signup. + } + }} type="create" /> diff --git a/@app/client/src/translations/en/register_event.json b/@app/client/src/translations/en/register_event.json index ffb1a98df..8a5078532 100644 --- a/@app/client/src/translations/en/register_event.json +++ b/@app/client/src/translations/en/register_event.json @@ -1,4 +1,12 @@ { + "calendar": { + "addAnother": "Add event to calendar", + "apple": "Apple Calendar / download .ics", + "emailConfirmation": "Check your email for your registration confirmation.", + "emailSent": "We’ve emailed your confirmation and calendar invitation. It may take a moment to arrive.", + "google": "Google Calendar", + "waitlistEmailSent": "You’re currently on the waiting list. We’ll send you a confirmation email when a place becomes available for you." + }, "confirmGoBack": "Are you sure? You will lose your registration spot.", "deleteRegistration": "Delete registration", "deleteRegistrationConfirmText": "Are you sure you want to delete your registration?", diff --git a/@app/client/src/translations/fi/register_event.json b/@app/client/src/translations/fi/register_event.json index 4c439c23f..2cafe2345 100644 --- a/@app/client/src/translations/fi/register_event.json +++ b/@app/client/src/translations/fi/register_event.json @@ -1,4 +1,12 @@ { + "calendar": { + "addAnother": "Lisää tapahtuma kalenteriin", + "apple": "Apple Calendar / lataa .ics", + "emailConfirmation": "Tarkista ilmoittautumisvahvistus sähköpostistasi.", + "emailSent": "Lähetimme vahvistuksen ja kalenterikutsun sähköpostiisi. Viestin saapumisessa voi kestää hetki.", + "google": "Google Calendar", + "waitlistEmailSent": "Olet tällä hetkellä jonossa. Lähetämme sinulle vahvistusviestin, kun saat paikan tapahtumaan." + }, "confirmGoBack": "Haluatko varmasti mennä takaisin? Menetät paikkasi jonossa.", "deleteRegistration": "Poista ilmoittautuminen", "deleteRegistrationConfirmText": "Haluatko varmasti poistaa ilmoittautumisesi?", diff --git a/@app/client/src/translations/se/register_event.json b/@app/client/src/translations/se/register_event.json index f003ddc37..ec8a5243e 100644 --- a/@app/client/src/translations/se/register_event.json +++ b/@app/client/src/translations/se/register_event.json @@ -1,4 +1,12 @@ { + "calendar": { + "addAnother": "Lägg till evenemanget i kalendern", + "apple": "Apple Calendar / ladda ner .ics", + "emailConfirmation": "Kontrollera din e-post för bekräftelsen på din anmälan.", + "emailSent": "Vi har mejlat din bekräftelse och kalenderinbjudan. Det kan ta en stund innan den kommer fram.", + "google": "Google Calendar", + "waitlistEmailSent": "Du står för närvarande på väntelistan. Vi skickar en bekräftelse via e-post när en plats blir ledig för dig." + }, "confirmGoBack": "Är du säker? Du kommer att förlora din registreringsplats.", "deleteRegistration": "Ta bort registrering", "deleteRegistrationConfirmText": "Är du säker på att du vill ta bort din registrering?", diff --git a/@app/components/src/EventRegistrationForm.tsx b/@app/components/src/EventRegistrationForm.tsx index 98e46d589..6ebc34115 100644 --- a/@app/components/src/EventRegistrationForm.tsx +++ b/@app/components/src/EventRegistrationForm.tsx @@ -37,8 +37,8 @@ interface EventRegistrationFormProps { isAdmin?: boolean questions: EventPage_QuestionFragment[] formRedirect?: { pathname: string; query: { [key: string]: string } } | string - // SubmitAction is used when this form is displayed in the admin panel - submitAction?: () => void + // Runs after submission/deletion; new signups include their registration ID. + submitAction?: (registrationId?: string) => void // eventId and quotaId are used when type is "create" eventId?: string quotaId?: string @@ -168,11 +168,15 @@ export const EventRegistrationForm: React.FC = memo( ...values, updateToken, } - const { error } = await formMutation({ input }) + const { data, error } = await formMutation({ input }) if (error) throw error if (submitAction) { - submitAction() + submitAction( + type === "create" + ? data?.createRegistration?.registration?.id + : undefined + ) } if (formRedirect) { router.push(formRedirect) diff --git a/@app/e2e/cypress/e2e/create_event_registration.spec.ts b/@app/e2e/cypress/e2e/create_event_registration.spec.ts index acd49bf7e..3e6f874cc 100644 --- a/@app/e2e/cypress/e2e/create_event_registration.spec.ts +++ b/@app/e2e/cypress/e2e/create_event_registration.spec.ts @@ -1,5 +1,8 @@ /// +// Matches REGISTRATION_CALENDAR_DURATION_SECONDS in RegistrationCalendar.tsx. +const REGISTRATION_CALENDAR_DURATION_SECONDS = 12 + context("Create event registration", () => { beforeEach(() => cy.serverCommand("clearTestUsers")) beforeEach(() => cy.serverCommand("clearTestEventData")) @@ -30,6 +33,59 @@ context("Create event registration", () => { cy.url().should("equal", Cypress.env("ROOT_URL") + `/event/${event.slug}`) cy.getCy("eventpage-signups-quota-0-table").should("contain", "Etunimi") cy.getCy("eventpage-signups-quota-0-table").should("contain", "Sukunimi") + cy.getCy("registration-calendar") + .should("be.visible") + .and("contain", "Ilmoittautuminen tallennettu") + // The calendar toast replaces the brief signup message. + cy.get(".ant-message-notice").should("not.exist") + cy.getCy("registration-calendar-google").should("not.be.visible") + cy.getCy("registration-calendar-microsoft365").should("not.be.visible") + cy.getCy("registration-calendar-outlook").should("not.be.visible") + cy.getCy("registration-calendar-download").should("not.be.visible") + cy.getCy("registration-calendar-other").click() + cy.getCy("registration-calendar-google") + .should("be.visible") + .invoke("attr", "href") + .then((href) => { + const url = new URL(href!) + expect(url.hostname).to.equal("www.google.com") + expect(url.pathname).to.equal("/calendar/render") + expect(url.searchParams.get("action")).to.equal("TEMPLATE") + expect(url.searchParams.get("details")).to.contain( + `/event/${event.slug}` + ) + }) + cy.getCy("registration-calendar-outlook").should("be.visible") + cy.getCy("registration-calendar-microsoft365").should("be.visible") + cy.getCy("registration-calendar-download") + .should("have.attr", "download", `${event.slug}.ics`) + .invoke("attr", "href") + .then((href) => { + cy.window().then(async (win) => { + const response = await win.fetch(href!) + expect(response.headers.get("content-type")).to.contain( + "text/calendar" + ) + const calendar = await response.text() + expect(calendar).to.contain("BEGIN:VCALENDAR\r\n") + expect(calendar).to.contain(`UID:${event.id}@`) + expect(calendar).to.contain("DTSTART:") + expect(calendar).to.contain("DTEND:") + expect(calendar).to.contain(`/event/${event.slug}`) + expect(calendar).not.to.contain("etunimi.sukunimi@prodeko.org") + }) + }) + // Using the calendar options keeps the toast open past its timeout. + cy.wait((REGISTRATION_CALENDAR_DURATION_SECONDS + 1) * 1000) + cy.getCy("registration-calendar-google").should("be.visible") + cy.getCy("registration-calendar") + .find(".ant-notification-notice-close") + .click() + cy.getCy("registration-calendar").should("not.exist") + // The confirmation is shown once, not again on reload. + cy.reload() + cy.getCy("eventpage-quotas-card").should("be.visible") + cy.getCy("registration-calendar").should("not.exist") }) }) diff --git a/@app/lib/src/calendar.ts b/@app/lib/src/calendar.ts new file mode 100644 index 000000000..9f1b8961a --- /dev/null +++ b/@app/lib/src/calendar.ts @@ -0,0 +1,132 @@ +interface CalendarEvent { + id: string + name: string + location: string + description: string + start: string + end: string + url: string +} + +// Calendar TEXT values must not introduce new properties or components. +function escapeText(value: string) { + return value + .replace(/\\/g, "\\\\") + .replace(/\r\n|\r|\n/g, "\\n") + .replace(/;/g, "\\;") + .replace(/,/g, "\\,") +} + +function timestamp(value: string | Date) { + return new Date(value) + .toISOString() + .replace(/[-:]/g, "") + .replace(/\.\d{3}Z$/, "Z") +} + +export function createCalendarLinks(event: CalendarEvent) { + const description = [event.description, event.url] + .filter(Boolean) + .join("\n\n") + // The eventedit path can launch Android's Calendar app without passing on + // the template fields. Use the web template entry point instead. A phone's + // app-link settings can still affect how the link opens. + const google = new URL("https://www.google.com/calendar/render") + google.search = new URLSearchParams({ + action: "TEMPLATE", + text: event.name, + dates: `${timestamp(event.start)}/${timestamp(event.end)}`, + details: description, + location: event.location, + }).toString() + + const outlookParams = new URLSearchParams({ + path: "/calendar/action/compose", + rru: "addevent", + subject: event.name, + startdt: new Date(event.start).toISOString(), + enddt: new Date(event.end).toISOString(), + body: description, + location: event.location, + }).toString() + + return { + google: google.href, + outlook: `https://outlook.live.com/calendar/0/deeplink/compose?${outlookParams}`, + microsoft365: `https://outlook.office.com/calendar/0/deeplink/compose?${outlookParams}`, + } +} + +// RFC 5545 limits content lines to 75 octets, including continuation spaces. +function foldLine(line: string) { + const encoder = new TextEncoder() + let result = "" + let length = 0 + for (const character of line) { + const size = encoder.encode(character).length + if (length + size > 75) { + result += "\r\n " + length = 1 + } + result += character + length += size + } + return result +} + +export function createEventCalendar( + event: CalendarEvent, + now = new Date(), + invitation?: { organizer: string; attendee: string } +) { + const calendarAddress = (address: string) => { + if (/[\r\n]/.test(address)) + throw new Error("Invalid calendar email address") + return encodeURI(address).replace(/[;,]/g, encodeURIComponent) + } + return ( + [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//Ilmo//Event Calendar//EN", + "CALSCALE:GREGORIAN", + ...(invitation ? ["METHOD:REQUEST"] : []), + "BEGIN:VEVENT", + `UID:${escapeText(event.id)}@ilmo`, + `DTSTAMP:${timestamp(now)}`, + `DTSTART:${timestamp(event.start)}`, + `DTEND:${timestamp(event.end)}`, + `SUMMARY:${escapeText(event.name)}`, + `LOCATION:${escapeText(event.location)}`, + `DESCRIPTION:${escapeText([event.description, event.url].filter(Boolean).join("\n\n"))}`, + `URL:${event.url.replace(/[\r\n]/g, "")}`, + ...(invitation + ? [ + "SEQUENCE:0", + `ORGANIZER:mailto:${calendarAddress(invitation.organizer)}`, + `ATTENDEE;RSVP=FALSE:mailto:${calendarAddress(invitation.attendee)}`, + ] + : []), + "END:VEVENT", + "END:VCALENDAR", + ] + .map(foldLine) + .join("\r\n") + "\r\n" + ) +} + +// Event descriptions are translated Slate documents, rather than HTML. +export function calendarDescription(node: unknown): string { + if (Array.isArray(node)) return node.map(calendarDescription).join("\n") + if (!node || typeof node !== "object") return "" + if ("text" in node && typeof node.text === "string") return node.text + if ("children" in node && Array.isArray(node.children)) { + const separator = + "type" in node && + ["bulleted-list", "numbered-list"].includes(String(node.type)) + ? "\n" + : "" + return node.children.map(calendarDescription).join(separator) + } + return "" +} diff --git a/@app/lib/src/index.ts b/@app/lib/src/index.ts index d6b5b3c89..3c5ad8c8e 100644 --- a/@app/lib/src/index.ts +++ b/@app/lib/src/index.ts @@ -1,3 +1,4 @@ +export * from "./calendar" export * from "./colors" export * from "./constants" export * from "./cookies" diff --git a/@app/server/__tests__/utils/calendar.test.ts b/@app/server/__tests__/utils/calendar.test.ts new file mode 100644 index 000000000..7d4964c41 --- /dev/null +++ b/@app/server/__tests__/utils/calendar.test.ts @@ -0,0 +1,98 @@ +import { + calendarDescription, + createCalendarLinks, + createEventCalendar, +} from "../../../lib/src/calendar" + +const event = { + id: "event-123", + name: "Sitsit, syksy; 🎉", + description: "Line one\nLine two\\three", + location: "Otaniemi", + start: "2026-10-24T18:00:00+03:00", + end: "2026-10-24T22:00:00+03:00", + url: "http://192.168.1.42:5678/event/test", +} + +it("prefills Google Calendar with encoded text and UTC event times", () => { + const url = new URL(createCalendarLinks(event).google) + expect(url.origin).toBe("https://www.google.com") + expect(url.pathname).toBe("/calendar/render") + expect(url.searchParams.get("action")).toBe("TEMPLATE") + expect(url.searchParams.get("text")).toBe(event.name) + expect(url.searchParams.get("dates")).toBe( + "20261024T150000Z/20261024T190000Z" + ) + expect(url.searchParams.get("details")).toBe( + `${event.description}\n\n${event.url}` + ) + expect(url.searchParams.get("location")).toBe(event.location) +}) + +it("prefills both Outlook account types without letting text add URL parameters", () => { + const name = "Dinner & location=wrong # åäö 🎉" + const links = createCalendarLinks({ ...event, name }) + for (const [key, origin] of [ + ["outlook", "https://outlook.live.com"], + ["microsoft365", "https://outlook.office.com"], + ] as const) { + const url = new URL(links[key]) + expect(url.origin).toBe(origin) + expect(url.searchParams.get("subject")).toBe(name) + expect(url.searchParams.getAll("location")).toEqual([event.location]) + expect(url.searchParams.get("startdt")).toBe("2026-10-24T15:00:00.000Z") + expect(url.searchParams.get("enddt")).toBe("2026-10-24T19:00:00.000Z") + expect(url.searchParams.get("body")).toBe( + `${event.description}\n\n${event.url}` + ) + } +}) + +it("exports the actual event times in UTC and a stable UID", () => { + const calendar = createEventCalendar(event, new Date("2026-10-17T10:00:00Z")) + expect(calendar).toContain("DTSTART:20261024T150000Z\r\n") + expect(calendar).toContain("DTEND:20261024T190000Z\r\n") + expect(calendar).toContain("DTSTAMP:20261017T100000Z\r\n") + expect(calendar).toContain("UID:event-123@ilmo\r\n") + expect(calendar).toContain("URL:http://192.168.1.42:5678/event/test\r\n") + expect(calendar).toMatch(/END:VEVENT\r\nEND:VCALENDAR\r\n$/) +}) + +it("escapes text and prevents injected calendar properties", () => { + const calendar = createEventCalendar({ + ...event, + location: "Hall\r\nEND:VEVENT", + }) + expect(calendar).toContain("SUMMARY:Sitsit\\, syksy\\; 🎉\r\n") + expect(calendar).toContain("LOCATION:Hall\\nEND:VEVENT\r\n") + expect(calendar).toContain("Line one\\nLine two\\\\three") + expect(calendar.match(/^END:VEVENT$/gm)).toHaveLength(1) +}) + +it("folds long UTF-8 lines without splitting characters", () => { + const name = "🎉ä".repeat(100) + const calendar = createEventCalendar({ ...event, name }) + for (const line of calendar.split("\r\n")) { + expect(Buffer.byteLength(line, "utf8")).toBeLessThanOrEqual(75) + } + expect(calendar.replace(/\r\n /g, "")).toContain(`SUMMARY:${name}\r\n`) +}) + +it("converts Slate paragraphs, inline formatting and lists to plain text", () => { + expect( + calendarDescription([ + { + type: "paragraph", + children: [{ text: "Hello " }, { text: "world", bold: true }], + }, + { + type: "bulleted-list", + children: [ + { type: "list-item", children: [{ text: "One" }] }, + { type: "list-item", children: [{ text: "Two" }] }, + ], + }, + ]) + ).toBe("Hello world\nOne\nTwo") + expect(calendarDescription(null)).toBe("") +}) diff --git a/@app/worker/README.md b/@app/worker/README.md index 2b764fa24..4835f8108 100644 --- a/@app/worker/README.md +++ b/@app/worker/README.md @@ -1,5 +1,29 @@ # @app/worker +## Local delivery testing + +By default, `NODE_ENV=test` captures emails in memory and development mode uses +Ethereal, which does not deliver to real inboxes. To test actual registration +emails locally without running the app in production mode: + +1. Configure `SENDGRID_USERNAME` and `SENDGRID_API_KEY` in the local + environment. The SMTP username is normally `apikey`. The sender configured in + `@app/config/src/index.ts` must be authorized in SendGrid. +2. Copy `email.local.example.json` to `email.local.json` in this directory and + replace `allowedRecipients` with the exact email addresses you want to test. +3. Restart the worker (or `pnpm dev`) and complete a new registration using an + allowed address. Already-sent confirmations are not automatically resent. + +The local configuration is ignored by Git, production, and automated tests. +Messages to addresses outside its allowlist are skipped. Remove the file and +restart the worker to return to the normal test transport. + +Confirmed registrations and promotions from the waiting list include a calendar +invitation alongside the existing confirmation text. Waitlisted registrations do +not receive an invitation until they get a place. Calendar responses do not +change registration status in Ilmo, and later event edits/cancellations are not +currently synchronized with saved calendar entries. + It's bad practice to perform unnecessary actions during the normal request cycle as it makes our web app seem slower. It's also bad practice to have a user retry an action a few seconds later that we could handle easily on the backend for diff --git a/@app/worker/__tests__/calendarEmail.test.ts b/@app/worker/__tests__/calendarEmail.test.ts new file mode 100644 index 000000000..4df8d3937 --- /dev/null +++ b/@app/worker/__tests__/calendarEmail.test.ts @@ -0,0 +1,93 @@ +import nodemailer from "nodemailer" + +import { registrationCalendarInvitation } from "../src/calendarInvitation" +import { + getLocalEmailSettings, + localRecipientAllowed, + parseLocalEmailSettings, +} from "../src/localEmail" + +const event = { + id: "test-event", + slug: "test-event", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { + fi: [{ type: "paragraph", children: [{ text: "Tervetuloa!" }] }], + }, + location: "Otaniemi", + event_start_time: "2026-10-24T18:00:00+03:00", + event_end_time: "2026-10-24T22:00:00+03:00", +} + +it("uses a strict recipient allowlist for local delivery", () => { + const settings = parseLocalEmailSettings({ + transport: "sendgrid", + allowedRecipients: ["Tester@example.com"], + }) + expect(localRecipientAllowed("tester@example.com", settings)).toBe(true) + expect(localRecipientAllowed(" TESTER@example.com ", settings)).toBe(true) + expect( + localRecipientAllowed(["tester@example.com", "other@example.com"], settings) + ).toBe(false) + expect( + localRecipientAllowed("tester@example.com,other@example.com", settings) + ).toBe(false) + expect(localRecipientAllowed([], settings)).toBe(false) + expect(() => + parseLocalEmailSettings({ transport: "sendgrid", allowedRecipients: [] }) + ).toThrow() + expect(() => + parseLocalEmailSettings({ + transport: "sendgrid", + allowedRecipients: ["a@example.com\nb@example.com"], + }) + ).toThrow() +}) + +it("ignores the local delivery configuration during automated tests", async () => { + expect(await getLocalEmailSettings()).toBeUndefined() +}) + +it("includes a private, correctly timed invitation without registration secrets", () => { + const invitation = registrationCalendarInvitation( + event, + "tester@example.com", + "http://192.168.1.42:5678" + ) + expect(invitation.method).toBe("REQUEST") + expect(invitation.content).toContain("METHOD:REQUEST\r\n") + expect(invitation.content).toContain("DTSTART:20261024T150000Z\r\n") + expect(invitation.content).toContain("DTEND:20261024T190000Z\r\n") + expect(invitation.content).toContain( + "ORGANIZER:mailto:no-reply@prodeko.org\r\n" + ) + expect(invitation.content).toContain( + "ATTENDEE;RSVP=FALSE:mailto:tester@example.com\r\n" + ) + expect(invitation.content).toContain("SUMMARY:Testitapahtuma\r\n") + expect(invitation.content).toContain("DESCRIPTION:Tervetuloa!") + expect(invitation.content).not.toContain("update-registration") +}) + +it("renders a real multipart email with the confirmation body and calendar part", async () => { + const transport = nodemailer.createTransport({ + streamTransport: true, + buffer: true, + }) + const result = await transport.sendMail({ + from: "no-reply@prodeko.org", + to: "tester@example.com", + subject: "Registration confirmed", + text: "Your registration was saved.", + html: "

Your registration was saved.

", + icalEvent: registrationCalendarInvitation( + event, + "tester@example.com", + "https://example.com" + ), + }) + const message = result.message.toString() + expect(message).toContain("Your registration was saved.") + expect(message).toMatch(/Content-Type: text\/calendar;[^]*?method=REQUEST/i) + expect(message).toContain("event.ics") +}) diff --git a/@app/worker/__tests__/localDelivery.test.ts b/@app/worker/__tests__/localDelivery.test.ts new file mode 100644 index 000000000..91fbd95fe --- /dev/null +++ b/@app/worker/__tests__/localDelivery.test.ts @@ -0,0 +1,85 @@ +import { getLocalEmailSettings } from "../src/localEmail" +import sendEmail from "../src/tasks/send_email" +import getTransport from "../src/transport" + +jest.mock("../src/transport", () => ({ __esModule: true, default: jest.fn() })) +jest.mock("../src/localEmail", () => ({ + ...jest.requireActual("../src/localEmail"), + getLocalEmailSettings: jest.fn(), +})) + +const sendMail = jest.fn().mockResolvedValue({ messageId: "test-message" }) + +beforeEach(() => { + jest.clearAllMocks() + jest.mocked(getLocalEmailSettings).mockResolvedValue({ + transport: "sendgrid", + allowedRecipients: ["tester@example.com"], + }) + jest.mocked(getTransport).mockResolvedValue({ sendMail } as any) +}) + +it("does not contact any transport for a recipient outside the local allowlist", async () => { + await sendEmail( + { + options: { to: "other@example.com", subject: "Test" }, + template: "", + variables: {}, + }, + {} as any + ) + expect(getTransport).not.toHaveBeenCalled() + expect(sendMail).not.toHaveBeenCalled() +}) + +it.each([false, true])( + "renders the registration email with waitlist status %s", + async (isWaitlisted) => { + const invitation = { + method: "REQUEST", + filename: "event.ics", + content: "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n", + } + await sendEmail( + { + options: { + to: "tester@example.com", + subject: "Test", + icalEvent: invitation, + }, + template: "event_registration.mjml.njk", + variables: { + isWaitlisted, + eventName: { fi: "Testitapahtuma", en: "Test event" }, + registrationName: "Test User", + registrationQuota: { fi: "Testi", en: "Test" }, + url: "https://example.com", + eventSlug: "test-event", + eventLocation: "Otaniemi", + eventTime: "24.10.26 18:00", + eventRegistrationUpdateLink: "update-registration/private-token", + }, + }, + {} as any + ) + expect(sendMail).toHaveBeenCalledTimes(1) + const message = sendMail.mock.calls[0][0] + expect(message.icalEvent).toEqual(invitation) + expect(message.html).toContain("Testitapahtuma") + expect(message.text).toContain("Test event") + expect(message.html).toContain("update-registration/private-token") + if (isWaitlisted) { + expect(message.text).toContain("Olet tällä hetkellä tapahtuman jonossa.") + expect(message.text).toContain("You're currently on the waiting list.") + expect(message.text).toContain("when a place becomes available for you.") + expect(message.text).not.toContain( + "Successfully registered to the event:" + ) + } else { + expect(message.text).toContain("Successfully registered to the event:") + expect(message.text).not.toContain( + "You're currently on the waiting list." + ) + } + } +) diff --git a/@app/worker/__tests__/registrationEmails.test.ts b/@app/worker/__tests__/registrationEmails.test.ts new file mode 100644 index 000000000..f942809fe --- /dev/null +++ b/@app/worker/__tests__/registrationEmails.test.ts @@ -0,0 +1,98 @@ +import promotion from "../src/tasks/registration__process_queue" +import confirmation from "../src/tasks/registration__send_confirmation_email" + +const event = { + id: "event", + slug: "event", + name: { en: "Test" }, + description: {}, + location: "Otaniemi", + event_start_time: "2026-10-24T15:00:00Z", + event_end_time: "2026-10-24T19:00:00Z", +} + +function helpers(status = "IN_QUOTA", finished = true) { + const registration = { + id: "registration", + event_id: "event", + quota_id: "quota", + email: "tester@example.com", + first_name: "Test", + last_name: "User", + status, + is_finished: finished, + } + return { + addJob: jest.fn().mockResolvedValue(undefined), + query: jest.fn(async (sql: string) => { + if (sql.startsWith("update")) return { rows: [] } + if (sql.includes("registration_secrets")) + return { + rows: [ + { + update_token: "private-token", + confirmation_email_sent: false, + received_spot_from_queue_email_sent: false, + }, + ], + } + if (sql.includes("app_public.registrations")) + return { rows: [registration] } + if (sql.includes("app_public.events")) return { rows: [event] } + if (sql.includes("app_public.quotas")) + return { rows: [{ title: { en: "Test quota" } }] } + throw new Error("Unexpected query") + }), + } +} + +beforeAll(() => { + process.env.ROOT_URL = "https://example.com" +}) + +it.each(["IN_QUOTA", "IN_OPEN_QUOTA"])( + "attaches an invitation to a %s confirmation", + async (status) => { + const context = helpers(status) + await confirmation({ id: "registration" }, context as any) + const payload = context.addJob.mock.calls[0][1] + expect(payload.template).toBe("event_registration.mjml.njk") + expect(payload.options.to).toBe("tester@example.com") + expect(payload.options.icalEvent.method).toBe("REQUEST") + expect(payload.variables.isWaitlisted).toBe(false) + expect(payload.variables.eventRegistrationUpdateLink).toContain( + "private-token" + ) + expect(payload.options.icalEvent.content).not.toContain("private-token") + } +) + +it("sends a waitlist confirmation without a calendar invitation", async () => { + const context = helpers("IN_QUEUE") + await confirmation({ id: "registration" }, context as any) + expect(context.addJob.mock.calls[0][1].options.icalEvent).toBeUndefined() + expect(context.addJob.mock.calls[0][1].variables.isWaitlisted).toBe(true) + expect(context.addJob.mock.calls[0][1].options.subject).toContain( + "Added to waiting list" + ) +}) + +it("does not send a confirmation for an unfinished signup", async () => { + const context = helpers("IN_QUOTA", false) + await confirmation({ id: "registration" }, context as any) + expect(context.addJob).not.toHaveBeenCalled() +}) + +it("attaches an invitation when a user receives a place from the queue", async () => { + const context = helpers() + await promotion( + { receivedSpot: { id: "registration", event_id: "event" } }, + context as any + ) + expect(context.addJob.mock.calls[0][1].template).toBe( + "spot_from_queue.mjml.njk" + ) + expect(context.addJob.mock.calls[0][1].options.icalEvent.method).toBe( + "REQUEST" + ) +}) diff --git a/@app/worker/email.local.example.json b/@app/worker/email.local.example.json new file mode 100644 index 000000000..611a608f6 --- /dev/null +++ b/@app/worker/email.local.example.json @@ -0,0 +1,4 @@ +{ + "transport": "sendgrid", + "allowedRecipients": ["your-test-address@example.com"] +} diff --git a/@app/worker/jest.config.ts b/@app/worker/jest.config.ts new file mode 100644 index 000000000..9bc2d71a8 --- /dev/null +++ b/@app/worker/jest.config.ts @@ -0,0 +1,3 @@ +module.exports = { + ...require("../../jest.config.base")(__dirname), +} diff --git a/@app/worker/src/calendarInvitation.ts b/@app/worker/src/calendarInvitation.ts new file mode 100644 index 000000000..cc5640464 --- /dev/null +++ b/@app/worker/src/calendarInvitation.ts @@ -0,0 +1,42 @@ +import { fromEmail } from "@app/config" +import { calendarDescription, createEventCalendar } from "@app/lib" + +export interface InvitationEvent { + id: string + slug: string + name: Record + description: Record + location: string + event_start_time: string | Date + event_end_time: string | Date +} + +export function registrationCalendarInvitation( + event: InvitationEvent, + recipient: string, + rootUrl: string +) { + const description = event.description || {} + return { + method: "REQUEST" as const, + filename: "event.ics", + content: createEventCalendar( + { + id: event.id, + name: event.name.fi || event.name.en || Object.values(event.name)[0], + description: calendarDescription( + description.fi || description.en || Object.values(description)[0] + ), + location: event.location || "", + start: new Date(event.event_start_time).toISOString(), + end: new Date(event.event_end_time).toISOString(), + url: new URL(`/event/${encodeURIComponent(event.slug)}`, rootUrl).href, + }, + new Date(), + { + organizer: fromEmail.match(/<([^>]+)>/)?.[1] || fromEmail, + attendee: recipient, + } + ), + } +} diff --git a/@app/worker/src/localEmail.ts b/@app/worker/src/localEmail.ts new file mode 100644 index 000000000..e3747ca0b --- /dev/null +++ b/@app/worker/src/localEmail.ts @@ -0,0 +1,66 @@ +import { promises as fs } from "node:fs" +import path from "node:path" + +export interface LocalEmailSettings { + transport: "sendgrid" + allowedRecipients: string[] +} + +export function parseLocalEmailSettings(value: unknown): LocalEmailSettings { + const settings = value as LocalEmailSettings + if ( + settings?.transport !== "sendgrid" || + !Array.isArray(settings.allowedRecipients) || + settings.allowedRecipients.length === 0 || + settings.allowedRecipients.some( + (email) => + typeof email !== "string" || !/^[^\s<>@,;]+@[^\s<>@,;]+$/.test(email) + ) + ) { + throw new Error( + "Invalid email.local.json: specify sendgrid and allowedRecipients" + ) + } + return { + transport: "sendgrid", + allowedRecipients: settings.allowedRecipients.map((email) => + email.toLowerCase() + ), + } +} + +export async function getLocalEmailSettings(): Promise< + LocalEmailSettings | undefined +> { + // A developer's delivery override must never enable real email in Jest/CI. + if ( + process.env.NODE_ENV === "production" || + process.env.JEST_WORKER_ID || + process.env.IN_TESTS === "1" + ) + return + let content: string + try { + content = await fs.readFile( + path.join(__dirname, "../email.local.json"), + "utf8" + ) + } catch (error) { + if (error.code === "ENOENT") return + throw error + } + return parseLocalEmailSettings(JSON.parse(content)) +} + +export function localRecipientAllowed( + recipient: string | string[], + settings: LocalEmailSettings +) { + const recipients = Array.isArray(recipient) ? recipient : [recipient] + return ( + recipients.length > 0 && + recipients.every((email) => + settings.allowedRecipients.includes(email.trim().toLowerCase()) + ) + ) +} diff --git a/@app/worker/src/tasks/registration__process_queue.ts b/@app/worker/src/tasks/registration__process_queue.ts index 4ad3fa686..e6830bf53 100644 --- a/@app/worker/src/tasks/registration__process_queue.ts +++ b/@app/worker/src/tasks/registration__process_queue.ts @@ -1,5 +1,8 @@ +import { registrationCalendarInvitation } from "../calendarInvitation" + import { getFormattedEventTime } from "./registration__send_confirmation_email" +import type { InvitationEvent } from "../calendarInvitation" import type { SendEmailPayload } from "./send_email" import type { RegistrationStatusAndPosition } from "@app/lib" import type { Task } from "graphile-worker" @@ -11,9 +14,8 @@ interface RegistrationProcessQueue { receivedSpot: RegistrationStatusAndPosition } -const { ROOT_URL } = process.env - const task: Task = async (inPayload, { addJob, query }) => { + const { ROOT_URL } = process.env const payload: RegistrationProcessQueue = inPayload as any const { receivedSpot } = payload @@ -39,11 +41,13 @@ const task: Task = async (inPayload, { addJob, query }) => { } = await query("select * from app_public.registrations where id = $1", [ receivedSpot.id, ]) + if (!registration || !registration.is_finished) return const { rows: [event], - } = await query("select * from app_public.events where id = $1", [ - receivedSpot.event_id, - ]) + } = await query( + "select * from app_public.events where id = $1", + [receivedSpot.event_id] + ) const { rows: [quota], } = await query("select * from app_public.quotas where id = $1", [ @@ -66,6 +70,7 @@ const task: Task = async (inPayload, { addJob, query }) => { subject: event.name.fi ? `${event.name.fi} - Olet saanut paikan jonosta` : `${event.name.en} - You have received a spot from the queue`, + icalEvent: registrationCalendarInvitation(event, email, ROOT_URL!), }, template: "spot_from_queue.mjml.njk", variables: { diff --git a/@app/worker/src/tasks/registration__send_confirmation_email.ts b/@app/worker/src/tasks/registration__send_confirmation_email.ts index 281ab9b4c..c5069f424 100644 --- a/@app/worker/src/tasks/registration__send_confirmation_email.ts +++ b/@app/worker/src/tasks/registration__send_confirmation_email.ts @@ -1,5 +1,8 @@ import dayjs from "dayjs" +import { registrationCalendarInvitation } from "../calendarInvitation" + +import type { InvitationEvent } from "../calendarInvitation" import type { SendEmailPayload } from "./send_email" import type { Task } from "graphile-worker" @@ -10,8 +13,6 @@ interface RegistrationSendConfirmationEmail { id: string } -const { ROOT_URL } = process.env - export function getFormattedEventTime(event: any) { const { event_start_time, event_end_time } = event const formatString = "D.M.YY HH:mm" @@ -21,23 +22,27 @@ export function getFormattedEventTime(event: any) { } const task: Task = async (inPayload, { addJob, query }) => { + const { ROOT_URL } = process.env const payload: RegistrationSendConfirmationEmail = inPayload as any const { id: registrationId } = payload const { rows: [registration], - } = await query("select * from app_public.registrations where id = $1", [ - registrationId, - ]) + } = await query( + "select r.*, app_public.registrations_status(r) as status from app_public.registrations r where id = $1", + [registrationId] + ) if (!registration) { console.error("Registration not found; aborting") return } + if (!registration.is_finished) return const { rows: [event], - } = await query("select * from app_public.events where id = $1", [ - registration.event_id, - ]) + } = await query( + "select * from app_public.events where id = $1", + [registration.event_id] + ) if (!event) { console.error("No event found; aborting") @@ -78,16 +83,21 @@ const task: Task = async (inPayload, { addJob, query }) => { console.error("No email specified; aborting") return } + const isWaitlisted = registration.status === "IN_QUEUE" const sendEmailPayload: SendEmailPayload = { options: { to: email, subject: event.name.fi - ? `${event.name.fi} - Rekisteröinti onnnistui` - : `${event.name.en} - Registration successful`, + ? `${event.name.fi} - ${isWaitlisted ? "Ilmoittautuminen jonoon" : "Ilmoittautuminen onnistui"}` + : `${event.name.en} - ${isWaitlisted ? "Added to waiting list" : "Registration successful"}`, + ...(["IN_QUOTA", "IN_OPEN_QUOTA"].includes(registration.status) + ? { icalEvent: registrationCalendarInvitation(event, email, ROOT_URL!) } + : {}), }, template: "event_registration.mjml.njk", variables: { + isWaitlisted, url: ROOT_URL, eventName: event.name, registrationName: `${first_name} ${last_name}`, diff --git a/@app/worker/src/tasks/send_email.ts b/@app/worker/src/tasks/send_email.ts index 308927b97..88a812830 100644 --- a/@app/worker/src/tasks/send_email.ts +++ b/@app/worker/src/tasks/send_email.ts @@ -9,6 +9,7 @@ import mjml2html from "mjml" import nodemailer from "nodemailer" import nunjucks from "nunjucks" +import { getLocalEmailSettings, localRecipientAllowed } from "../localEmail" import getTransport from "../transport" import type { Task } from "graphile-worker" @@ -31,6 +32,11 @@ export interface SendEmailPayload { from?: string to: string | string[] subject: string + icalEvent?: { + method: "REQUEST" + filename: string + content: string + } } template: string variables: { @@ -40,8 +46,15 @@ export interface SendEmailPayload { const task: Task = async (inPayload) => { const payload: SendEmailPayload = inPayload as any - const transport = await getTransport() const { options: inOptions, template, variables } = payload + const localSettings = await getLocalEmailSettings() + if (localSettings && !localRecipientAllowed(inOptions.to, localSettings)) { + console.log( + "Skipped local email: recipient is outside the delivery allowlist." + ) + return + } + const transport = await getTransport() const options = { from: fromEmail, ...inOptions, @@ -59,6 +72,9 @@ const task: Task = async (inPayload) => { Object.assign(options, { html, text }) } const info = await transport.sendMail(options) + if (localSettings) { + console.log(`Local email accepted by SendGrid: ${info.messageId}`) + } if (isTest) { global.TEST_EMAILS.push(info) } else if (isDev) { diff --git a/@app/worker/src/transport.ts b/@app/worker/src/transport.ts index 107f65320..e7449207d 100644 --- a/@app/worker/src/transport.ts +++ b/@app/worker/src/transport.ts @@ -2,6 +2,8 @@ import chalk from "chalk" import { promises as fsp } from "node:fs" import nodemailer from "nodemailer" +import { getLocalEmailSettings } from "./localEmail" + const { readFile, writeFile } = fsp const isTest = process.env.NODE_ENV === "test" @@ -15,6 +17,27 @@ let logged = false export default function getTransport(): Promise { if (!transporterPromise) { transporterPromise = (async () => { + const localSettings = await getLocalEmailSettings() + if (!isDev || localSettings?.transport === "sendgrid") { + const { SENDGRID_API_KEY, SENDGRID_USERNAME } = process.env + if (!SENDGRID_USERNAME || !SENDGRID_API_KEY) { + throw new Error("SendGrid credentials are not configured") + } + if (localSettings) { + console.log( + "Local SendGrid delivery enabled for allowed recipients only." + ) + } + return nodemailer.createTransport({ + host: "smtp.sendgrid.net", + port: 465, + secure: true, + connectionTimeout: 15000, + greetingTimeout: 15000, + socketTimeout: 30000, + auth: { user: SENDGRID_USERNAME, pass: SENDGRID_API_KEY }, + }) + } if (isTest) { return nodemailer.createTransport({ jsonTransport: true, @@ -52,24 +75,8 @@ export default function getTransport(): Promise { pass: account.pass, }, }) - } else { - const { SENDGRID_API_KEY, SENDGRID_USERNAME } = process.env - if (!SENDGRID_USERNAME) { - throw new Error("Misconfiguration: no SENDGRID_USERNAME") - } - if (!SENDGRID_API_KEY) { - throw new Error("Misconfiguration: no SENDGRID_API_KEY") - } - return nodemailer.createTransport({ - host: "smtp.sendgrid.net", - port: 465, - secure: true, - auth: { - user: SENDGRID_USERNAME, - pass: SENDGRID_API_KEY, - }, - }) } + throw new Error("Email transport is not configured") })() } return transporterPromise! diff --git a/@app/worker/templates/event_registration.mjml.njk b/@app/worker/templates/event_registration.mjml.njk index 9c7a1c708..0ff86ee4d 100644 --- a/@app/worker/templates/event_registration.mjml.njk +++ b/@app/worker/templates/event_registration.mjml.njk @@ -2,7 +2,14 @@ {% block content %} + {% if isWaitlisted %} + + Olet tällä hetkellä tapahtuman jonossa. Lähetämme sinulle vahvistusviestin, + kun saat paikan tapahtumaan. + + {% else %} Ilmoittautuminen tapahtumaan onnistui: + {% endif %} - Nimi: {{ registrationName }}
- Kiintiö: {{ registrationQuota.fi }}
@@ -18,7 +25,14 @@
+ {% if isWaitlisted %} + + You're currently on the waiting list. We'll send you a confirmation email + when a place becomes available for you. + + {% else %} Successfully registered to the event: + {% endif %} - Name: {{ registrationName }}
- Quota: {{ registrationQuota.en }}
diff --git a/@app/worker/tsconfig.json b/@app/worker/tsconfig.json index 03140d362..09ca64a09 100644 --- a/@app/worker/tsconfig.json +++ b/@app/worker/tsconfig.json @@ -11,5 +11,5 @@ "module": "commonjs" }, "include": ["src"], - "references": [{ "path": "../config" }] + "references": [{ "path": "../config" }, { "path": "../lib" }] } From 57314699b9229c803d7f75443a530a0fc0efcd3f Mon Sep 17 00:00:00 2001 From: Kuutti Niku <206612000+sleeeski@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:02:32 +0200 Subject: [PATCH 2/2] Add registration reminders with saved preferences Users can opt into reminders before event registration opens. They save delivery (email, Telegram or both) and timing once, then enable reminders for upcoming events with one click. First use guides them through preferences and Telegram linking; Settings -> My reminders lists, updates and cancels reminders. The reminder control sits in a light panel at the bottom of the quota card with a fixed layout: a status line and a full-width button that toggles in place. Setting a reminder shows a temporary toast with the delivery method, timing and a link to reminder settings. - Schedule durable Graphile Worker jobs, reschedule pending reminders when preferences or opening times change, pause drafts and cancel removed reminders. Email and Telegram track delivery separately. - Link Telegram with expiring single-use hashed tokens, authenticate production webhooks and support local polling. Telegram /language supports English, Finnish and automatic detection; email keeps the user's saved website language. - Add FI/EN/SE wording, GraphQL operations, persisted operations, schema snapshots, tests and deployment docs. Migrations 000005.sql and 000006.sql contain schema and functions only. Main's pending migrations/current files are left unchanged. Co-Authored-By: Claude Opus 5.5 --- @app/client/i18n.js | 3 +- @app/client/src/components/EventReminder.tsx | 257 +++++ .../src/components/ReminderLeadTime.tsx | 14 + .../src/components/ReminderPreferences.tsx | 161 ++++ .../src/components/TelegramConnection.tsx | 125 +++ .../reminders/RegistrationReminders.graphql | 117 +++ @app/client/src/pages/event/[slug]/index.tsx | 11 + @app/client/src/pages/settings/reminders.tsx | 186 ++++ @app/client/src/translations/en/common.json | 1 + .../client/src/translations/en/reminders.json | 70 ++ @app/client/src/translations/en/settings.json | 1 + @app/client/src/translations/fi/common.json | 1 + .../client/src/translations/fi/reminders.json | 70 ++ @app/client/src/translations/fi/settings.json | 3 +- @app/client/src/translations/se/common.json | 1 + .../client/src/translations/se/reminders.json | 70 ++ @app/client/src/translations/se/settings.json | 1 + @app/components/src/EventQuotasCard.tsx | 6 +- @app/components/src/SettingsLayout.tsx | 6 + @app/components/src/SharedLayout.tsx | 11 + .../functions/reminder_preferences.test.ts | 283 ++++++ .../set_event_registration_reminder.test.ts | 417 +++++++++ .../app_public/functions/telegram.test.ts | 365 ++++++++ .../functions/telegram_language.test.ts | 236 +++++ @app/db/migrations/committed/000005.sql | 332 +++++++ @app/db/migrations/committed/000006.sql | 52 ++ @app/db/package.json | 1 + @app/e2e/cypress/e2e/reminders.spec.ts | 87 ++ ...88a16ff6fef26f3cfd3996c81a8cdcc9ad.graphql | 36 + ...c51e1480cf01ae7fab2ec82396a11e3373.graphql | 8 + ...e820d527732ae1de883ba5469d9b040fd9.graphql | 101 ++ ...018d51bb73560ac2915bc09565a902d10e.graphql | 13 + ...b3ca75177a45ec44ebf459e8552639214b.graphql | 6 + ...5d24d12b8dfa77e280ba963dfda631dcf3.graphql | 6 + ...03adbd9765ceb023a2dfbef48540cadd94.graphql | 6 + @app/graphql/client.json | 7 + @app/graphql/server.json | 7 + @app/lib/src/telegram.ts | 140 +++ @app/lib/tsconfig.cjs.json | 2 + .../renderEmailTemplates.test.ts.snap | 336 ++++++- .../queries/renderEmailTemplates.test.ts | 4 + @app/server/__tests__/telegramPolling.test.ts | 83 ++ @app/server/__tests__/telegramWebhook.test.ts | 110 +++ @app/server/src/app.ts | 1 + @app/server/src/middleware/index.ts | 2 + .../src/middleware/installCSRFProtection.ts | 7 + .../src/middleware/installPostGraphile.ts | 3 + @app/server/src/middleware/installTelegram.ts | 46 + @app/server/src/plugins/EmailsPlugin.ts | 15 +- .../src/plugins/TelegramSettingsPlugin.ts | 19 + @app/server/src/plugins/index.ts | 2 + @app/server/src/telegram.ts | 243 +++++ @app/worker/__tests__/localDelivery.test.ts | 30 + .../__tests__/registrationReminder.test.ts | 112 +++ .../worker/__tests__/telegramReminder.test.ts | 210 +++++ @app/worker/__tests__/telegramReply.test.ts | 105 +++ .../src/tasks/reminder__send_registration.ts | 226 +++++ .../src/tasks/reminder__send_telegram.ts | 3 + @app/worker/src/tasks/telegram__reply.ts | 53 ++ .../templates/registration_reminder.mjml.njk | 16 + README.md | 3 + data/schema.graphql | 874 +++++++++++++++++- data/schema.sql | 732 +++++++++++++++ docs/registration-reminders.md | 81 ++ docs/reminder-release.md | 118 +++ docs/telegram-reminders.md | 120 +++ pnpm-lock.yaml | 3 + scripts/telegram-webhook.mjs | 32 + 68 files changed, 6794 insertions(+), 15 deletions(-) create mode 100644 @app/client/src/components/EventReminder.tsx create mode 100644 @app/client/src/components/ReminderLeadTime.tsx create mode 100644 @app/client/src/components/ReminderPreferences.tsx create mode 100644 @app/client/src/components/TelegramConnection.tsx create mode 100644 @app/client/src/graphql/reminders/RegistrationReminders.graphql create mode 100644 @app/client/src/pages/settings/reminders.tsx create mode 100644 @app/client/src/translations/en/reminders.json create mode 100644 @app/client/src/translations/fi/reminders.json create mode 100644 @app/client/src/translations/se/reminders.json create mode 100644 @app/db/__tests__/app_public/functions/reminder_preferences.test.ts create mode 100644 @app/db/__tests__/app_public/functions/set_event_registration_reminder.test.ts create mode 100644 @app/db/__tests__/app_public/functions/telegram.test.ts create mode 100644 @app/db/__tests__/app_public/functions/telegram_language.test.ts create mode 100644 @app/db/migrations/committed/000005.sql create mode 100644 @app/db/migrations/committed/000006.sql create mode 100644 @app/e2e/cypress/e2e/reminders.spec.ts create mode 100644 @app/graphql/.persisted_operations/16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad.graphql create mode 100644 @app/graphql/.persisted_operations/19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373.graphql create mode 100644 @app/graphql/.persisted_operations/36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9.graphql create mode 100644 @app/graphql/.persisted_operations/3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e.graphql create mode 100644 @app/graphql/.persisted_operations/9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b.graphql create mode 100644 @app/graphql/.persisted_operations/c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3.graphql create mode 100644 @app/graphql/.persisted_operations/d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94.graphql create mode 100644 @app/lib/src/telegram.ts create mode 100644 @app/server/__tests__/telegramPolling.test.ts create mode 100644 @app/server/__tests__/telegramWebhook.test.ts create mode 100644 @app/server/src/middleware/installTelegram.ts create mode 100644 @app/server/src/plugins/TelegramSettingsPlugin.ts create mode 100644 @app/server/src/telegram.ts create mode 100644 @app/worker/__tests__/registrationReminder.test.ts create mode 100644 @app/worker/__tests__/telegramReminder.test.ts create mode 100644 @app/worker/__tests__/telegramReply.test.ts create mode 100644 @app/worker/src/tasks/reminder__send_registration.ts create mode 100644 @app/worker/src/tasks/reminder__send_telegram.ts create mode 100644 @app/worker/src/tasks/telegram__reply.ts create mode 100644 @app/worker/templates/registration_reminder.mjml.njk create mode 100644 docs/registration-reminders.md create mode 100644 docs/reminder-release.md create mode 100644 docs/telegram-reminders.md create mode 100644 scripts/telegram-webhook.mjs diff --git a/@app/client/i18n.js b/@app/client/i18n.js index 3ecd1bab7..2c00d6d5f 100644 --- a/@app/client/i18n.js +++ b/@app/client/i18n.js @@ -13,11 +13,12 @@ module.exports = { "/settings/delete": ["settings"], "/settings/emails": ["settings"], "/settings/security": ["settings"], + "/settings/reminders": ["settings", "reminders"], "/invitations/accept": ["invitations"], "/create-event-category": ["events"], "/update-registration/[updateToken]": ["register_event"], "rgx:^/admin": ["admin", "events", "home", "register_event"], - "rgx:^/event": ["events", "register_event"], + "rgx:^/event": ["events", "register_event", "reminders"], }, loadLocaleFrom: (lang, ns) => import(`./src/translations/${lang}/${ns}.json`).then((m) => m.default), diff --git a/@app/client/src/components/EventReminder.tsx b/@app/client/src/components/EventReminder.tsx new file mode 100644 index 000000000..c5214fd47 --- /dev/null +++ b/@app/client/src/components/EventReminder.tsx @@ -0,0 +1,257 @@ +import { useEffect, useState } from "react" +import { BellOutlined, CheckCircleFilled } from "@ant-design/icons" +import { + ButtonLink, + ErrorAlert, + Link, + useIsMobile, + useTranslation, +} from "@app/components" +import { + SharedLayout_UserFragment, + useEnableEventReminderMutation, + useEventRegistrationReminderQuery, + useSetEventRegistrationReminderMutation, +} from "@app/graphql" +import { Button, Modal, notification, theme, Typography } from "antd" + +import { ReminderLeadTime } from "./ReminderLeadTime" +import { ReminderPreferences } from "./ReminderPreferences" + +import type { ArgsProps } from "antd/es/notification/interface" + +const NOTIFICATION_KEY = "event-reminder-set" +export const REMINDER_SET_DURATION_SECONDS = 8 + +// Full-width like the quota buttons above, so "Set reminder" and "Remove +// reminder" occupy exactly the same spot. +const buttonStyle: React.CSSProperties = { marginTop: 12 } + +// One fixed layout for every state: a status line and a full-width button. +// Delivery details are shown in the confirmation toast and in settings. +function ReminderPanel({ + icon, + title, + action, + error, +}: { + icon: React.ReactNode + title: React.ReactNode + action: React.ReactNode + error?: React.ReactNode +}) { + const { token } = theme.useToken() + return ( +
+ + {icon} {title} + + {action} + {error &&
{error}
} +
+ ) +} + +export function EventReminder({ + eventId, + slug, + currentUser, +}: { + eventId: string + slug: string + currentUser: SharedLayout_UserFragment | null | undefined +}) { + const { t, lang } = useTranslation("reminders") + const isMobile = useIsMobile() + const { token } = theme.useToken() + const [api, contextHolder] = notification.useNotification({ + placement: isMobile ? "top" : "topRight", + }) + const [setup, setSetup] = useState(false) + // Set after enabling succeeds; the toast opens once the refreshed reminder + // (with its actual delivery method and lead time) has loaded. + const [confirmPending, setConfirmPending] = useState(false) + const [query, refresh] = useEventRegistrationReminderQuery({ + variables: { eventId }, + pause: !currentUser, + requestPolicy: "cache-and-network", + }) + const [mutation, setReminder] = useSetEventRegistrationReminderMutation() + const [enableMutation, enable] = useEnableEventReminderMutation() + const reminder = query.data?.eventRegistrationReminders?.nodes[0] + const preferences = query.data?.currentReminderPreferences + const refreshData = () => refresh({ requestPolicy: "network-only" }) + useEffect(() => { + const onFocus = () => { + if (currentUser) refresh({ requestPolicy: "network-only" }) + } + window.addEventListener("focus", onFocus) + return () => window.removeEventListener("focus", onFocus) + }, [refresh, currentUser]) + + useEffect(() => { + if (!confirmPending) return + if (query.error) setConfirmPending(false) + if (!reminder) return + setConfirmPending(false) + api.success({ + key: NOTIFICATION_KEY, + message: t("toast.title"), + description: ( + <> +
+ {t("toast.delivery")}: {t(`channels.${reminder.deliveryMethod}`)} +
+
+ {t("toast.timing")}:{" "} + +
+ + ), + actions: ( + + {t("preferences.changeSettings")} + + ), + duration: REMINDER_SET_DURATION_SECONDS, + showProgress: true, + pauseOnHover: true, + role: "status", + props: { "data-cy": "event-reminder-toast" } as ArgsProps["props"], + }) + }, [api, confirmPending, query.error, reminder, t]) + + // Close the toast when leaving the event page. + useEffect(() => () => api.destroy(NOTIFICATION_KEY), [api]) + + if (!currentUser) + return ( + } + style={buttonStyle} + block + > + {t("signIn")} + + } + icon={} + title={t("preferences.eventPrompt")} + /> + ) + const verified = ( + query.data?.currentUser ?? currentUser + ).userEmails.nodes.some((email) => email.isPrimary && email.isVerified) + const needsSetup = + !preferences || + (preferences.deliveryMethod !== "email" && + (!query.data?.currentTelegramAccount || + !query.data?.telegramBotUsername)) || + (preferences.deliveryMethod !== "telegram" && !verified) + const enableReminder = async () => { + const result = await enable({ + eventId, + language: lang === "en" ? "en" : "fi", + }) + if (!result.error) { + setSetup(false) + setConfirmPending(true) + refreshData() + } + } + const cancelReminder = async () => { + const result = await setReminder({ + eventId, + enabled: false, + language: lang === "en" ? "en" : "fi", + }) + if (!result.error) { + api.destroy(NOTIFICATION_KEY) + refreshData() + } + } + const error = query.error || mutation.error || enableMutation.error + return ( + <> + {contextHolder} + + {t("cancel")} + + ) : ( + + ) + } + error={error && } + icon={ + reminder ? ( + + ) : ( + + ) + } + title={ + reminder + ? t(reminder.sentAt ? "sent" : "enabled") + : t("preferences.eventPrompt") + } + /> + setSetup(false)} + > + {setup && ( + + )} + {enableMutation.error && } + + + ) +} diff --git a/@app/client/src/components/ReminderLeadTime.tsx b/@app/client/src/components/ReminderLeadTime.tsx new file mode 100644 index 000000000..33594ca80 --- /dev/null +++ b/@app/client/src/components/ReminderLeadTime.tsx @@ -0,0 +1,14 @@ +import { useTranslation } from "@app/components" + +export function ReminderLeadTime({ minutes }: { minutes: number }) { + const { t } = useTranslation("reminders") + return ( + <> + {minutes === 1440 + ? t("leadTimes.day") + : minutes === 60 + ? t("leadTimes.hour") + : t("leadTime", { minutes })} + + ) +} diff --git a/@app/client/src/components/ReminderPreferences.tsx b/@app/client/src/components/ReminderPreferences.tsx new file mode 100644 index 000000000..bd347b978 --- /dev/null +++ b/@app/client/src/components/ReminderPreferences.tsx @@ -0,0 +1,161 @@ +import { useState } from "react" +import { ErrorAlert, Link, useTranslation } from "@app/components" +import { useSaveReminderPreferencesMutation } from "@app/graphql" +import { Alert, Button, Select, Space, Steps, Typography } from "antd" + +import { ReminderLeadTime } from "./ReminderLeadTime" +import { TelegramConnection } from "./TelegramConnection" + +type Preferences = { minutesBefore: number; deliveryMethod: string } + +export function ReminderPreferences({ + preferences, + account, + botUsername, + verified, + refresh, + onSaved, +}: { + preferences?: Preferences | null + account?: { username?: string | null } | null + botUsername?: string | null + verified: boolean + refresh: () => void + onSaved: () => Promise +}) { + const { t } = useTranslation("reminders") + const [step, setStep] = useState(0) + const [deliveryMethod, setDeliveryMethod] = useState( + preferences?.deliveryMethod ?? (botUsername ? "telegram" : "email") + ) + const [minutesBefore, setMinutesBefore] = useState( + preferences?.minutesBefore ?? 30 + ) + const [mutation, save] = useSaveReminderPreferencesMutation() + const [finishing, setFinishing] = useState(false) + const needsTelegram = deliveryMethod !== "email" + const needsEmail = deliveryMethod !== "telegram" + const ready = (!needsTelegram || !!account) && (!needsEmail || verified) + return ( + + + {t("preferences.explanation")} + + + {step === 0 ? ( + <> + +