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/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")}
+
+ ) : (
+ }
+ loading={enableMutation.fetching || confirmPending}
+ style={buttonStyle}
+ type="primary"
+ block
+ onClick={async () => {
+ if (needsSetup) setSetup(true)
+ else await enableReminder()
+ }}
+ >
+ {t("enable")}
+
+ )
+ }
+ 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/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/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 ? (
+ <>
+
+
+ )
+}
diff --git a/@app/client/src/components/TelegramConnection.tsx b/@app/client/src/components/TelegramConnection.tsx
new file mode 100644
index 000000000..e51a486d6
--- /dev/null
+++ b/@app/client/src/components/TelegramConnection.tsx
@@ -0,0 +1,125 @@
+import { useEffect, useState } from "react"
+import { SendOutlined } from "@ant-design/icons"
+import { ErrorAlert, useTranslation } from "@app/components"
+import {
+ useDisconnectTelegramMutation,
+ useRequestTelegramLinkMutation,
+} from "@app/graphql"
+import { Alert, Button, Space, Typography } from "antd"
+
+export function TelegramConnection({
+ account,
+ refresh,
+ botUsername,
+}: {
+ botUsername?: string | null
+ account?: { username?: string | null } | null
+ refresh: () => void
+}) {
+ const { t } = useTranslation("reminders")
+ const [link, setLink] = useState()
+ const [expiresAt, setExpiresAt] = useState(0)
+ const [popupBlocked, setPopupBlocked] = useState(false)
+ const [request, requestLink] = useRequestTelegramLinkMutation()
+ const [disconnect, disconnectTelegram] = useDisconnectTelegramMutation()
+ const error = request.error || disconnect.error
+ useEffect(() => {
+ if (!link || account) return
+ const timer = window.setInterval(() => {
+ if (Date.now() >= expiresAt) window.clearInterval(timer)
+ else refresh()
+ }, 3000)
+ return () => window.clearInterval(timer)
+ }, [link, account, expiresAt, refresh])
+ if (!botUsername) return null
+ const connect = async () => {
+ // Open synchronously from the click so browser popup protection permits it.
+ const tab = window.open("about:blank", "_blank")
+ if (tab) tab.opener = null
+ let opened = false
+ setPopupBlocked(false)
+ try {
+ const result = await requestLink({})
+ const token = result.data?.requestTelegramLink?.string
+ if (!token) return
+ const url = `https://t.me/${botUsername}?start=${encodeURIComponent(token)}`
+ setLink(url)
+ setExpiresAt(Date.now() + 15 * 60 * 1000)
+ if (tab && !tab.closed) {
+ tab.location.href = url
+ opened = true
+ }
+ setPopupBlocked(!opened)
+ } finally {
+ if (!opened && tab && !tab.closed) tab.close()
+ }
+ }
+ return (
+
+ {account && (
+
+ {t("telegram.connected", {
+ name: account.username ? `@${account.username}` : "Telegram",
+ })}
+
+ )}
+ {error && }
+ {account ? (
+
+ ) : (
+
+ {link ? (
+ <>
+
+
+
+ >
+ ) : (
+ }
+ loading={request.fetching}
+ type="primary"
+ onClick={connect}
+ >
+ {t("telegram.connect")}
+
+ )}
+
+ )}
+ {!account && popupBlocked && (
+ {t("telegram.popupBlocked")}
+ )}
+ {!account && link && (
+ {t("telegram.instructions")}
+ )}
+
+ }
+ message={t("telegram.title")}
+ style={{ marginBottom: 24 }}
+ type="info"
+ />
+ )
+}
diff --git a/@app/client/src/graphql/reminders/RegistrationReminders.graphql b/@app/client/src/graphql/reminders/RegistrationReminders.graphql
new file mode 100644
index 000000000..7f0b71f28
--- /dev/null
+++ b/@app/client/src/graphql/reminders/RegistrationReminders.graphql
@@ -0,0 +1,117 @@
+fragment RegistrationReminderFields on EventRegistrationReminder {
+ id
+ eventId
+ deliveryMethod
+ minutesBefore
+ sentAt
+ event {
+ id
+ slug
+ name
+ isDraft
+ registrationStartTime
+ }
+}
+
+query RegistrationReminders($first: Int!) {
+ telegramBotUsername
+ currentReminderPreferences {
+ userId
+ minutesBefore
+ deliveryMethod
+ }
+ ...SharedLayout_Query
+ currentTelegramAccount {
+ userId
+ username
+ }
+ eventRegistrationReminders(first: $first, orderBy: PRIMARY_KEY_ASC) {
+ totalCount
+ nodes {
+ ...RegistrationReminderFields
+ }
+ }
+}
+
+query EventRegistrationReminder($eventId: UUID!) {
+ currentUser {
+ id
+ userEmails {
+ nodes {
+ isPrimary
+ isVerified
+ }
+ }
+ }
+ telegramBotUsername
+ currentReminderPreferences {
+ userId
+ minutesBefore
+ deliveryMethod
+ }
+ currentTelegramAccount {
+ userId
+ username
+ }
+ eventRegistrationReminders(condition: { eventId: $eventId }, first: 1) {
+ nodes {
+ id
+ deliveryMethod
+ minutesBefore
+ sentAt
+ }
+ }
+}
+
+mutation SetEventRegistrationReminder(
+ $eventId: UUID!
+ $enabled: Boolean!
+ $language: String!
+ $minutesBefore: Int = 30
+ $deliveryMethod: String = "email"
+) {
+ setEventRegistrationReminder(
+ input: {
+ eventId: $eventId
+ enabled: $enabled
+ language: $language
+ minutesBefore: $minutesBefore
+ deliveryMethod: $deliveryMethod
+ }
+ ) {
+ boolean
+ }
+}
+
+mutation RequestTelegramLink {
+ requestTelegramLink(input: {}) {
+ string
+ }
+}
+
+mutation DisconnectTelegram {
+ disconnectTelegram(input: {}) {
+ boolean
+ }
+}
+
+mutation SaveReminderPreferences(
+ $minutesBefore: Int!
+ $deliveryMethod: String!
+) {
+ saveReminderPreferences(
+ input: { minutesBefore: $minutesBefore, deliveryMethod: $deliveryMethod }
+ ) {
+ reminderPreference {
+ userId
+ minutesBefore
+ deliveryMethod
+ }
+ }
+}
+
+mutation EnableEventReminder($eventId: UUID!, $language: String!) {
+ enableEventReminder(input: { eventId: $eventId, language: $language }) {
+ boolean
+ }
+}
diff --git a/@app/client/src/pages/event/[slug]/index.tsx b/@app/client/src/pages/event/[slug]/index.tsx
index 4d5918f31..217070f3e 100644
--- a/@app/client/src/pages/event/[slug]/index.tsx
+++ b/@app/client/src/pages/event/[slug]/index.tsx
@@ -25,6 +25,9 @@ import dayjs from "dayjs"
import * as NextImage from "next/image"
import { useRouter } from "next/router"
+import { EventReminder } from "../../../components/EventReminder"
+import { RegistrationCalendar } from "../../../components/RegistrationCalendar"
+
import type { NextPage } from "next"
// See SharedLayout.tsx — namespace-then-default access works around a
@@ -216,6 +219,9 @@ const EventPageInner: React.FC = ({
onBack={() => router.push("/")}
/>
+
+
+
= ({
>
+ ) : null
+ }
registrations={registrations.nodes}
signupState={signupState}
/>
diff --git a/@app/client/src/pages/event/[slug]/register/[quotaId]/index.tsx b/@app/client/src/pages/event/[slug]/register/[quotaId]/index.tsx
index 47ebd8ff1..6b0463125 100644
--- a/@app/client/src/pages/event/[slug]/register/[quotaId]/index.tsx
+++ b/@app/client/src/pages/event/[slug]/register/[quotaId]/index.tsx
@@ -112,6 +112,16 @@ const EventRegistrationPage: NextPage = () => {
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/pages/settings/reminders.tsx b/@app/client/src/pages/settings/reminders.tsx
new file mode 100644
index 000000000..c6f724974
--- /dev/null
+++ b/@app/client/src/pages/settings/reminders.tsx
@@ -0,0 +1,186 @@
+import { useEffect, useState } from "react"
+import {
+ ErrorAlert,
+ Link,
+ PageHeader,
+ SettingsLayout,
+ useTranslation,
+} from "@app/components"
+import {
+ useRegistrationRemindersQuery,
+ useSetEventRegistrationReminderMutation,
+} from "@app/graphql"
+import { Alert, Button, Empty, List, Modal, Space, Tag, Typography } from "antd"
+import dayjs from "dayjs"
+
+import { ReminderLeadTime } from "../../components/ReminderLeadTime"
+import { ReminderPreferences } from "../../components/ReminderPreferences"
+import { TelegramConnection } from "../../components/TelegramConnection"
+
+export default function Reminders() {
+ const { t, lang } = useTranslation("reminders")
+ const [editing, setEditing] = useState(false)
+ const [saved, setSaved] = useState(false)
+ const [first, setFirst] = useState(50)
+ const [query, refresh] = useRegistrationRemindersQuery({
+ variables: { first },
+ requestPolicy: "cache-and-network",
+ })
+ useEffect(() => {
+ const onFocus = () => refresh({ requestPolicy: "network-only" })
+ window.addEventListener("focus", onFocus)
+ return () => window.removeEventListener("focus", onFocus)
+ }, [refresh])
+ const [mutation, setReminder] = useSetEventRegistrationReminderMutation()
+ const reminders = query.data?.eventRegistrationReminders
+ const language = lang === "en" ? "en" : "fi"
+ return (
+
+
+ {query.data && (
+ <>
+
+ {t("preferences.title")}
+
+
+ {t("preferences.explanation")}
+
+ {query.data.currentReminderPreferences && (
+
+ {t(
+ `channels.${query.data.currentReminderPreferences.deliveryMethod}`
+ )}{" "}
+ ·{" "}
+
+
+ )}
+
+ {saved && (
+
+ )}
+ setEditing(false)}
+ >
+ {editing && (
+ refresh({ requestPolicy: "network-only" })}
+ verified={
+ !!query.data.currentUser?.userEmails.nodes.some(
+ (email) => email.isPrimary && email.isVerified
+ )
+ }
+ onSaved={async () => {
+ setEditing(false)
+ setSaved(true)
+ refresh({ requestPolicy: "network-only" })
+ }}
+ />
+ )}
+
+ >
+ )}
+ refresh({ requestPolicy: "network-only" })}
+ />
+ {t("timingNote")}
+ {query.error && }
+ {mutation.error && }
+
}}
+ renderItem={(reminder) => {
+ const event = reminder.event
+ const expired =
+ event && dayjs(event.registrationStartTime).isBefore(dayjs())
+ return (
+ {
+ const result = await setReminder({
+ eventId: reminder.eventId,
+ enabled: false,
+ language,
+ })
+ if (!result.error)
+ refresh({ requestPolicy: "network-only" })
+ }}
+ >
+ {t("cancel")}
+ ,
+ ]}
+ >
+
+ {event ? (
+
+ {event.name[language] || event.name.fi || event.name.en}
+
+ ) : (
+ {t("unavailable")}
+ )}
+ {event && (
+
+ {t("opens")}:{" "}
+ {dayjs(event.registrationStartTime).format(
+ "D.M.YYYY HH:mm"
+ )}
+
+ )}
+
+
+
+ {t(`channels.${reminder.deliveryMethod}`)}
+
+ {t(
+ reminder.sentAt
+ ? "sent"
+ : !event || event.isDraft
+ ? "paused"
+ : expired
+ ? "expired"
+ : "pending"
+ )}
+
+
+
+ )
+ }}
+ />
+ {reminders && reminders.totalCount > reminders.nodes.length && (
+
+ )}
+
+ )
+}
diff --git a/@app/client/src/translations/en/common.json b/@app/client/src/translations/en/common.json
index bb0448cb3..be8b1b331 100644
--- a/@app/client/src/translations/en/common.json
+++ b/@app/client/src/translations/en/common.json
@@ -52,6 +52,7 @@
"registrationUpcoming": "Signup upcoming",
"registrations": "Registrations",
"registrationsPerQuota": "Registrations by quota",
+ "reminders": "My reminders",
"remove": "Remove",
"required": "Required",
"settings": "Settings",
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/en/reminders.json b/@app/client/src/translations/en/reminders.json
new file mode 100644
index 000000000..36568a18c
--- /dev/null
+++ b/@app/client/src/translations/en/reminders.json
@@ -0,0 +1,70 @@
+{
+ "cancel": "Remove reminder",
+ "delivery": "Email reminder to {{email}}.",
+ "empty": "You have no registration reminders.",
+ "enable": "Set reminder",
+ "enabled": "Reminder set",
+ "expired": "Registration has opened",
+ "loadMore": "Show more",
+ "myReminders": "My reminders",
+ "opens": "Registration opens",
+ "paused": "Paused",
+ "pending": "Scheduled",
+ "sent": "Reminder sent",
+ "signIn": "Sign in",
+ "timingNote": "If your chosen reminder time has already passed, the reminder is sent as soon as possible.",
+ "unavailable": "Event unavailable",
+ "verifyEmail": "Verify your primary email to enable reminders",
+ "minutesBefore": "Reminder timing",
+ "save": "Save",
+ "leadTime": "{{minutes}} minutes before registration opens",
+ "presets": {
+ "5": "5 minutes before",
+ "10": "10 minutes before",
+ "15": "15 minutes before",
+ "30": "30 minutes before",
+ "60": "1 hour before",
+ "1440": "1 day before"
+ },
+ "channelLabel": "Reminder delivery method",
+ "channels": {
+ "email": "Email",
+ "telegram": "Telegram",
+ "both": "Both"
+ },
+ "telegram": {
+ "title": "Telegram reminders",
+ "connected": "Connected: {{name}}",
+ "connect": "Connect Telegram",
+ "disconnect": "Disconnect Telegram",
+ "open": "Open Telegram",
+ "check": "Refresh connection status",
+ "instructions": "Confirm the connection in Telegram, then return here.",
+ "connectHint": "Connect Telegram in settings",
+ "newLink": "Generate a new link",
+ "popupBlocked": "Your browser did not open Telegram automatically. Click Open Telegram to continue."
+ },
+ "preferences": {
+ "title": "Reminder preferences",
+ "explanation": "Choose reminder delivery and timing.",
+ "delivery": "Choose delivery",
+ "timing": "Choose timing",
+ "next": "Continue",
+ "back": "Back",
+ "getStarted": "Set up reminders",
+ "eventPrompt": "Don’t miss registration!",
+ "changeSettings": "Change reminder settings",
+ "saved": "Settings saved.",
+ "telegramUnavailable": "Telegram is currently unavailable. Choose email or try again later."
+ },
+ "leadTimes": {
+ "day": "1 day before registration opens",
+ "hour": "1 hour before registration opens"
+ },
+ "toast": {
+ "title": "Reminder set!",
+ "delivery": "Delivery method",
+ "timing": "Timing"
+ },
+ "recommended": "recommended"
+}
diff --git a/@app/client/src/translations/en/settings.json b/@app/client/src/translations/en/settings.json
index 0ec27d743..c2e5d9685 100644
--- a/@app/client/src/translations/en/settings.json
+++ b/@app/client/src/translations/en/settings.json
@@ -89,6 +89,7 @@
"delete": "Delete account",
"emails": "Email addresses",
"index": "Edit profile",
+ "reminders": "My reminders",
"security": "Change passphrase"
}
}
diff --git a/@app/client/src/translations/fi/common.json b/@app/client/src/translations/fi/common.json
index c9bcbc1fa..5b363901e 100644
--- a/@app/client/src/translations/fi/common.json
+++ b/@app/client/src/translations/fi/common.json
@@ -52,6 +52,7 @@
"registrationUpcoming": "Ilmoittautuminen tulossa",
"registrations": "Ilmoittautuneet",
"registrationsPerQuota": "Ilmoittautuneet kiintiöittäin",
+ "reminders": "Omat muistutukset",
"remove": "Poista",
"required": "Pakollinen",
"settings": "Asetukset",
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/fi/reminders.json b/@app/client/src/translations/fi/reminders.json
new file mode 100644
index 000000000..d2c681f23
--- /dev/null
+++ b/@app/client/src/translations/fi/reminders.json
@@ -0,0 +1,70 @@
+{
+ "cancel": "Poista muistutus",
+ "delivery": "Sähköpostimuistutus osoitteeseen {{email}}.",
+ "empty": "Sinulla ei ole ilmoittautumismuistutuksia.",
+ "enable": "Aseta muistutus",
+ "enabled": "Muistutus asetettu",
+ "expired": "Ilmoittautuminen on avautunut",
+ "loadMore": "Näytä lisää",
+ "myReminders": "Omat muistutukset",
+ "opens": "Ilmoittautuminen alkaa",
+ "paused": "Keskeytetty",
+ "pending": "Ajastettu",
+ "sent": "Muistutus lähetetty",
+ "signIn": "Kirjaudu sisään",
+ "timingNote": "Jos valitsemasi muistutusaika on jo mennyt, muistutus lähetetään mahdollisimman pian.",
+ "unavailable": "Tapahtuma ei ole saatavilla",
+ "verifyEmail": "Vahvista ensisijainen sähköpostisi ottaaksesi muistutukset käyttöön",
+ "minutesBefore": "Muistutuksen ajankohta",
+ "save": "Tallenna",
+ "leadTime": "{{minutes}} minuuttia ennen ilmoittautumisen alkua",
+ "presets": {
+ "5": "5 minuuttia ennen",
+ "10": "10 minuuttia ennen",
+ "15": "15 minuuttia ennen",
+ "30": "30 minuuttia ennen",
+ "60": "Tunti ennen",
+ "1440": "Päivä ennen"
+ },
+ "channelLabel": "Muistutuksen toimitustapa",
+ "channels": {
+ "email": "Sähköposti",
+ "telegram": "Telegram",
+ "both": "Molemmat"
+ },
+ "telegram": {
+ "title": "Telegram-muistutukset",
+ "connected": "Yhdistetty: {{name}}",
+ "connect": "Yhdistä Telegram",
+ "disconnect": "Katkaise Telegram-yhteys",
+ "open": "Avaa Telegram",
+ "check": "Päivitä yhteyden tila",
+ "instructions": "Vahvista yhteys Telegramissa ja palaa sitten tänne.",
+ "connectHint": "Yhdistä Telegram asetuksissa",
+ "newLink": "Luo uusi linkki",
+ "popupBlocked": "Selain ei avannut Telegramia automaattisesti. Jatka painamalla Avaa Telegram."
+ },
+ "preferences": {
+ "title": "Muistutusasetukset",
+ "explanation": "Valitse muistutuksen toimitustapa ja ajankohta.",
+ "delivery": "Valitse toimitustapa",
+ "timing": "Valitse ajankohta",
+ "next": "Jatka",
+ "back": "Takaisin",
+ "getStarted": "Ota muistutukset käyttöön",
+ "eventPrompt": "Älä missaa ilmoittautumista!",
+ "changeSettings": "Muuta muistutusasetuksia",
+ "saved": "Asetukset tallennettu.",
+ "telegramUnavailable": "Telegram ei ole nyt saatavilla. Valitse sähköposti tai yritä myöhemmin uudelleen."
+ },
+ "leadTimes": {
+ "day": "Päivä ennen ilmoittautumisen alkua",
+ "hour": "Tunti ennen ilmoittautumisen alkua"
+ },
+ "toast": {
+ "title": "Muistutus asetettu!",
+ "delivery": "Toimitustapa",
+ "timing": "Ajankohta"
+ },
+ "recommended": "suositeltu"
+}
diff --git a/@app/client/src/translations/fi/settings.json b/@app/client/src/translations/fi/settings.json
index e22c81d7a..bbf966b2c 100644
--- a/@app/client/src/translations/fi/settings.json
+++ b/@app/client/src/translations/fi/settings.json
@@ -25,7 +25,7 @@
"profileUpdated": "Profiili päivitetty"
},
"label": {
- "newEmail": "Uusi sähköpostil",
+ "newEmail": "Uusi sähköposti",
"newPassphrase": "Uusi salasana",
"oldPassphrase": "Vanha salasana"
},
@@ -89,6 +89,7 @@
"delete": "Poista käyttäjä",
"emails": "Sähköpostiosoitteet",
"index": "Muokkaa tiliä",
+ "reminders": "Omat muistutukset",
"security": "Vaihda salasana"
}
}
diff --git a/@app/client/src/translations/se/common.json b/@app/client/src/translations/se/common.json
index e4cc3771d..576f1b1a0 100644
--- a/@app/client/src/translations/se/common.json
+++ b/@app/client/src/translations/se/common.json
@@ -52,6 +52,7 @@
"registrationUpcoming": "Registrering kommande",
"registrations": "Registrationer",
"registrationsPerQuota": "Registrationer efter kvot",
+ "reminders": "Mina påminnelser",
"remove": "Ta bort",
"required": "Krävs",
"settings": "Inställningar",
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/client/src/translations/se/reminders.json b/@app/client/src/translations/se/reminders.json
new file mode 100644
index 000000000..0462b4d54
--- /dev/null
+++ b/@app/client/src/translations/se/reminders.json
@@ -0,0 +1,70 @@
+{
+ "cancel": "Ta bort påminnelsen",
+ "delivery": "E-postpåminnelse till {{email}}.",
+ "empty": "Du har inga påminnelser.",
+ "enable": "Ställ in påminnelse",
+ "enabled": "Påminnelse inställd",
+ "expired": "Anmälan har öppnat",
+ "loadMore": "Visa fler",
+ "myReminders": "Mina påminnelser",
+ "opens": "Anmälan öppnar",
+ "paused": "Pausad",
+ "pending": "Schemalagd",
+ "sent": "Påminnelse skickad",
+ "signIn": "Logga in",
+ "timingNote": "Om den valda tiden redan har passerat skickas påminnelsen så snart som möjligt.",
+ "unavailable": "Evenemanget är inte tillgängligt",
+ "verifyEmail": "Verifiera din primära e-postadress för att aktivera påminnelser",
+ "minutesBefore": "Tidpunkt för påminnelsen",
+ "save": "Spara",
+ "leadTime": "{{minutes}} minuter innan anmälan öppnar",
+ "presets": {
+ "5": "5 minuter före",
+ "10": "10 minuter före",
+ "15": "15 minuter före",
+ "30": "30 minuter före",
+ "60": "1 timme före",
+ "1440": "1 dag före"
+ },
+ "channelLabel": "Leveransmetod",
+ "channels": {
+ "email": "E-post",
+ "telegram": "Telegram",
+ "both": "Båda"
+ },
+ "telegram": {
+ "title": "Telegram-påminnelser",
+ "connected": "Ansluten: {{name}}",
+ "connect": "Anslut Telegram",
+ "disconnect": "Koppla från Telegram",
+ "open": "Öppna Telegram",
+ "check": "Uppdatera anslutningsstatus",
+ "instructions": "Bekräfta anslutningen i Telegram och återvänd sedan hit.",
+ "connectHint": "Anslut Telegram i inställningarna",
+ "newLink": "Skapa en ny länk",
+ "popupBlocked": "Webbläsaren öppnade inte Telegram automatiskt. Tryck på Öppna Telegram för att fortsätta."
+ },
+ "preferences": {
+ "title": "Påminnelseinställningar",
+ "explanation": "Välj leveranssätt och tidpunkt.",
+ "delivery": "Välj leveranssätt",
+ "timing": "Välj tidpunkt",
+ "next": "Fortsätt",
+ "back": "Tillbaka",
+ "getStarted": "Ställ in påminnelser",
+ "eventPrompt": "Missa inte anmälan!",
+ "changeSettings": "Ändra påminnelseinställningar",
+ "saved": "Inställningarna har sparats.",
+ "telegramUnavailable": "Telegram är inte tillgängligt just nu. Välj e-post eller försök senare."
+ },
+ "leadTimes": {
+ "day": "1 dag innan anmälan öppnar",
+ "hour": "1 timme innan anmälan öppnar"
+ },
+ "toast": {
+ "title": "Påminnelse inställd!",
+ "delivery": "Leveranssätt",
+ "timing": "Tidpunkt"
+ },
+ "recommended": "rekommenderas"
+}
diff --git a/@app/client/src/translations/se/settings.json b/@app/client/src/translations/se/settings.json
index 82a9ff7fc..7ffba7791 100644
--- a/@app/client/src/translations/se/settings.json
+++ b/@app/client/src/translations/se/settings.json
@@ -89,6 +89,7 @@
"delete": "Radera konto",
"emails": "E-postadresser",
"index": "Redigera profil",
+ "reminders": "Mina påminnelser",
"security": "Ändra lösenfras"
}
}
diff --git a/@app/components/src/EventQuotasCard.tsx b/@app/components/src/EventQuotasCard.tsx
index 620cf94fe..ba408d037 100644
--- a/@app/components/src/EventQuotasCard.tsx
+++ b/@app/components/src/EventQuotasCard.tsx
@@ -9,14 +9,17 @@ import { Button, Card, Popover } from "antd"
import { useIsMobile, useTranslation } from "./hooks"
import { Link, ProgressBar, SignupState } from "."
+import type { ReactNode } from "react"
+
interface EventQuotasCardProps {
event: EventPage_EventFragment
registrations: EventPage_RegistrationFragment[]
signupState: SignupState
+ footer?: ReactNode
}
export const EventQuotasCard: React.FC = memo(
- ({ event, registrations, signupState }) => {
+ ({ event, registrations, signupState, footer }) => {
const { t, lang } = useTranslation("events")
const isMobile = useIsMobile()
const { slug, quotas } = event
@@ -76,6 +79,7 @@ export const EventQuotasCard: React.FC = memo(
)
})}
+ {footer && {footer}
}
)
},
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/components/src/SettingsLayout.tsx b/@app/components/src/SettingsLayout.tsx
index 2572cc07d..cc41c5224 100644
--- a/@app/components/src/SettingsLayout.tsx
+++ b/@app/components/src/SettingsLayout.tsx
@@ -1,6 +1,7 @@
import qs from "querystring"
import {
+ BellOutlined,
LoginOutlined,
MailOutlined,
ProfileOutlined,
@@ -33,6 +34,11 @@ interface SettingsPageSpec {
}
export const pages = (t: Translate) => ({
+ "/settings/reminders": {
+ title: t("titles.reminders"),
+ icon: ,
+ cy: "settingslayout-link-reminders",
+ } as SettingsPageSpec,
"/settings/profile": {
title: t("titles.index"),
icon: ,
diff --git a/@app/components/src/SharedLayout.tsx b/@app/components/src/SharedLayout.tsx
index da145e6e2..99acc843c 100644
--- a/@app/components/src/SharedLayout.tsx
+++ b/@app/components/src/SharedLayout.tsx
@@ -287,6 +287,17 @@ export function SharedLayout({
),
},
+ {
+ key: "reminders",
+ label: (
+
+ {t("reminders")}
+
+ ),
+ },
{
key: "logout",
label: {t("logout")},
diff --git a/@app/db/__tests__/app_public/functions/reminder_preferences.test.ts b/@app/db/__tests__/app_public/functions/reminder_preferences.test.ts
new file mode 100644
index 000000000..4df09c332
--- /dev/null
+++ b/@app/db/__tests__/app_public/functions/reminder_preferences.test.ts
@@ -0,0 +1,283 @@
+import {
+ asRoot,
+ becomeUser,
+ createEventCategories,
+ createEvents,
+ createOrganizations,
+ createUsers,
+ withRootDb,
+} from "../../helpers"
+
+it("updates upcoming reminders with saved preferences and keeps preferences private", () =>
+ withRootDb(async (client) => {
+ const [user, other] = await createUsers(client, 2, true)
+ await becomeUser(client, user.id)
+ const [organization] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, organization.id)
+ const [event, nextEvent] = await createEvents(
+ client,
+ 2,
+ organization.id,
+ category.id,
+ false
+ )
+ await becomeUser(client, user.id)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.current_reminder_preferences()"
+ )
+ ).rows[0].user_id
+ ).toBeNull()
+ await client.query(
+ "select app_public.save_reminder_preferences(15, 'email')"
+ )
+ await client.query("select app_public.enable_event_reminder($1, 'fi')", [
+ event.id,
+ ])
+ await client.query(
+ "select app_public.save_reminder_preferences(60, 'email')"
+ )
+ await client.query("select app_public.enable_event_reminder($1, 'en')", [
+ nextEvent.id,
+ ])
+ const { rows } = await client.query(
+ "select event_id, minutes_before from app_public.event_registration_reminders"
+ )
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ { event_id: event.id, minutes_before: 60 },
+ { event_id: nextEvent.id, minutes_before: 60 },
+ ])
+ )
+ await becomeUser(client, other.id)
+ expect(
+ (await client.query("select * from app_public.reminder_preferences")).rows
+ ).toHaveLength(0)
+ await client.query(
+ "select app_public.save_reminder_preferences(30, 'email')"
+ )
+ await becomeUser(client, user.id)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.current_reminder_preferences()"
+ )
+ ).rows[0].minutes_before
+ ).toBe(60)
+ }))
+
+it("requires onboarding before one-click enable", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ await expect(
+ client.query("select app_public.enable_event_reminder(gen_random_uuid())")
+ ).rejects.toHaveProperty("code", "CHECK")
+ }))
+
+it.each([0, 10081, null])("rejects invalid default lead time %s", (minutes) =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ await expect(
+ client.query("select app_public.save_reminder_preferences($1, 'email')", [
+ minutes,
+ ])
+ ).rejects.toHaveProperty("code", "CHECK")
+ })
+)
+
+it("requires authentication to save preferences", () =>
+ withRootDb(async (client) => {
+ await becomeUser(client, null)
+ await expect(
+ client.query("select app_public.save_reminder_preferences(30, 'email')")
+ ).rejects.toHaveProperty("code", "LOGIN")
+ }))
+
+it("requires email verification", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, false)
+ await becomeUser(client, user.id)
+ await expect(
+ client.query("select app_public.save_reminder_preferences(30, 'email')")
+ ).rejects.toHaveProperty("code", "EMAIL")
+ }))
+
+it("requires a connected Telegram account", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ await expect(
+ client.query(
+ "select app_public.save_reminder_preferences(30, 'telegram')"
+ )
+ ).rejects.toHaveProperty("code", "CHECK")
+ }))
+
+it("rechecks delivery availability when enabling with saved preferences", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ await asRoot(client, () =>
+ client.query(
+ "insert into app_public.telegram_accounts(user_id, chat_id) values($1, 123456)",
+ [user.id]
+ )
+ )
+ await client.query(
+ "select app_public.save_reminder_preferences(30, 'telegram')"
+ )
+ await client.query("select app_public.disconnect_telegram()")
+ await expect(
+ client.query("select app_public.enable_event_reminder(gen_random_uuid())")
+ ).rejects.toHaveProperty("code", "CHECK")
+ }))
+
+it("reschedules pending reminders while preserving sent and past reminders", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ const [organization] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, organization.id)
+ const events = await createEvents(
+ client,
+ 3,
+ organization.id,
+ category.id,
+ false
+ )
+ await client.query(
+ "select app_public.save_reminder_preferences(15, 'email')"
+ )
+ for (const event of events)
+ await client.query("select app_public.enable_event_reminder($1)", [
+ event.id,
+ ])
+ await asRoot(client, async () => {
+ await client.query(
+ "update app_public.event_registration_reminders set sent_at=now(), email_sent_at=now() where event_id=$1",
+ [events[1].id]
+ )
+ await client.query(
+ "update app_public.events set registration_start_time=now()-interval '1 minute' where id=$1",
+ [events[2].id]
+ )
+ })
+ await client.query(
+ "select app_public.save_reminder_preferences(60, 'email')"
+ )
+ const { rows } = await client.query(
+ "select * from app_public.event_registration_reminders"
+ )
+ expect(rows.find((r) => r.event_id === events[0].id).minutes_before).toBe(
+ 60
+ )
+ expect(rows.find((r) => r.event_id === events[1].id).minutes_before).toBe(
+ 15
+ )
+ expect(rows.find((r) => r.event_id === events[2].id).minutes_before).toBe(
+ 15
+ )
+ const pending = rows.find((r) => r.event_id === events[0].id)
+ await asRoot(client, async () => {
+ const jobs = (
+ await client.query(
+ "select run_at from graphile_worker._private_jobs where key=$1",
+ ["registration-reminder:" + pending.id]
+ )
+ ).rows
+ expect(jobs).toHaveLength(1)
+ expect(new Date(jobs[0].run_at).getTime()).toBe(
+ new Date(events[0].registration_start_time).getTime() - 60 * 60000
+ )
+ })
+ }))
+
+it("updates delivery channels without resending a channel already delivered", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, true)
+ await becomeUser(client, user.id)
+ const [organization] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, organization.id)
+ const [event] = await createEvents(
+ client,
+ 1,
+ organization.id,
+ category.id,
+ false
+ )
+ await asRoot(client, () =>
+ client.query(
+ "insert into app_public.telegram_accounts(user_id,chat_id) values($1,123456)",
+ [user.id]
+ )
+ )
+ await client.query(
+ "select app_public.save_reminder_preferences(15, 'both')"
+ )
+ await client.query("select app_public.enable_event_reminder($1)", [
+ event.id,
+ ])
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.event_registration_reminders set email_sent_at=now() where event_id=$1",
+ [event.id]
+ )
+ )
+ await client.query(
+ "select app_public.save_reminder_preferences(60, 'email')"
+ )
+ const reminder = (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id=$1",
+ [event.id]
+ )
+ ).rows[0]
+ expect(reminder.delivery_method).toBe("email")
+ expect(reminder.sent_at).not.toBeNull()
+ await asRoot(client, async () => {
+ expect(
+ (
+ await client.query(
+ "select key from graphile_worker._private_jobs where key like $1",
+ ["registration-reminder:" + reminder.id + "%"]
+ )
+ ).rows
+ ).toHaveLength(0)
+ })
+ }))
+
+it("does not change another user's reminders when preferences are saved", () =>
+ withRootDb(async (client) => {
+ const users = await createUsers(client, 2, true)
+ await becomeUser(client, users[0].id)
+ const [organization] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, organization.id)
+ const [event] = await createEvents(
+ client,
+ 1,
+ organization.id,
+ category.id,
+ false
+ )
+ for (const user of users) {
+ await becomeUser(client, user.id)
+ await client.query(
+ "select app_public.save_reminder_preferences(15, 'email')"
+ )
+ await client.query("select app_public.enable_event_reminder($1)", [
+ event.id,
+ ])
+ }
+ await becomeUser(client, users[0].id)
+ await client.query(
+ "select app_public.save_reminder_preferences(60, 'email')"
+ )
+ await becomeUser(client, users[1].id)
+ const { rows } = await client.query(
+ "select minutes_before from app_public.event_registration_reminders"
+ )
+ expect(rows).toEqual([{ minutes_before: 15 }])
+ }))
diff --git a/@app/db/__tests__/app_public/functions/set_event_registration_reminder.test.ts b/@app/db/__tests__/app_public/functions/set_event_registration_reminder.test.ts
new file mode 100644
index 000000000..2892dc4eb
--- /dev/null
+++ b/@app/db/__tests__/app_public/functions/set_event_registration_reminder.test.ts
@@ -0,0 +1,417 @@
+import { PoolClient } from "pg"
+
+import reminderTask from "../../../../worker/src/tasks/reminder__send_registration"
+import sendEmail from "../../../../worker/src/tasks/send_email"
+import {
+ asRoot,
+ becomeUser,
+ createEventCategories,
+ createEvents,
+ createOrganizations,
+ createUsers,
+ withRootDb,
+} from "../../helpers"
+
+jest.mock("../../../../worker/src/tasks/send_email", () => ({
+ __esModule: true,
+ default: jest.fn(),
+}))
+
+async function setup(client: PoolClient, verified = true) {
+ const [user] = await createUsers(client, 1, verified)
+ await becomeUser(client, user.id)
+ const [organization] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, organization.id)
+ const [event] = await createEvents(
+ client,
+ 1,
+ organization.id,
+ category.id,
+ false
+ )
+ await becomeUser(client, user.id)
+ return { user, event }
+}
+
+async function enable(client: PoolClient, eventId: string) {
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi')",
+ [eventId]
+ )
+ return (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id = $1",
+ [eventId]
+ )
+ ).rows[0]
+}
+
+async function jobs(client: PoolClient, id: string) {
+ return asRoot(
+ client,
+ async () =>
+ (
+ await client.query(
+ "select * from graphile_worker._private_jobs where key = $1",
+ [`registration-reminder:${id}`]
+ )
+ ).rows
+ )
+}
+
+it("stores one reminder per user/event, scheduled exactly 30 minutes before opening", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ const reminder = await enable(client, event.id)
+ await enable(client, event.id)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.event_registration_reminders"
+ )
+ ).rows
+ ).toHaveLength(1)
+ const scheduled = await jobs(client, reminder.id)
+ expect(scheduled).toHaveLength(1)
+ expect(new Date(scheduled[0].run_at).getTime()).toBe(
+ new Date(event.registration_start_time).getTime() - 30 * 60000
+ )
+ }))
+
+it("isolates reminders between users and permits cancellation only by their owner", () =>
+ withRootDb(async (client) => {
+ const { user, event } = await setup(client)
+ const reminder = await enable(client, event.id)
+ const [other] = await asRoot(client, () => createUsers(client))
+ await becomeUser(client, other.id)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.event_registration_reminders"
+ )
+ ).rows
+ ).toHaveLength(0)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, false)",
+ [event.id]
+ )
+ expect(await jobs(client, reminder.id)).toHaveLength(1)
+ await becomeUser(client, user.id)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, false)",
+ [event.id]
+ )
+ expect(await jobs(client, reminder.id)).toHaveLength(0)
+ }))
+
+it("requires a signed-in user", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ await becomeUser(client, null)
+ await expect(enable(client, event.id)).rejects.toHaveProperty(
+ "code",
+ "LOGIN"
+ )
+ }))
+
+it("requires a verified primary email", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client, false)
+ await expect(enable(client, event.id)).rejects.toHaveProperty(
+ "code",
+ "EMAIL"
+ )
+ }))
+
+it.each(["hidden", "open"])("rejects an %s event", (kind) =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ await asRoot(client, () =>
+ client.query(
+ kind === "hidden"
+ ? "update app_public.events set is_draft = true where id = $1"
+ : "update app_public.events set registration_start_time = now() - interval '1 minute' where id = $1",
+ [event.id]
+ )
+ )
+ await expect(enable(client, event.id)).rejects.toHaveProperty(
+ "code",
+ "CLOSD"
+ )
+ })
+)
+
+it("reschedules pending reminders, pauses hidden events and removes deleted events' jobs", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ const reminder = await enable(client, event.id)
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set registration_start_time = registration_start_time + interval '1 hour' where id = $1",
+ [event.id]
+ )
+ )
+ const scheduled = await jobs(client, reminder.id)
+ expect(new Date(scheduled[0].run_at).getTime()).toBe(
+ new Date(event.registration_start_time).getTime() + 30 * 60000
+ )
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set is_draft = true where id = $1",
+ [event.id]
+ )
+ )
+ expect(await jobs(client, reminder.id)).toHaveLength(0)
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set is_draft = false where id = $1",
+ [event.id]
+ )
+ )
+ expect(await jobs(client, reminder.id)).toHaveLength(1)
+ await asRoot(client, () =>
+ client.query("delete from app_public.events where id = $1", [event.id])
+ )
+ expect(await jobs(client, reminder.id)).toHaveLength(0)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.event_registration_reminders"
+ )
+ ).rows
+ ).toHaveLength(0)
+ }))
+
+it("schedules immediately inside the 30-minute window", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set registration_start_time = now() + interval '10 minutes' where id = $1",
+ [event.id]
+ )
+ )
+ const reminder = await enable(client, event.id)
+ const scheduled = await jobs(client, reminder.id)
+ const {
+ rows: [row],
+ } = await client.query("select now() as now")
+ expect(new Date(scheduled[0].run_at).getTime()).toBe(
+ new Date(row.now).getTime()
+ )
+ }))
+
+it("delivers a due reminder once using real database locks and the verified primary email", () =>
+ withRootDb(async (client) => {
+ const { event, user } = await setup(client)
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set registration_start_time = now() + interval '40 minutes' where id = $1",
+ [event.id]
+ )
+ )
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 60)",
+ [event.id]
+ )
+ const reminder = (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0]
+ jest.mocked(sendEmail).mockResolvedValue(undefined)
+ process.env.ROOT_URL = "https://example.com"
+ const deliveryClient = {
+ query: (sql: string, args?: unknown[]) =>
+ client.query(
+ sql === "begin"
+ ? "savepoint reminder_delivery"
+ : sql === "commit"
+ ? "release savepoint reminder_delivery"
+ : sql === "rollback"
+ ? "rollback to savepoint reminder_delivery"
+ : sql,
+ args
+ ),
+ }
+ const helpers = {
+ withPgClient: async (callback) => callback(deliveryClient),
+ }
+ await asRoot(client, async () => {
+ await reminderTask({ id: reminder.id }, helpers as any)
+ await reminderTask({ id: reminder.id }, helpers as any)
+ })
+ expect(sendEmail).toHaveBeenCalledTimes(1)
+ expect((jest.mocked(sendEmail).mock.calls[0][0] as any).options.to).toBe(
+ user._email
+ )
+ expect(
+ (
+ await client.query(
+ "select sent_at from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ ).rows[0].sent_at
+ ).not.toBeNull()
+ }))
+
+it("updates the lead time and reschedules the existing reminder", () =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ const reminder = await enable(client, event.id)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'en', 60)",
+ [event.id]
+ )
+ const rows = (
+ await client.query(
+ "select * from app_public.event_registration_reminders"
+ )
+ ).rows
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({
+ id: reminder.id,
+ minutes_before: 60,
+ language: "en",
+ })
+ expect(
+ new Date((await jobs(client, reminder.id))[0].run_at).getTime()
+ ).toBe(new Date(event.registration_start_time).getTime() - 60 * 60000)
+ }))
+
+it.each([0, -1, 10081, null])(
+ "rejects invalid reminder lead time %s",
+ (minutes) =>
+ withRootDb(async (client) => {
+ const { event } = await setup(client)
+ await expect(
+ client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', $2)",
+ [event.id, minutes]
+ )
+ ).rejects.toHaveProperty("code", "CHECK")
+ })
+)
+
+it.each([
+ "reminder removed",
+ "account deleted",
+ "event deleted",
+ "organization deleted",
+ "event hidden",
+ "primary email removed",
+ "primary email unverified",
+ "registration opened",
+])("does not deliver an old queued job after %s", (scenario) =>
+ withRootDb(async (client) => {
+ const fixture = await setup(client)
+ const event = fixture.event
+ const user =
+ scenario === "account deleted"
+ ? (await asRoot(client, () => createUsers(client)))[0]
+ : fixture.user
+ await becomeUser(client, user.id)
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.events set registration_start_time = now() + interval '10 minutes' where id = $1",
+ [event.id]
+ )
+ )
+ const reminder = await enable(client, event.id)
+ jest.mocked(sendEmail).mockClear()
+ await asRoot(client, async () => {
+ switch (scenario) {
+ case "reminder removed":
+ await client.query(
+ "delete from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ break
+ case "account deleted":
+ await client.query(
+ "update app_public.organization_memberships set is_owner = false where user_id = $1",
+ [user.id]
+ )
+ await client.query("delete from app_public.users where id = $1", [
+ user.id,
+ ])
+ break
+ case "event deleted":
+ await client.query("delete from app_public.events where id = $1", [
+ event.id,
+ ])
+ break
+ case "organization deleted":
+ await client.query(
+ "delete from app_public.organizations where id = $1",
+ [event.owner_organization_id]
+ )
+ break
+ case "event hidden":
+ await client.query(
+ "update app_public.events set is_draft = true where id = $1",
+ [event.id]
+ )
+ break
+ case "primary email removed":
+ await client.query(
+ "insert into app_public.user_emails (user_id, email, is_verified) values ($1, 'backup-reminder@example.com', true)",
+ [user.id]
+ )
+ await client.query(
+ "delete from app_public.user_emails where user_id = $1 and is_primary",
+ [user.id]
+ )
+ break
+ case "primary email unverified":
+ await client.query(
+ "update app_public.user_emails set is_verified = false, is_primary = false where user_id = $1",
+ [user.id]
+ )
+ break
+ case "registration opened":
+ await client.query(
+ "update app_public.events set registration_start_time = now() - interval '1 minute' where id = $1",
+ [event.id]
+ )
+ break
+ }
+ if (
+ [
+ "reminder removed",
+ "account deleted",
+ "event deleted",
+ "organization deleted",
+ ].includes(scenario)
+ ) {
+ expect(
+ (
+ await client.query(
+ "select id from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ ).rows
+ ).toHaveLength(0)
+ expect(await jobs(client, reminder.id)).toHaveLength(0)
+ }
+ const deliveryClient = {
+ query: (sql: string, args?: unknown[]) =>
+ client.query(
+ sql === "begin"
+ ? "savepoint skipped_reminder"
+ : sql === "commit"
+ ? "release savepoint skipped_reminder"
+ : sql === "rollback"
+ ? "rollback to savepoint skipped_reminder"
+ : sql,
+ args
+ ),
+ }
+ await reminderTask({ id: reminder.id }, {
+ withPgClient: async (callback) => callback(deliveryClient),
+ } as any)
+ })
+ expect(sendEmail).not.toHaveBeenCalled()
+ })
+)
diff --git a/@app/db/__tests__/app_public/functions/telegram.test.ts b/@app/db/__tests__/app_public/functions/telegram.test.ts
new file mode 100644
index 000000000..5aa5435dc
--- /dev/null
+++ b/@app/db/__tests__/app_public/functions/telegram.test.ts
@@ -0,0 +1,365 @@
+import { PoolClient } from "pg"
+
+import { processTelegramUpdate } from "../../../../server/src/telegram"
+import {
+ asRoot,
+ becomeUser,
+ createEventCategories,
+ createEvents,
+ createOrganizations,
+ createUsers,
+ withRootDb,
+} from "../../helpers"
+
+async function link(client: PoolClient, chatId = 12345) {
+ const token = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ const result = await asRoot(client, () =>
+ client.query(
+ "select app_private.connect_telegram($1, $2, 'tester') as connected",
+ [token, chatId]
+ )
+ )
+ expect(result.rows[0].connected).toBe(true)
+ return token
+}
+
+it("requires login to request a linking code", () =>
+ withRootDb(async (client) => {
+ await becomeUser(client, null)
+ await expect(
+ client.query("select app_public.request_telegram_link()")
+ ).rejects.toHaveProperty("code", "LOGIN")
+ }))
+it("stores only a hash, consumes codes once, and isolates accounts", () =>
+ withRootDb(async (client) => {
+ const [user, other] = await createUsers(client, 2)
+ await becomeUser(client, user.id)
+ const token = await link(client)
+ expect(token).toMatch(/^[a-f0-9]{48}$/)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.current_telegram_account()"
+ )
+ ).rows[0].username
+ ).toBe("tester")
+ const again = await asRoot(client, () =>
+ client.query(
+ "select app_private.connect_telegram($1, 12345, 'tester') as connected",
+ [token]
+ )
+ )
+ expect(again.rows[0].connected).toBe(false)
+ await becomeUser(client, other.id)
+ expect(
+ (await client.query("select * from app_public.telegram_accounts")).rows
+ ).toHaveLength(0)
+ await expect(
+ client.query("select * from app_private.telegram_link_tokens")
+ ).rejects.toHaveProperty("code", "42501")
+ }))
+it("expires and replaces linking codes", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const old = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ const token = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ await asRoot(client, async () => {
+ expect(
+ (
+ await client.query(
+ "select app_private.connect_telegram($1, 12345, null) as connected",
+ [old]
+ )
+ ).rows[0].connected
+ ).toBe(false)
+ await client.query(
+ "update app_private.telegram_link_tokens set expires_at = now() - interval '1 minute' where user_id = $1",
+ [user.id]
+ )
+ expect(
+ (
+ await client.query(
+ "select app_private.connect_telegram($1, 12345, null) as connected",
+ [token]
+ )
+ ).rows[0].connected
+ ).toBe(false)
+ })
+ }))
+it("does not transfer a Telegram chat between Ilmo accounts", () =>
+ withRootDb(async (client) => {
+ const [first, second] = await createUsers(client, 2)
+ await becomeUser(client, first.id)
+ await link(client)
+ await becomeUser(client, second.id)
+ const token = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ await asRoot(client, async () => {
+ expect(
+ (
+ await client.query(
+ "select app_private.connect_telegram($1, 12345, null) as connected",
+ [token]
+ )
+ ).rows[0].connected
+ ).toBe(false)
+ expect(
+ (
+ await client.query(
+ "select user_id from app_public.telegram_accounts where chat_id = 12345"
+ )
+ ).rows[0].user_id
+ ).toBe(first.id)
+ })
+ }))
+it("schedules both channels and disconnecting preserves only email", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ await link(client)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'both')",
+ [event.id]
+ )
+ const reminder = (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0]
+ await asRoot(client, async () => {
+ const jobs = (
+ await client.query(
+ "select key from graphile_worker._private_jobs where key like $1",
+ [`registration-reminder:${reminder.id}%`]
+ )
+ ).rows
+ expect(jobs).toHaveLength(2)
+ })
+ await client.query("select app_public.disconnect_telegram()")
+ expect(
+ (
+ await client.query(
+ "select * from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ ).rows[0].delivery_method
+ ).toBe("email")
+ await asRoot(client, async () => {
+ expect(
+ (
+ await client.query(
+ "select key from graphile_worker._private_jobs where key = $1",
+ [`registration-reminder:${reminder.id}:telegram`]
+ )
+ ).rows
+ ).toHaveLength(0)
+ })
+ }))
+it("deduplicates /start updates and ignores commands in groups", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const token = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ await asRoot(client, async () => {
+ const update = {
+ update_id: 1024,
+ message: {
+ text: `/start ${token}`,
+ chat: { type: "private", id: 12345 },
+ from: { id: 12345, username: "tester" },
+ },
+ }
+ await processTelegramUpdate(client, {
+ ...update,
+ message: { ...update.message, chat: { type: "group", id: -12345 } },
+ })
+ expect(
+ (
+ await client.query(
+ "select * from app_public.telegram_accounts where user_id = $1",
+ [user.id]
+ )
+ ).rows
+ ).toHaveLength(0)
+ const valid = { ...update, update_id: 1025 }
+ await processTelegramUpdate(client, valid)
+ await processTelegramUpdate(client, valid)
+ expect(
+ (
+ await client.query(
+ "select * from app_public.telegram_accounts where user_id = $1",
+ [user.id]
+ )
+ ).rows
+ ).toHaveLength(1)
+ expect(
+ (
+ await client.query(
+ "select * from graphile_worker._private_jobs j join graphile_worker._private_tasks t on j.task_id = t.id where t.identifier = 'telegram__reply'"
+ )
+ ).rows
+ ).toHaveLength(1)
+ await processTelegramUpdate(client, {
+ update_id: 1026,
+ message: {
+ text: "/stop",
+ chat: { id: 12345, type: "private" },
+ from: { id: 12345 },
+ },
+ })
+ expect(
+ (
+ await client.query(
+ "select * from app_public.telegram_accounts where user_id = $1",
+ [user.id]
+ )
+ ).rows
+ ).toHaveLength(0)
+ })
+ }))
+
+it("allows Telegram-only reminders without a verified email and removes them on disconnect", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client, 1, false)
+ await becomeUser(client, user.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ await link(client)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'telegram')",
+ [event.id]
+ )
+ const reminder = (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0]
+ await client.query("select app_public.disconnect_telegram()")
+ expect(
+ (
+ await client.query(
+ "select id from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ ).rows
+ ).toHaveLength(0)
+ await asRoot(client, async () => {
+ expect(
+ (
+ await client.query(
+ "select key from graphile_worker._private_jobs where key like $1",
+ [`registration-reminder:${reminder.id}%`]
+ )
+ ).rows
+ ).toHaveLength(0)
+ })
+ }))
+it("rejects Telegram delivery until the user links a chat", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ await expect(
+ client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'telegram')",
+ [event.id]
+ )
+ ).rejects.toHaveProperty("code", "CHECK")
+ }))
+it("marks a partially delivered both reminder complete when switched to the delivered channel", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ await link(client)
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'both')",
+ [event.id]
+ )
+ await asRoot(client, () =>
+ client.query(
+ "update app_public.event_registration_reminders set email_sent_at = now() where event_id = $1",
+ [event.id]
+ )
+ )
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'email')",
+ [event.id]
+ )
+ expect(
+ (
+ await client.query(
+ "select sent_at from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0].sent_at
+ ).not.toBeNull()
+ }))
+it("removes a deleted subscriber's link, tokens, reminders and both jobs", () =>
+ withRootDb(async (client) => {
+ const [owner, subscriber] = await createUsers(client, 2)
+ await becomeUser(client, owner.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ await becomeUser(client, subscriber.id)
+ await link(client)
+ await client.query("select app_public.request_telegram_link()")
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'both')",
+ [event.id]
+ )
+ const reminder = (
+ await client.query(
+ "select id from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0]
+ await asRoot(client, async () => {
+ await client.query("delete from app_public.users where id = $1", [
+ subscriber.id,
+ ])
+ for (const table of [
+ "app_public.telegram_accounts",
+ "app_private.telegram_link_tokens",
+ "app_public.event_registration_reminders",
+ ]) {
+ expect(
+ (
+ await client.query(
+ `select user_id from ${table} where user_id = $1`,
+ [subscriber.id]
+ )
+ ).rows
+ ).toHaveLength(0)
+ }
+ expect(
+ (
+ await client.query(
+ "select key from graphile_worker._private_jobs where key like $1",
+ [`registration-reminder:${reminder.id}%`]
+ )
+ ).rows
+ ).toHaveLength(0)
+ })
+ }))
diff --git a/@app/db/__tests__/app_public/functions/telegram_language.test.ts b/@app/db/__tests__/app_public/functions/telegram_language.test.ts
new file mode 100644
index 000000000..ac9343c70
--- /dev/null
+++ b/@app/db/__tests__/app_public/functions/telegram_language.test.ts
@@ -0,0 +1,236 @@
+import { telegramRequest } from "@app/lib/dist/cjs/telegram"
+
+import {
+ processTelegramUpdate,
+ TelegramUpdate,
+} from "../../../../server/src/telegram"
+import telegramReminder from "../../../../worker/src/tasks/reminder__send_telegram"
+import {
+ asRoot,
+ becomeUser,
+ createEventCategories,
+ createEvents,
+ createOrganizations,
+ createUsers,
+ withRootDb,
+} from "../../helpers"
+
+jest.mock("@app/lib/dist/cjs/telegram", () => ({
+ ...jest.requireActual("@app/lib/dist/cjs/telegram"),
+ telegramRequest: jest.fn(),
+}))
+
+function message(
+ update_id: number,
+ text: string,
+ language_code?: string
+): TelegramUpdate {
+ return {
+ update_id,
+ message: {
+ text,
+ chat: { id: 12345, type: "private" },
+ from: { id: 12345, language_code },
+ },
+ }
+}
+
+it("detects language, preserves explicit choices, and supports returning to automatic", () =>
+ withRootDb(async (client) => {
+ const preferences = async () =>
+ (
+ await client.query(
+ "select * from app_private.telegram_preferences where chat_id = 12345"
+ )
+ ).rows[0]
+ await asRoot(client, async () => {
+ await processTelegramUpdate(client, message(100, "/start", "fi-FI"))
+ expect(await preferences()).toMatchObject({
+ language: "auto",
+ detected_language: "fi",
+ })
+ await processTelegramUpdate(client, message(101, "/language en", "fi"))
+ await processTelegramUpdate(client, message(102, "/start", "fi"))
+ expect(await preferences()).toMatchObject({
+ language: "en",
+ detected_language: "fi",
+ })
+ await processTelegramUpdate(client, message(103, "/language auto", "fi"))
+ await processTelegramUpdate(client, message(104, "/start"))
+ expect(await preferences()).toMatchObject({
+ language: "auto",
+ detected_language: "fi",
+ })
+ await processTelegramUpdate(client, message(105, "/start", "sv"))
+ expect(await preferences()).toMatchObject({
+ language: "auto",
+ detected_language: "en",
+ })
+ })
+ }))
+it("validates button ownership and deduplicates language changes", () =>
+ withRootDb(async (client) =>
+ asRoot(client, async () => {
+ const update: TelegramUpdate = {
+ update_id: 200,
+ callback_query: {
+ id: "cb",
+ data: "language:fi",
+ from: { id: 12345, language_code: "en" },
+ message: { chat: { id: 12345, type: "private" } },
+ },
+ }
+ await processTelegramUpdate(client, update)
+ await processTelegramUpdate(client, update)
+ expect(
+ (
+ await client.query(
+ "select language from app_private.telegram_preferences where chat_id = 12345"
+ )
+ ).rows[0].language
+ ).toBe("fi")
+ const jobs = (
+ await client.query(
+ "select j.payload from graphile_worker._private_jobs j join graphile_worker._private_tasks t on t.id = j.task_id where t.identifier = 'telegram__reply'"
+ )
+ ).rows
+ expect(jobs).toHaveLength(1)
+ expect(jobs[0].payload).toMatchObject({
+ chatId: 12345,
+ reply: "languageSaved",
+ callbackQueryId: "cb",
+ })
+ await processTelegramUpdate(client, {
+ ...update,
+ update_id: 201,
+ callback_query: {
+ ...update.callback_query!,
+ from: { id: 54321 },
+ data: "language:en",
+ },
+ })
+ await processTelegramUpdate(client, {
+ ...update,
+ update_id: 202,
+ callback_query: {
+ ...update.callback_query!,
+ message: { chat: { id: 12345, type: "group" } },
+ data: "language:en",
+ },
+ })
+ expect(
+ (
+ await client.query(
+ "select language from app_private.telegram_preferences where chat_id = 12345"
+ )
+ ).rows[0].language
+ ).toBe("fi")
+ })
+ ))
+it("falls back to English for a new chat without a language hint and prompts for invalid choices", () =>
+ withRootDb(async (client) =>
+ asRoot(client, async () => {
+ await processTelegramUpdate(client, message(300, "/language unsupported"))
+ expect(
+ (
+ await client.query(
+ "select * from app_private.telegram_preferences where chat_id = 12345"
+ )
+ ).rows[0]
+ ).toMatchObject({ language: "auto", detected_language: "en" })
+ const jobs = (
+ await client.query(
+ "select j.payload from graphile_worker._private_jobs j join graphile_worker._private_tasks t on t.id = j.task_id where t.identifier = 'telegram__reply'"
+ )
+ ).rows
+ expect(jobs[0].payload.reply).toBe("languageMenu")
+ })
+ ))
+it("retains preferences after disconnecting and keeps them private", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await asRoot(client, async () => {
+ await processTelegramUpdate(client, message(400, "/language fi", "en"))
+ await processTelegramUpdate(client, message(401, "/stop", "en"))
+ expect(
+ (
+ await client.query(
+ "select language from app_private.telegram_preferences where chat_id = 12345"
+ )
+ ).rows[0].language
+ ).toBe("fi")
+ })
+ await becomeUser(client, user.id)
+ await expect(
+ client.query("select * from app_private.telegram_preferences")
+ ).rejects.toHaveProperty("code", "42501")
+ }))
+
+it("delivers an already scheduled reminder in the newly selected bot language", () =>
+ withRootDb(async (client) => {
+ const [user] = await createUsers(client)
+ await becomeUser(client, user.id)
+ const [org] = await createOrganizations(client, 1)
+ const [category] = await createEventCategories(client, 1, org.id)
+ const [event] = await createEvents(client, 1, org.id, category.id, false)
+ const token = (
+ await client.query("select app_public.request_telegram_link() as token")
+ ).rows[0].token
+ await asRoot(client, async () => {
+ await processTelegramUpdate(client, message(500, `/start ${token}`, "fi"))
+ await client.query(
+ "update app_public.events set registration_start_time = now() + interval '10 minutes' where id = $1",
+ [event.id]
+ )
+ })
+ await client.query(
+ "select app_public.set_event_registration_reminder($1, true, 'fi', 30, 'telegram')",
+ [event.id]
+ )
+ const reminder = (
+ await client.query(
+ "select * from app_public.event_registration_reminders where event_id = $1",
+ [event.id]
+ )
+ ).rows[0]
+ await asRoot(client, async () => {
+ await processTelegramUpdate(client, message(501, "/language en", "fi"))
+ jest.mocked(telegramRequest).mockResolvedValue({})
+ process.env.ROOT_URL = "https://example.com"
+ const deliveryClient = {
+ query: (sql: string, args?: unknown[]) =>
+ client.query(
+ sql === "begin"
+ ? "savepoint bot_language_delivery"
+ : sql === "commit"
+ ? "release savepoint bot_language_delivery"
+ : sql === "rollback"
+ ? "rollback to savepoint bot_language_delivery"
+ : sql,
+ args
+ ),
+ }
+ await telegramReminder({ id: reminder.id }, {
+ withPgClient: async (callback) => callback(deliveryClient),
+ } as any)
+ expect(telegramRequest).toHaveBeenCalledWith(
+ "sendMessage",
+ expect.objectContaining({
+ text: expect.stringContaining("Registration reminder"),
+ reply_markup: {
+ inline_keyboard: [
+ [expect.objectContaining({ text: "Open event" })],
+ ],
+ },
+ })
+ )
+ const stored = (
+ await client.query(
+ "select language, telegram_sent_at from app_public.event_registration_reminders where id = $1",
+ [reminder.id]
+ )
+ ).rows[0]
+ expect(stored.language).toBe("fi")
+ expect(stored.telegram_sent_at).not.toBeNull()
+ })
+ }))
diff --git a/@app/db/migrations/committed/000005.sql b/@app/db/migrations/committed/000005.sql
new file mode 100644
index 000000000..26dd6bf4f
--- /dev/null
+++ b/@app/db/migrations/committed/000005.sql
@@ -0,0 +1,332 @@
+--! Previous: sha1:eafce160dd3a8ec859a47bc11b5c9117cc07fd8e
+--! Hash: sha1:4f00de0a12fe4f8d48132d1d2169088bcef24109
+
+--! split: 3-registration-reminders.sql
+-- Telegram chat identifiers are only exposed to the server, never in GraphQL.
+create table if not exists app_public.telegram_accounts (
+ user_id uuid primary key references app_public.users(id) on delete cascade,
+ chat_id bigint not null unique check (chat_id > 0),
+ username text,
+ created_at timestamptz not null default now()
+);
+comment on table app_public.telegram_accounts is E'@omit create,update,delete\nTelegram accounts linked by their owners.';
+comment on column app_public.telegram_accounts.chat_id is E'@omit';
+alter table app_public.telegram_accounts enable row level security;
+drop policy if exists own_telegram_account on app_public.telegram_accounts;
+create policy own_telegram_account on app_public.telegram_accounts
+ using (user_id = app_public.current_user_id());
+grant select on app_public.telegram_accounts to :DATABASE_VISITOR;
+
+create table if not exists app_private.telegram_link_tokens (
+ user_id uuid primary key references app_public.users(id) on delete cascade,
+ token_hash bytea not null unique,
+ expires_at timestamptz not null
+);
+revoke all on app_private.telegram_link_tokens from public;
+
+create or replace function app_public.current_telegram_account()
+returns app_public.telegram_accounts as $$
+ select * from app_public.telegram_accounts where user_id = app_public.current_user_id();
+$$ language sql stable;
+grant execute on function app_public.current_telegram_account() to :DATABASE_VISITOR;
+
+create or replace function app_public.request_telegram_link() returns text as $$
+declare
+ v_user uuid := app_public.current_user_id();
+ v_token text := encode(public.gen_random_bytes(24), 'hex');
+begin
+ if v_user is null then
+ raise exception 'Sign in to connect Telegram.' using errcode = 'LOGIN';
+ end if;
+ insert into app_private.telegram_link_tokens(user_id, token_hash, expires_at)
+ values(v_user, public.digest(v_token, 'sha256'), now() + interval '15 minutes')
+ on conflict (user_id) do update set token_hash = excluded.token_hash, expires_at = excluded.expires_at;
+ return v_token;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.request_telegram_link() from public;
+grant execute on function app_public.request_telegram_link() to :DATABASE_VISITOR;
+
+-- Only trusted bot-update processing may consume a linking code.
+create or replace function app_private.connect_telegram(token text, chat_id bigint, username text)
+returns boolean as $$
+#variable_conflict use_variable
+declare
+ v_user uuid;
+begin
+ if chat_id is null or chat_id <= 0 then return false; end if;
+ delete from app_private.telegram_link_tokens t
+ where t.token_hash = public.digest(token, 'sha256') and t.expires_at > clock_timestamp()
+ returning t.user_id into v_user;
+ if v_user is null then return false; end if;
+ -- Do not silently move somebody else's Telegram chat to another account.
+ if exists(select 1 from app_public.telegram_accounts a where a.chat_id = chat_id and a.user_id <> v_user) then
+ return false;
+ end if;
+ insert into app_public.telegram_accounts(user_id, chat_id, username)
+ values(v_user, chat_id, username)
+ on conflict (user_id) do update set chat_id = excluded.chat_id, username = excluded.username;
+ return true;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_private.connect_telegram(text, bigint, text) from public;
+
+create table if not exists app_public.event_registration_reminders (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references app_public.users(id) on delete cascade,
+ event_id uuid not null references app_public.events(id) on delete cascade,
+ language text not null default 'fi' check (language in ('fi', 'en')),
+ minutes_before integer not null default 30 check (minutes_before between 1 and 10080),
+ delivery_method text not null default 'email' check (delivery_method in ('email', 'telegram', 'both')),
+ email_sent_at timestamptz,
+ telegram_sent_at timestamptz,
+ created_at timestamptz not null default now(),
+ sent_at timestamptz,
+ unique (user_id, event_id)
+);
+alter table app_public.event_registration_reminders add column if not exists minutes_before integer not null default 30 check (minutes_before between 1 and 10080);
+alter table app_public.event_registration_reminders add column if not exists delivery_method text not null default 'email' check (delivery_method in ('email', 'telegram', 'both'));
+alter table app_public.event_registration_reminders add column if not exists email_sent_at timestamptz;
+alter table app_public.event_registration_reminders add column if not exists telegram_sent_at timestamptz;
+update app_public.event_registration_reminders set email_sent_at = sent_at where sent_at is not null and email_sent_at is null and delivery_method = 'email';
+create index if not exists event_registration_reminders_event_id_idx
+ on app_public.event_registration_reminders(event_id);
+
+comment on table app_public.event_registration_reminders is E'@omit create,update\nRegistration reminders requested by the current user, before registration opens.';
+alter table app_public.event_registration_reminders enable row level security;
+drop policy if exists own_reminders on app_public.event_registration_reminders;
+create policy own_reminders on app_public.event_registration_reminders
+ using (user_id = app_public.current_user_id());
+grant select, delete on app_public.event_registration_reminders to :DATABASE_VISITOR;
+
+create or replace function app_private.schedule_registration_reminder(reminder_id uuid)
+returns void as $$
+declare
+ v_due timestamptz;
+ v_reminder app_public.event_registration_reminders;
+ v_key text := 'registration-reminder:' || reminder_id::text;
+begin
+ select * into v_reminder from app_public.event_registration_reminders where id = reminder_id;
+ select e.registration_start_time - make_interval(mins => v_reminder.minutes_before) into v_due
+ from app_public.events e where e.id = v_reminder.event_id
+ and v_reminder.sent_at is null and not e.is_draft and e.registration_start_time > now();
+ if v_due is not null and v_reminder.delivery_method in ('email', 'both') and v_reminder.email_sent_at is null then
+ perform graphile_worker.add_job('reminder__send_registration', json_build_object('id', reminder_id),
+ run_at := greatest(now(), v_due), job_key := v_key);
+ else
+ perform graphile_worker.remove_job(v_key);
+ end if;
+ if v_due is not null and v_reminder.delivery_method in ('telegram', 'both') and v_reminder.telegram_sent_at is null then
+ perform graphile_worker.add_job('reminder__send_telegram', json_build_object('id', reminder_id),
+ run_at := greatest(now(), v_due), job_key := v_key || ':telegram', queue_name := 'telegram-reminders');
+ else
+ perform graphile_worker.remove_job(v_key || ':telegram');
+ end if;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_private.schedule_registration_reminder(uuid) from public;
+
+create or replace function app_private.tg__schedule_registration_reminder()
+returns trigger as $$
+begin
+ if TG_OP = 'DELETE' then
+ perform graphile_worker.remove_job('registration-reminder:' || OLD.id::text);
+ perform graphile_worker.remove_job('registration-reminder:' || OLD.id::text || ':telegram');
+ return OLD;
+ end if;
+ perform app_private.schedule_registration_reminder(NEW.id);
+ return NEW;
+end;
+$$ language plpgsql security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_private.tg__schedule_registration_reminder() from public;
+drop trigger if exists schedule_registration_reminder on app_public.event_registration_reminders;
+create trigger schedule_registration_reminder after insert or delete or update of minutes_before, delivery_method
+ on app_public.event_registration_reminders for each row
+ execute function app_private.tg__schedule_registration_reminder();
+
+create or replace function app_private.tg__reschedule_registration_reminders()
+returns trigger as $$
+declare
+ v_id uuid;
+begin
+ for v_id in select id from app_public.event_registration_reminders
+ where event_id = NEW.id and sent_at is null
+ loop
+ perform app_private.schedule_registration_reminder(v_id);
+ end loop;
+ return NEW;
+end;
+$$ language plpgsql security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_private.tg__reschedule_registration_reminders() from public;
+drop trigger if exists reschedule_registration_reminders on app_public.events;
+create trigger reschedule_registration_reminders
+ after update of registration_start_time, is_draft on app_public.events
+ for each row execute function app_private.tg__reschedule_registration_reminders();
+
+drop function if exists app_public.set_event_registration_reminder(uuid, boolean, text);
+drop function if exists app_public.set_event_registration_reminder(uuid, boolean, text, integer);
+create or replace function app_public.set_event_registration_reminder(
+ event_id uuid, enabled boolean, language text default 'fi', minutes_before integer default 30, delivery_method text default 'email'
+) returns boolean as $$
+#variable_conflict use_variable
+declare
+ v_user uuid := app_public.current_user_id();
+begin
+ if v_user is null then
+ raise exception 'Please sign in to manage reminders.' using errcode = 'LOGIN';
+ end if;
+ if not enabled then
+ delete from app_public.event_registration_reminders r
+ where r.user_id = v_user and r.event_id = event_id;
+ return false;
+ end if;
+ if minutes_before is null or minutes_before < 1 or minutes_before > 10080 then
+ raise exception 'Choose a reminder between 1 minute and 7 days before opening.' using errcode = 'CHECK';
+ end if;
+ if language not in ('fi', 'en') or language is null then
+ raise exception 'Unsupported reminder language.' using errcode = 'CHECK';
+ end if;
+ if delivery_method is null or delivery_method not in ('email', 'telegram', 'both') then
+ raise exception 'Unsupported delivery method.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('telegram', 'both') and not exists(select 1 from app_public.telegram_accounts where user_id = v_user) then
+ raise exception 'Connect Telegram before enabling Telegram reminders.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('email', 'both') and not exists(select 1 from app_public.user_emails
+ where user_id = v_user and is_primary and is_verified) then
+ raise exception 'Verify your primary email before enabling reminders.' using errcode = 'EMAIL';
+ end if;
+ perform 1 from app_public.events e where e.id = event_id
+ and not e.is_draft and e.registration_start_time > now() for share;
+ if not found then
+ raise exception 'Reminders are only available before registration opens.' using errcode = 'CLOSD';
+ end if;
+ insert into app_public.event_registration_reminders(user_id, event_id, language, minutes_before, delivery_method)
+ values (v_user, event_id, language, minutes_before, delivery_method)
+ on conflict on constraint event_registration_reminders_user_id_event_id_key do update
+ set minutes_before = excluded.minutes_before, language = excluded.language, delivery_method = excluded.delivery_method,
+ sent_at = case
+ when excluded.delivery_method = 'email' then event_registration_reminders.email_sent_at
+ when excluded.delivery_method = 'telegram' then event_registration_reminders.telegram_sent_at
+ when event_registration_reminders.email_sent_at is not null and event_registration_reminders.telegram_sent_at is not null
+ then greatest(event_registration_reminders.email_sent_at, event_registration_reminders.telegram_sent_at)
+ else null end
+ where event_registration_reminders.sent_at is null;
+ return true;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.set_event_registration_reminder(uuid, boolean, text, integer, text) from public;
+grant execute on function app_public.set_event_registration_reminder(uuid, boolean, text, integer, text) to :DATABASE_VISITOR;
+
+-- Unlinking cancels Telegram-only reminders and preserves email delivery for both.
+create or replace function app_private.disconnect_telegram(target_user uuid) returns void as $$
+begin
+ delete from app_public.event_registration_reminders where user_id = target_user and delivery_method = 'telegram' and sent_at is null;
+ update app_public.event_registration_reminders set delivery_method = 'email', sent_at = email_sent_at
+ where user_id = target_user and delivery_method = 'both' and sent_at is null;
+ delete from app_private.telegram_link_tokens where user_id = target_user;
+ delete from app_public.telegram_accounts where user_id = target_user;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_private.disconnect_telegram(uuid) from public;
+
+create or replace function app_public.disconnect_telegram() returns boolean as $$
+begin
+ if app_public.current_user_id() is null then
+ raise exception 'Sign in to disconnect Telegram.' using errcode = 'LOGIN';
+ end if;
+ perform app_private.disconnect_telegram(app_public.current_user_id());
+ return true;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.disconnect_telegram() from public;
+grant execute on function app_public.disconnect_telegram() to :DATABASE_VISITOR;
+
+-- Checkpoints survive polling restarts. A transaction claims each update once.
+create table if not exists app_private.telegram_updates (
+ update_id bigint primary key,
+ processed_at timestamptz not null default now()
+);
+create table if not exists app_private.telegram_poll_state (
+ id boolean primary key default true check(id),
+ next_offset bigint not null default 0
+);
+insert into app_private.telegram_poll_state(id) values(true) on conflict do nothing;
+
+--! split: 4-reminder-preferences.sql
+-- An absent row means the user has not completed reminder setup.
+create table if not exists app_public.reminder_preferences (
+ user_id uuid primary key references app_public.users(id) on delete cascade,
+ minutes_before integer not null check (minutes_before between 1 and 10080),
+ delivery_method text not null check (delivery_method in ('email', 'telegram', 'both'))
+);
+comment on table app_public.reminder_preferences is E'@omit create,update,delete\nDefaults for newly enabled registration reminders. Existing reminders retain their settings.';
+alter table app_public.reminder_preferences enable row level security;
+drop policy if exists own_reminder_preferences on app_public.reminder_preferences;
+create policy own_reminder_preferences on app_public.reminder_preferences
+ using (user_id = app_public.current_user_id());
+grant select on app_public.reminder_preferences to :DATABASE_VISITOR;
+
+create or replace function app_public.current_reminder_preferences()
+returns app_public.reminder_preferences as $$
+ select * from app_public.reminder_preferences where user_id = app_public.current_user_id();
+$$ language sql stable;
+grant execute on function app_public.current_reminder_preferences() to :DATABASE_VISITOR;
+
+create or replace function app_public.save_reminder_preferences(minutes_before integer, delivery_method text)
+returns app_public.reminder_preferences as $$
+#variable_conflict use_variable
+declare
+ v_user uuid := app_public.current_user_id();
+ v_preferences app_public.reminder_preferences;
+begin
+ if v_user is null then
+ raise exception 'Sign in to manage reminder preferences.' using errcode = 'LOGIN';
+ end if;
+ if minutes_before is null or minutes_before not between 1 and 10080
+ or delivery_method is null or delivery_method not in ('email', 'telegram', 'both') then
+ raise exception 'Choose a delivery method and a lead time between 1 minute and 7 days.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('telegram', 'both') and not exists(select 1 from app_public.telegram_accounts where user_id = v_user) then
+ raise exception 'Connect Telegram before saving Telegram reminders.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('email', 'both') and not exists(select 1 from app_public.user_emails where user_id = v_user and is_primary and is_verified) then
+ raise exception 'Verify your primary email before saving reminders.' using errcode = 'EMAIL';
+ end if;
+ insert into app_public.reminder_preferences as p(user_id, minutes_before, delivery_method)
+ values(v_user, minutes_before, delivery_method)
+ on conflict(user_id) do update set minutes_before = excluded.minutes_before, delivery_method = excluded.delivery_method
+ returning * into v_preferences;
+ return v_preferences;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.save_reminder_preferences(integer, text) from public;
+grant execute on function app_public.save_reminder_preferences(integer, text) to :DATABASE_VISITOR;
+
+create or replace function app_public.enable_event_reminder(event_id uuid, language text default 'fi')
+returns boolean as $$
+declare
+ v_preferences app_public.reminder_preferences;
+begin
+ if app_public.current_user_id() is null then
+ raise exception 'Sign in to enable reminders.' using errcode = 'LOGIN';
+ end if;
+ select * into v_preferences from app_public.reminder_preferences where user_id = app_public.current_user_id();
+ if not found then
+ raise exception 'Set up reminder preferences first.' using errcode = 'CHECK';
+ end if;
+ return app_public.set_event_registration_reminder(event_id, true, language, v_preferences.minutes_before, v_preferences.delivery_method);
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.enable_event_reminder(uuid, text) from public;
+grant execute on function app_public.enable_event_reminder(uuid, text) to :DATABASE_VISITOR;
+
+--! split: 5-telegram-language.sql
+-- Bot preferences belong to a private Telegram chat, including before linking.
+-- Retain them across /stop and reconnect; never expose chat IDs in GraphQL.
+create table if not exists app_private.telegram_preferences (
+ chat_id bigint primary key check (chat_id > 0),
+ language text not null default 'auto' check (language in ('auto', 'fi', 'en')),
+ detected_language text not null default 'en' check (detected_language in ('fi', 'en'))
+);
+revoke all on app_private.telegram_preferences from public;
diff --git a/@app/db/migrations/committed/000006.sql b/@app/db/migrations/committed/000006.sql
new file mode 100644
index 000000000..be0155a7d
--- /dev/null
+++ b/@app/db/migrations/committed/000006.sql
@@ -0,0 +1,52 @@
+--! Previous: sha1:4f00de0a12fe4f8d48132d1d2169088bcef24109
+--! Hash: sha1:f24e757e035de70b0a8c328d3522f2b23901a9e8
+
+--! split: 3-reminder-preference-updates.sql
+create or replace function app_public.save_reminder_preferences(minutes_before integer, delivery_method text)
+returns app_public.reminder_preferences as $$
+#variable_conflict use_variable
+declare
+ v_user uuid := app_public.current_user_id();
+ v_preferences app_public.reminder_preferences;
+begin
+ if v_user is null then
+ raise exception 'Sign in to manage reminder preferences.' using errcode = 'LOGIN';
+ end if;
+ if minutes_before is null or minutes_before not between 1 and 10080
+ or delivery_method is null or delivery_method not in ('email', 'telegram', 'both') then
+ raise exception 'Choose a delivery method and a lead time between 1 minute and 7 days.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('telegram', 'both') and not exists(select 1 from app_public.telegram_accounts where user_id = v_user) then
+ raise exception 'Connect Telegram before saving Telegram reminders.' using errcode = 'CHECK';
+ end if;
+ if delivery_method in ('email', 'both') and not exists(select 1 from app_public.user_emails where user_id = v_user and is_primary and is_verified) then
+ raise exception 'Verify your primary email before saving reminders.' using errcode = 'EMAIL';
+ end if;
+ insert into app_public.reminder_preferences as p(user_id, minutes_before, delivery_method)
+ values(v_user, minutes_before, delivery_method)
+ on conflict(user_id) do update set minutes_before = excluded.minutes_before, delivery_method = excluded.delivery_method
+ returning * into v_preferences;
+ -- Lock reminders in a stable order before rescheduling them.
+ perform 1 from app_public.event_registration_reminders r
+ join app_public.events e on e.id = r.event_id
+ where r.user_id = v_user and r.sent_at is null and e.registration_start_time > now()
+ order by r.id for update of r;
+ update app_public.event_registration_reminders r
+ set minutes_before = v_preferences.minutes_before,
+ delivery_method = v_preferences.delivery_method,
+ sent_at = case
+ when v_preferences.delivery_method = 'email' then r.email_sent_at
+ when v_preferences.delivery_method = 'telegram' then r.telegram_sent_at
+ when r.email_sent_at is not null and r.telegram_sent_at is not null
+ then greatest(r.email_sent_at, r.telegram_sent_at)
+ else null end
+ from app_public.events e
+ where r.user_id = v_user and r.event_id = e.id
+ and r.sent_at is null and e.registration_start_time > now();
+ return v_preferences;
+end;
+$$ language plpgsql volatile security definer set search_path = pg_catalog, public, pg_temp;
+revoke all on function app_public.save_reminder_preferences(integer, text) from public;
+grant execute on function app_public.save_reminder_preferences(integer, text) to :DATABASE_VISITOR;
+
+comment on table app_public.reminder_preferences is E'@omit create,update,delete\nDelivery and timing preferences for upcoming registration reminders.';
diff --git a/@app/db/package.json b/@app/db/package.json
index 90e80d42d..c1b580e24 100644
--- a/@app/db/package.json
+++ b/@app/db/package.json
@@ -22,6 +22,7 @@
"devDependencies": {
"@app/config": "workspace:*",
"@app/graphql": "workspace:*",
+ "@app/lib": "workspace:*",
"@faker-js/faker": "^9.3.0",
"@types/pg": "^8.11.10",
"jest": "^29.7.0",
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/e2e/cypress/e2e/reminders.spec.ts b/@app/e2e/cypress/e2e/reminders.spec.ts
new file mode 100644
index 000000000..271a77227
--- /dev/null
+++ b/@app/e2e/cypress/e2e/reminders.spec.ts
@@ -0,0 +1,87 @@
+///
+
+context("Registration reminder preferences", () => {
+ beforeEach(() => cy.serverCommand("clearTestUsers"))
+ beforeEach(() => cy.serverCommand("clearTestEventData"))
+ beforeEach(() => cy.serverCommand("clearTestOrganizations"))
+
+ it("sets up once, persists preferences, and enables again without onboarding", () => {
+ cy.serverCommand("createTestEventData", { eventSignupUpcoming: true }).then(
+ ({ event }: any) => {
+ cy.login({
+ username: "testuser",
+ password: "DOESNT MATTER",
+ existingUser: true,
+ })
+ cy.visit(`${Cypress.env("ROOT_URL")}/en/event/${event.slug}`)
+ cy.getCy("event-reminder").should("contain", "Don’t miss registration!")
+ cy.getCy("event-reminder").should(
+ "not.contain",
+ "Registration reminder"
+ )
+ cy.getCy("event-reminder").find(".ant-alert").should("not.exist")
+ cy.getCy("event-reminder-toggle")
+ .should("not.be.disabled")
+ .and("contain", "Set reminder")
+ cy.getCy("event-reminder")
+ .contains("Change reminder settings")
+ .should("not.exist")
+ cy.getCy("event-reminder-toggle").click()
+ cy.get(".ant-modal:visible").should("exist")
+ cy.getCy("reminder-preferences-channel").click()
+ cy.get(".ant-select-dropdown:visible").contains("Email").click()
+ cy.getCy("reminder-preferences-next").should("not.be.disabled").click()
+ cy.getCy("reminder-preferences-time").click()
+ cy.get(".ant-select-dropdown:visible")
+ .contains("15 minutes before")
+ .click()
+ cy.getCy("reminder-preferences-save").click()
+ cy.get(".ant-modal:visible").should("not.exist")
+ cy.getCy("event-reminder-toast")
+ .should("be.visible")
+ .and("contain", "Reminder set!")
+ .and("contain", "Delivery method: Email")
+ .and("contain", "15 minutes before registration opens")
+ cy.getCy("event-reminder-toast-settings")
+ .should("contain", "Change reminder settings")
+ .and("have.attr", "href")
+ .and("match", /\/settings\/reminders$/)
+ cy.getCy("event-reminder-toggle").should("contain", "Remove reminder")
+ cy.getCy("event-reminder-status").should("contain", "Reminder set")
+ // The toast is temporary; the footer keeps the enabled state.
+ cy.get('[data-cy="event-reminder-toast"]', { timeout: 15000 }).should(
+ "not.exist"
+ )
+ cy.getCy("event-reminder-status").should("contain", "Reminder set")
+
+ cy.reload()
+ cy.getCy("event-reminder-toggle").should("not.be.disabled").click()
+ cy.getCy("event-reminder").should("contain", "Set reminder")
+ cy.getCy("event-reminder-toggle").should("not.be.disabled").click()
+ cy.get(".ant-modal:visible").should("not.exist")
+ cy.getCy("event-reminder-toast").should("contain", "Reminder set")
+ cy.getCy("event-reminder-toggle").should("contain", "Remove reminder")
+
+ cy.visit(`${Cypress.env("ROOT_URL")}/en/settings/reminders`)
+ cy.getCy("reminder-preferences-edit").should("exist")
+ cy.contains("15 minutes before registration opens").should("exist")
+ cy.getCy("reminder-cancel").click()
+ cy.contains("You have no registration reminders.").should("exist")
+ }
+ )
+ })
+
+ it("asks signed-out users to sign in", () => {
+ cy.serverCommand("createTestEventData", { eventSignupUpcoming: true }).then(
+ ({ event }: any) => {
+ cy.visit(`${Cypress.env("ROOT_URL")}/en/event/${event.slug}`)
+ cy.getCy("event-reminder").should("contain", "Don’t miss registration!")
+ cy.getCy("event-reminder-sign-in")
+ .should("contain", "Sign in")
+ .and("have.attr", "href")
+ .and("contain", "/login?next=")
+ cy.getCy("event-reminder-toggle").should("not.exist")
+ }
+ )
+ })
+})
diff --git a/@app/graphql/.persisted_operations/16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad.graphql b/@app/graphql/.persisted_operations/16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad.graphql
new file mode 100644
index 000000000..4c5573eac
--- /dev/null
+++ b/@app/graphql/.persisted_operations/16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad.graphql
@@ -0,0 +1,36 @@
+query EventRegistrationReminder($eventId: UUID!) {
+ currentUser {
+ id
+ userEmails {
+ nodes {
+ isPrimary
+ isVerified
+ __typename
+ }
+ __typename
+ }
+ __typename
+ }
+ telegramBotUsername
+ currentReminderPreferences {
+ userId
+ minutesBefore
+ deliveryMethod
+ __typename
+ }
+ currentTelegramAccount {
+ userId
+ username
+ __typename
+ }
+ eventRegistrationReminders(condition: {eventId: $eventId}, first: 1) {
+ nodes {
+ id
+ deliveryMethod
+ minutesBefore
+ sentAt
+ __typename
+ }
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373.graphql b/@app/graphql/.persisted_operations/19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373.graphql
new file mode 100644
index 000000000..b17daa02c
--- /dev/null
+++ b/@app/graphql/.persisted_operations/19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373.graphql
@@ -0,0 +1,8 @@
+mutation SetEventRegistrationReminder($eventId: UUID!, $enabled: Boolean!, $language: String!, $minutesBefore: Int = 30, $deliveryMethod: String = "email") {
+ setEventRegistrationReminder(
+ input: {eventId: $eventId, enabled: $enabled, language: $language, minutesBefore: $minutesBefore, deliveryMethod: $deliveryMethod}
+ ) {
+ boolean
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9.graphql b/@app/graphql/.persisted_operations/36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9.graphql
new file mode 100644
index 000000000..30821aa97
--- /dev/null
+++ b/@app/graphql/.persisted_operations/36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9.graphql
@@ -0,0 +1,101 @@
+fragment SharedLayout_Query on Query {
+ currentUser {
+ ...SharedLayout_User
+ __typename
+ }
+ organizations(orderBy: SLUG_ASC) {
+ nodes {
+ ...SharedLayout_Organization
+ __typename
+ }
+ __typename
+ }
+ ssoLoginEnabled
+ supportedLanguages
+ __typename
+}
+fragment SharedLayout_User on User {
+ id
+ name
+ username
+ avatarUrl
+ isAdmin
+ isVerified
+ primaryEmail
+ userEmails(first: 50) {
+ nodes {
+ ...SharedLayout_UserEmail
+ __typename
+ }
+ __typename
+ }
+ organizationMemberships(first: 20) {
+ totalCount
+ nodes {
+ id
+ isOwner
+ organization {
+ id
+ name
+ slug
+ __typename
+ }
+ __typename
+ }
+ __typename
+ }
+ __typename
+}
+fragment SharedLayout_UserEmail on UserEmail {
+ id
+ email
+ isVerified
+ isPrimary
+ createdAt
+ __typename
+}
+fragment SharedLayout_Organization on Organization {
+ id
+ name
+ slug
+ __typename
+}
+fragment RegistrationReminderFields on EventRegistrationReminder {
+ id
+ eventId
+ deliveryMethod
+ minutesBefore
+ sentAt
+ event {
+ id
+ slug
+ name
+ isDraft
+ registrationStartTime
+ __typename
+ }
+ __typename
+}
+query RegistrationReminders($first: Int!) {
+ telegramBotUsername
+ currentReminderPreferences {
+ userId
+ minutesBefore
+ deliveryMethod
+ __typename
+ }
+ ...SharedLayout_Query
+ currentTelegramAccount {
+ userId
+ username
+ __typename
+ }
+ eventRegistrationReminders(first: $first, orderBy: PRIMARY_KEY_ASC) {
+ totalCount
+ nodes {
+ ...RegistrationReminderFields
+ __typename
+ }
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e.graphql b/@app/graphql/.persisted_operations/3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e.graphql
new file mode 100644
index 000000000..e970da81d
--- /dev/null
+++ b/@app/graphql/.persisted_operations/3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e.graphql
@@ -0,0 +1,13 @@
+mutation SaveReminderPreferences($minutesBefore: Int!, $deliveryMethod: String!) {
+ saveReminderPreferences(
+ input: {minutesBefore: $minutesBefore, deliveryMethod: $deliveryMethod}
+ ) {
+ reminderPreference {
+ userId
+ minutesBefore
+ deliveryMethod
+ __typename
+ }
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b.graphql b/@app/graphql/.persisted_operations/9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b.graphql
new file mode 100644
index 000000000..b84df3629
--- /dev/null
+++ b/@app/graphql/.persisted_operations/9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b.graphql
@@ -0,0 +1,6 @@
+mutation RequestTelegramLink {
+ requestTelegramLink(input: {}) {
+ string
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3.graphql b/@app/graphql/.persisted_operations/c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3.graphql
new file mode 100644
index 000000000..5583e8eba
--- /dev/null
+++ b/@app/graphql/.persisted_operations/c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3.graphql
@@ -0,0 +1,6 @@
+mutation DisconnectTelegram {
+ disconnectTelegram(input: {}) {
+ boolean
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/.persisted_operations/d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94.graphql b/@app/graphql/.persisted_operations/d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94.graphql
new file mode 100644
index 000000000..756e4c411
--- /dev/null
+++ b/@app/graphql/.persisted_operations/d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94.graphql
@@ -0,0 +1,6 @@
+mutation EnableEventReminder($eventId: UUID!, $language: String!) {
+ enableEventReminder(input: {eventId: $eventId, language: $language}) {
+ boolean
+ __typename
+ }
+}
\ No newline at end of file
diff --git a/@app/graphql/client.json b/@app/graphql/client.json
index c68ae7607..d90032123 100644
--- a/@app/graphql/client.json
+++ b/@app/graphql/client.json
@@ -42,6 +42,13 @@
"DeleteEventRegistration": "be0f72e306dcf5e22dbaa962b5228422a5a0bd12dc68d688ee8b9a28b479318b",
"UpdateEventRegistrationPage": "2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9",
"UpdateEventRegistration": "a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739",
+ "RegistrationReminders": "36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9",
+ "EventRegistrationReminder": "16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad",
+ "SetEventRegistrationReminder": "19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373",
+ "RequestTelegramLink": "9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b",
+ "DisconnectTelegram": "c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3",
+ "SaveReminderPreferences": "3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e",
+ "EnableEventReminder": "d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94",
"AddEmail": "da27b66ae2e115cc90ba53748aaadae32ba97b016e2783550fe847089f7423c2",
"ChangePassword": "2532c897bead71cb8b9171c240298a47c4b6b13197886c990ccfcc937356ceab",
"ConfirmAccountDeletion": "28c6757c5282d5f04e93b027aea1642ffd3afc54ea99778983d476e615919c04",
diff --git a/@app/graphql/server.json b/@app/graphql/server.json
index ae4556691..d421f4c5c 100644
--- a/@app/graphql/server.json
+++ b/@app/graphql/server.json
@@ -42,6 +42,13 @@
"be0f72e306dcf5e22dbaa962b5228422a5a0bd12dc68d688ee8b9a28b479318b": "mutation DeleteEventRegistration($updateToken: String!) {\n deleteRegistration(input: {updateToken: $updateToken}) {\n success\n __typename\n }\n}",
"2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9": "fragment UpdateEventRegistrationPage_Query on Query {\n ...SharedLayout_Query\n registrationByUpdateToken(updateToken: $updateToken) {\n ...UpdateEventRegistrationPage_Registration\n quota {\n ...EventPage_Quota\n __typename\n }\n event {\n ...EventPage_Event\n __typename\n }\n __typename\n }\n __typename\n}\nfragment SharedLayout_Query on Query {\n currentUser {\n ...SharedLayout_User\n __typename\n }\n organizations(orderBy: SLUG_ASC) {\n nodes {\n ...SharedLayout_Organization\n __typename\n }\n __typename\n }\n ssoLoginEnabled\n supportedLanguages\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isVerified\n primaryEmail\n userEmails(first: 50) {\n nodes {\n ...SharedLayout_UserEmail\n __typename\n }\n __typename\n }\n organizationMemberships(first: 20) {\n totalCount\n nodes {\n id\n isOwner\n organization {\n id\n name\n slug\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n}\nfragment SharedLayout_UserEmail on UserEmail {\n id\n email\n isVerified\n isPrimary\n createdAt\n __typename\n}\nfragment SharedLayout_Organization on Organization {\n id\n name\n slug\n __typename\n}\nfragment UpdateEventRegistrationPage_Registration on Registration {\n id\n firstName\n lastName\n answers\n __typename\n}\nfragment EventPage_Quota on Quota {\n id\n position\n title\n size\n __typename\n}\nfragment EventPage_Event on Event {\n ...EventFields\n category {\n ...EventPage_EventCategory\n __typename\n }\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Quota\n __typename\n }\n __typename\n }\n registrations(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Registration\n __typename\n }\n __typename\n }\n eventQuestions(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Question\n __typename\n }\n __typename\n }\n __typename\n}\nfragment EventFields on Event {\n id\n name\n slug\n description\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n isHighlighted\n isDraft\n headerImageFile\n openQuotaSize\n signupOpen\n signupUpcoming\n signupClosed\n createdBy\n updatedBy\n createdAt\n updatedAt\n __typename\n}\nfragment EventPage_EventCategory on EventCategory {\n id\n description\n name\n color\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n updatedAt\n __typename\n}\nfragment EventPage_Organization on Organization {\n id\n name\n slug\n color\n __typename\n}\nfragment EventPage_Registration on Registration {\n id\n fullName\n status\n position\n createdAt\n quota {\n ...EventPage_Quota\n __typename\n }\n __typename\n}\nfragment EventPage_Question on EventQuestion {\n id\n position\n type\n label\n isRequired\n data\n __typename\n}\nquery UpdateEventRegistrationPage($updateToken: String!) {\n ...UpdateEventRegistrationPage_Query\n}",
"a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739": "fragment EventPage_Registration on Registration {\n id\n fullName\n status\n position\n createdAt\n quota {\n ...EventPage_Quota\n __typename\n }\n __typename\n}\nfragment EventPage_Quota on Quota {\n id\n position\n title\n size\n __typename\n}\nmutation UpdateEventRegistration($input: UpdateRegistrationInput!) {\n updateRegistration(input: $input) {\n registration {\n ...EventPage_Registration\n firstName\n lastName\n answers\n updatedAt\n __typename\n }\n __typename\n }\n}",
+ "36bc98b27f0382de46d6d2d3c5cdece820d527732ae1de883ba5469d9b040fd9": "fragment SharedLayout_Query on Query {\n currentUser {\n ...SharedLayout_User\n __typename\n }\n organizations(orderBy: SLUG_ASC) {\n nodes {\n ...SharedLayout_Organization\n __typename\n }\n __typename\n }\n ssoLoginEnabled\n supportedLanguages\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isVerified\n primaryEmail\n userEmails(first: 50) {\n nodes {\n ...SharedLayout_UserEmail\n __typename\n }\n __typename\n }\n organizationMemberships(first: 20) {\n totalCount\n nodes {\n id\n isOwner\n organization {\n id\n name\n slug\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n}\nfragment SharedLayout_UserEmail on UserEmail {\n id\n email\n isVerified\n isPrimary\n createdAt\n __typename\n}\nfragment SharedLayout_Organization on Organization {\n id\n name\n slug\n __typename\n}\nfragment RegistrationReminderFields on EventRegistrationReminder {\n id\n eventId\n deliveryMethod\n minutesBefore\n sentAt\n event {\n id\n slug\n name\n isDraft\n registrationStartTime\n __typename\n }\n __typename\n}\nquery RegistrationReminders($first: Int!) {\n telegramBotUsername\n currentReminderPreferences {\n userId\n minutesBefore\n deliveryMethod\n __typename\n }\n ...SharedLayout_Query\n currentTelegramAccount {\n userId\n username\n __typename\n }\n eventRegistrationReminders(first: $first, orderBy: PRIMARY_KEY_ASC) {\n totalCount\n nodes {\n ...RegistrationReminderFields\n __typename\n }\n __typename\n }\n}",
+ "16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad": "query EventRegistrationReminder($eventId: UUID!) {\n currentUser {\n id\n userEmails {\n nodes {\n isPrimary\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n telegramBotUsername\n currentReminderPreferences {\n userId\n minutesBefore\n deliveryMethod\n __typename\n }\n currentTelegramAccount {\n userId\n username\n __typename\n }\n eventRegistrationReminders(condition: {eventId: $eventId}, first: 1) {\n nodes {\n id\n deliveryMethod\n minutesBefore\n sentAt\n __typename\n }\n __typename\n }\n}",
+ "19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373": "mutation SetEventRegistrationReminder($eventId: UUID!, $enabled: Boolean!, $language: String!, $minutesBefore: Int = 30, $deliveryMethod: String = \"email\") {\n setEventRegistrationReminder(\n input: {eventId: $eventId, enabled: $enabled, language: $language, minutesBefore: $minutesBefore, deliveryMethod: $deliveryMethod}\n ) {\n boolean\n __typename\n }\n}",
+ "9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b": "mutation RequestTelegramLink {\n requestTelegramLink(input: {}) {\n string\n __typename\n }\n}",
+ "c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3": "mutation DisconnectTelegram {\n disconnectTelegram(input: {}) {\n boolean\n __typename\n }\n}",
+ "3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e": "mutation SaveReminderPreferences($minutesBefore: Int!, $deliveryMethod: String!) {\n saveReminderPreferences(\n input: {minutesBefore: $minutesBefore, deliveryMethod: $deliveryMethod}\n ) {\n reminderPreference {\n userId\n minutesBefore\n deliveryMethod\n __typename\n }\n __typename\n }\n}",
+ "d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94": "mutation EnableEventReminder($eventId: UUID!, $language: String!) {\n enableEventReminder(input: {eventId: $eventId, language: $language}) {\n boolean\n __typename\n }\n}",
"da27b66ae2e115cc90ba53748aaadae32ba97b016e2783550fe847089f7423c2": "fragment EmailsForm_UserEmail on UserEmail {\n id\n email\n isVerified\n isPrimary\n createdAt\n __typename\n}\nmutation AddEmail($email: Email!) {\n createUserEmail(input: {userEmail: {email: $email}}) {\n user {\n id\n userEmails(first: 50) {\n nodes {\n ...EmailsForm_UserEmail\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n}",
"2532c897bead71cb8b9171c240298a47c4b6b13197886c990ccfcc937356ceab": "mutation ChangePassword($oldPassword: String!, $newPassword: String!) {\n changePassword(input: {oldPassword: $oldPassword, newPassword: $newPassword}) {\n success\n __typename\n }\n}",
"28c6757c5282d5f04e93b027aea1642ffd3afc54ea99778983d476e615919c04": "mutation ConfirmAccountDeletion($token: String!) {\n confirmAccountDeletion(input: {token: $token}) {\n success\n __typename\n }\n}",
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/lib/src/telegram.ts b/@app/lib/src/telegram.ts
new file mode 100644
index 000000000..e40d9306d
--- /dev/null
+++ b/@app/lib/src/telegram.ts
@@ -0,0 +1,140 @@
+// Server-only entry point: import this file directly, not through the browser barrel.
+import { request } from "node:https"
+
+export class TelegramError extends Error {
+ constructor(
+ public code: number,
+ public retryAfter?: number
+ ) {
+ super(`Telegram request failed (${code})`)
+ }
+}
+
+export function telegramRequest(
+ method: string,
+ body: Record,
+ timeout = 35000
+): Promise {
+ const token = process.env.TELEGRAM_BOT_TOKEN
+ if (!token) return Promise.reject(new Error("Telegram bot is not configured"))
+ if (!/^\d+:[A-Za-z0-9_-]+$/.test(token))
+ return Promise.reject(new Error("Telegram bot token has an invalid format"))
+ // Do not attach request objects, URLs, or Telegram response descriptions to
+ // errors: the request path contains the bot token.
+ return new Promise((resolve, reject) => {
+ const payload = JSON.stringify(body)
+ const req = request(
+ {
+ hostname: "api.telegram.org",
+ path: `/bot${token}/${method}`,
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload),
+ },
+ },
+ (res) => {
+ let data = ""
+ res.on("data", (chunk) => (data += chunk))
+ res.on("error", () =>
+ reject(new Error("Telegram response interrupted"))
+ )
+ res.on("end", () => {
+ try {
+ const parsed = JSON.parse(data)
+ if (parsed.ok) resolve(parsed.result as T)
+ else
+ reject(
+ new TelegramError(
+ parsed.error_code || res.statusCode || 500,
+ parsed.parameters?.retry_after
+ )
+ )
+ } catch {
+ reject(new Error("Invalid Telegram response"))
+ }
+ })
+ }
+ )
+ req.setTimeout(timeout, () => req.destroy())
+ req.on("error", () => reject(new Error("Telegram connection failed")))
+ req.end(payload)
+ })
+}
+
+export type TelegramLanguage = "fi" | "en"
+export type TelegramLanguagePreference = TelegramLanguage | "auto"
+
+export function detectedTelegramLanguage(
+ code?: string | null
+): TelegramLanguage {
+ return code?.toLowerCase().split("-")[0] === "fi" ? "fi" : "en"
+}
+
+export function resolveTelegramLanguage(preferences?: {
+ language?: string | null
+ detected_language?: string | null
+}): TelegramLanguage {
+ if (preferences?.language === "fi" || preferences?.language === "en")
+ return preferences.language
+ return detectedTelegramLanguage(preferences?.detected_language)
+}
+
+const telegramReplies = {
+ en: {
+ disconnected:
+ "Telegram reminders disconnected. You can reconnect in Ilmo settings.",
+ connected:
+ "Telegram connected! Return to Ilmo to choose your reminders.\n\nChange language anytime with /language.",
+ invalidLink:
+ "This link is invalid or expired, or this Telegram account is already connected. Generate a new link in Ilmo settings.",
+ welcome:
+ "Connect your account using Connect Telegram in Ilmo settings. Use /stop to disconnect.\n\nChange language anytime with /language.",
+ languageMenu:
+ "Choose your bot language. Automatic follows your Telegram language (Finnish or English; other languages use English).",
+ languageSaved:
+ "Bot language saved. All Telegram messages, including scheduled reminders, now use this preference. Change it anytime with /language.",
+ automatic: "Automatic",
+ },
+ fi: {
+ disconnected:
+ "Telegram-muistutukset poistettu käytöstä. Voit yhdistää tilin uudelleen Ilmon asetuksissa.",
+ connected:
+ "Telegram yhdistetty! Palaa Ilmoon valitsemaan muistutuksesi.\n\nChange language: /language.",
+ invalidLink:
+ "Linkki ei kelpaa, se on vanhentunut tai Telegram-tili on jo yhdistetty. Luo uusi linkki Ilmon asetuksissa.",
+ welcome:
+ "Yhdistä tilisi Ilmon asetusten Yhdistä Telegram -painikkeella. Komento /stop katkaisee yhteyden.\n\nChange language: /language.",
+ languageMenu:
+ "Valitse botin kieli. Automaattinen seuraa Telegramin kieltä (suomi tai englanti; muilla kielillä käytetään englantia).",
+ languageSaved:
+ "Botin kieliasetus tallennettu. Kaikki Telegram-viestit, myös ajastetut muistutukset, käyttävät nyt tätä asetusta. Change language: /language.",
+ automatic: "Automaattinen",
+ },
+}
+export type TelegramReply = Exclude<
+ keyof typeof telegramReplies.en,
+ "automatic"
+>
+
+export function telegramReplyText(
+ reply: TelegramReply,
+ language: TelegramLanguage
+) {
+ return telegramReplies[language][reply]
+}
+
+export function telegramLanguageKeyboard(language: TelegramLanguage) {
+ return {
+ inline_keyboard: [
+ [
+ { text: "English", callback_data: "language:en" },
+ { text: "Suomi", callback_data: "language:fi" },
+ {
+ text: telegramReplies[language].automatic,
+ callback_data: "language:auto",
+ },
+ ],
+ ],
+ }
+}
diff --git a/@app/lib/tsconfig.cjs.json b/@app/lib/tsconfig.cjs.json
index 9681136f9..7abe3b9af 100644
--- a/@app/lib/tsconfig.cjs.json
+++ b/@app/lib/tsconfig.cjs.json
@@ -1,6 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
+ "tsBuildInfoFile": "dist/tsconfig.cjs.tsbuildinfo",
+ "declarationDir": "dist/cjs",
"outDir": "dist/cjs",
"module": "commonjs"
},
diff --git a/@app/server/__tests__/queries/__snapshots__/renderEmailTemplates.test.ts.snap b/@app/server/__tests__/queries/__snapshots__/renderEmailTemplates.test.ts.snap
index 2a25df982..806c2c867 100644
--- a/@app/server/__tests__/queries/__snapshots__/renderEmailTemplates.test.ts.snap
+++ b/@app/server/__tests__/queries/__snapshots__/renderEmailTemplates.test.ts.snap
@@ -2322,6 +2322,334 @@ This message is purely for your information. No action is required.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+ Registration opens soon: Test event
+
+ |
+
+
+
+ |
+
+ Registration opens 1 January 2021 at 12:00 (Finland time).
+
+ |
+
+
+
+ |
+
+
+
+ |
+
+
+
+ |
+
+ You requested a reminder for this event. This reminder does not reserve a place.
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+ © Tuotantotalouden Kilta Prodeko ry.
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+