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")} + + ) : ( + + ) + } + 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 ? ( + <> + +