diff --git a/.env.ci b/.env.ci index 63e5957d5..e6bad0335 100644 --- a/.env.ci +++ b/.env.ci @@ -14,3 +14,11 @@ PORT=5678 ROOT_URL=http://localhost:5678 ENABLE_CYPRESS_COMMANDS=1 REDIS_URL=redis://127.0.0.1:6379 + +# Stripe is not configured with this file, so the `payments` feature flag is +# unavailable: jest runs with payments off and the server tests set the +# Stripe variables themselves. The sharded Cypress job in +# .github/workflows/e2e.yml appends dummy keys. Never put real Stripe keys +# here. +# STRIPE_SECRET_KEY=sk_test_... +# STRIPE_WEBHOOK_SECRET=whsec_... diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 43f040bb3..203afa245 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,35 @@ jobs: docker run --rm -v "$PWD:/repo" -w /repo \ rhysd/actionlint:1.7.7 -color + migrations: + name: Migration files + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Check current/ prefixes are unique + run: node scripts/check-migrations.mjs current + + # Maintainers commit migrations. Their own migration-commit PRs carry the + # `migration-commit` label; the label is read from the API, not the event + # payload, so re-running the job after labelling picks it up. + - name: Check the PR leaves committed/ unchanged + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + labels=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '.labels[].name') + if grep -qxF migration-commit <<< "$labels"; then + echo "::notice::Label migration-commit is set; committed/ changes are allowed." + exit 0 + fi + node scripts/check-migrations.mjs committed "$BASE_SHA" + lint: name: Lint & depcheck runs-on: ubuntu-latest @@ -114,8 +143,9 @@ jobs: run: pnpm build - name: Test - # --runInBand: debezium/postgres has a single replication slot, - # so parallel jest workers race on it. + # One test file at a time: debezium/postgres has a single replication + # slot, so parallel jest workers race on it. scripts/test.mjs runs the + # files in one worker that jest restarts to bound its memory. run: pnpm test --ci --runInBand docker: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index b64b1e1e4..7ff2df3f7 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -44,10 +44,18 @@ jobs: uses: ./.github/actions/install-pg-dump - name: Setup environment and database + # Stripe is configured here so that the payments_* specs can switch + # the `payments` flag on; the keys are dummies because the specs + # never reach Stripe (Checkout is stubbed and the webhook gets signed + # fake events from the completeStripeCheckout server command). # `setup` resets the DB to committed migrations only; `watch --once` # applies migrations/current/ on top, as `pnpm dev` does locally. run: | cp .env.ci .env + { + echo "STRIPE_SECRET_KEY=sk_test_dummy" + echo "STRIPE_WEBHOOK_SECRET=whsec_dummy" + } >> .env CONFIRM_DROP=1 pnpm run setup pnpm --filter @app/db run watch --once diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index e9e35bcff..951d85931 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -18,25 +18,55 @@ permissions: actions: read jobs: + # Lets docs-only PRs skip e2e. Pushes to main and manual runs always run it. + changes: + name: Detect changes + runs-on: ubuntu-latest + outputs: + code: ${{ steps.filter.outputs.code }} + steps: + - name: Check for changes outside docs + id: filter + if: github.event_name == 'pull_request' + uses: dorny/paths-filter@v4 + with: + predicate-quantifier: every + filters: | + code: + - "**" + - "!**/*.md" + - "!docs/**" + ci: uses: ./.github/workflows/ci.yml secrets: inherit e2e: + needs: [changes] + if: github.event_name != 'pull_request' || needs.changes.outputs.code == 'true' uses: ./.github/workflows/e2e.yml secrets: inherit all-checks: name: All checks passed runs-on: ubuntu-latest - needs: [ci, e2e] + needs: [changes, ci, e2e] if: always() steps: - name: Verify all required jobs succeeded + env: + CHANGES_RESULT: ${{ needs.changes.result }} + CI_RESULT: ${{ needs.ci.result }} + E2E_RESULT: ${{ needs.e2e.result }} + E2E_SKIPPABLE: ${{ github.event_name == 'pull_request' && needs.changes.outputs.code != 'true' }} run: | set -euo pipefail - if [ "${{ needs.ci.result }}" != "success" ] || [ "${{ needs.e2e.result }}" != "success" ]; then - echo "ci=${{ needs.ci.result }} e2e=${{ needs.e2e.result }}" + echo "changes=$CHANGES_RESULT ci=$CI_RESULT e2e=$E2E_RESULT e2e_skippable=$E2E_SKIPPABLE" + if [ "$CHANGES_RESULT" != "success" ] || [ "$CI_RESULT" != "success" ]; then + exit 1 + fi + # e2e may only be skipped when the PR touches docs alone + if [ "$E2E_RESULT" != "success" ] && ! { [ "$E2E_RESULT" = "skipped" ] && [ "$E2E_SKIPPABLE" = "true" ]; }; then exit 1 fi 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/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..5ee7abd87 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +pnpm exec lint-staged diff --git a/@app/__tests__/data.ts b/@app/__tests__/data.ts index e28216c5f..813fef97d 100644 --- a/@app/__tests__/data.ts +++ b/@app/__tests__/data.ts @@ -40,7 +40,8 @@ export const createUsers = async ( client: PoolClient, count: number = 1, verified: boolean = true, - isAdmin: boolean = false + isAdmin: boolean = false, + isDeveloper: boolean = false ): Promise[]> => { const users = [] if (userCreationCounter > 25) { @@ -73,6 +74,17 @@ export const createUsers = async ( ] ) ).rows[0] + if (isDeveloper) { + // Not settable through really_create_user: developer rights come from + // Keycloak or a direct update only. + const { + rows: [developer], + } = await client.query( + "update app_public.users set is_developer = true where id = $1 returning *", + [user.id] + ) + Object.assign(user, developer) + } user._email = email user._password = password users.push(user) diff --git a/@app/__tests__/helpers.ts b/@app/__tests__/helpers.ts index 404e11dc5..38f3b50ad 100644 --- a/@app/__tests__/helpers.ts +++ b/@app/__tests__/helpers.ts @@ -3,6 +3,8 @@ import { readdirSync } from "node:fs" import { resolve } from "node:path" import { Pool, PoolClient } from "pg" +import type { FeatureFlagState, FeatureKey } from "@app/lib" + export { constructAnswersFromQuestions, createEventCategories, @@ -63,6 +65,8 @@ export const deleteTestEventData = (pool: Pool) => { // We're not using withRootDb because we don't want the transaction rolled back return pool.query( `BEGIN; + delete from app_public.payments; + delete from app_private.stripe_events; delete from app_private.registration_secrets; delete from app_public.registrations; delete from app_public.quotas; @@ -79,10 +83,26 @@ export const deleteTestEventData = (pool: Pool) => { ) } +/** + * The flag state every test starts from: off, or on when the suite runs with + * TEST_FEATURE_FLAGS=on, see scripts/test.mjs. + */ +export const featureFlagBaseline = (): FeatureFlagState => + process.env.TEST_FEATURE_FLAGS === "on" ? "on" : "off" + +// Also marks every flag available again: a server booted by a test records +// the availability of integration-backed flags from its own environment. +export const resetFeatureFlags = (pool: Pool) => + pool.query( + "update app_public.feature_flags set state = $1, available = true where state <> $1 or not available", + [featureFlagBaseline()] + ) + export const deleteTestData = async () => { const pool = poolFromUrl(TEST_DATABASE_URL) await deleteTestUsers(pool) await deleteTestEventData(pool) + await resetFeatureFlags(pool) } /* Quickly becomes root, does the thing, and then reverts back to previous role */ @@ -105,6 +125,35 @@ export const asRoot = async ( } } +/******************************************************************************/ +// Feature flags + +/** + * Sets the state of a feature flag directly, bypassing the developer check + * and the audit log. With a pool the change is committed; with a client it + * belongs to the client's transaction. deleteTestData switches every flag + * back off. Fails for a key without a row, which means the migration that + * adds the feature has not run. + */ +export const setFeatureFlag = async ( + client: Pool | PoolClient, + key: FeatureKey, + state: FeatureFlagState +) => { + const update = (c: Pool | PoolClient) => + c.query( + "update app_public.feature_flags set state = $2 where key = $1 returning key", + [key, state] + ) + const { rowCount } = + client instanceof Pool ? await update(client) : await asRoot(client, update) + if (!rowCount) { + throw new Error( + `Feature flag "${key}" has no row in app_public.feature_flags` + ) + } +} + /******************************************************************************/ // Job helpers @@ -195,14 +244,6 @@ export async function claimRegistrationToken(eventId: string, quotaId: string) { } } -export const refreshMaterializedView = async (client: PoolClient) => { - // Become root - await client.query("reset role") - client.query( - "refresh materialized view app_hidden.registrations_status_and_position" - ) -} - export const getEmails = () => global["TEST_EMAILS"] export const clearEmails = () => { diff --git a/@app/client/i18n.js b/@app/client/i18n.js index 3ecd1bab7..e44c454fd 100644 --- a/@app/client/i18n.js +++ b/@app/client/i18n.js @@ -13,11 +13,13 @@ 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"], + "/update-registration/[updateToken]": ["register_event", "payments"], + "/pay/[updateToken]": ["payments"], "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 ? ( + <> + + + + + + + {error ? ( + + + + ) : success ? ( + + + + ) : null} + + + + + ) +} + +/** Deleting your own registration details works whatever the flag's state. */ +function DeleteRegistrationProfileButton() { + const { t } = useTranslation("settings") + const [{ error, fetching }, deleteRegistrationProfile] = + useDeleteRegistrationProfileMutation() + + const handleDelete = useCallback(async () => { + const { error } = await deleteRegistrationProfile({}) + if (!error) { + message.success(t("form.feedback.registrationProfileDeleted")) + } + }, [deleteRegistrationProfile, t]) + + return ( + + {error ? ( + + ) : null} + + + + + ) +} diff --git a/@app/client/src/pages/settings/reminders.tsx b/@app/client/src/pages/settings/reminders.tsx new file mode 100644 index 000000000..222702c7b --- /dev/null +++ b/@app/client/src/pages/settings/reminders.tsx @@ -0,0 +1,223 @@ +import { useEffect, useState } from "react" +import { + ErrorAlert, + featureEnabledIn, + FourOhFour, + 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 RemindersPage() { + 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" + // The page renders the layout, so it reads the flags from its own query + const remindersOn = featureEnabledIn(query.data, "registration_reminders") + // Without a bot username the page offers no way to choose or link Telegram; + // a linked account can still be disconnected. + const botUsername = + remindersOn && featureEnabledIn(query.data, "telegram_reminders") + ? query.data?.telegramBotUsername + : null + // While reminders are off the page only offers ways out: removing + // reminders and disconnecting Telegram. It stays in that mode after the + // last one is gone, and is not found for users who have nothing to remove. + const hasSomethingToRemove = + !!query.data?.currentTelegramAccount || !!reminders?.totalCount + const [hadSomethingToRemove, setHadSomethingToRemove] = useState(false) + useEffect(() => { + if (hasSomethingToRemove) setHadSomethingToRemove(true) + }, [hasSomethingToRemove]) + if ( + query.data && + !remindersOn && + !hasSomethingToRemove && + !hadSomethingToRemove + ) { + return + } + return ( + + + {query.data && !remindersOn && ( + + )} + {query.data && remindersOn && ( + <> + + {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" })} + /> + {remindersOn && ( + {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/pages/update-registration/[updateToken]/index.tsx b/@app/client/src/pages/update-registration/[updateToken]/index.tsx index 80e74bfa1..9415beb35 100644 --- a/@app/client/src/pages/update-registration/[updateToken]/index.tsx +++ b/@app/client/src/pages/update-registration/[updateToken]/index.tsx @@ -1,13 +1,18 @@ import { EventRegistrationForm, + Link, PageHeader, Redirect, SharedLayout, useTranslation, } from "@app/components" -import { useUpdateEventRegistrationPageQuery } from "@app/graphql" -import { filterObjectByKeys } from "@app/lib" -import { Col, Row } from "antd" +import { + RegistrationPaymentStatus, + useUpdateEventRegistrationPageQuery, +} from "@app/graphql" +import { filterObjectByKeys, formatEuro, payPageState } from "@app/lib" +import { Alert, Col, Row } from "antd" +import dayjs from "dayjs" import { useRouter } from "next/router" import type { NextPage } from "next" @@ -42,6 +47,16 @@ const UpdateEventRegistrationPage: NextPage = () => { const event = registration?.event const quota = registration?.quota + // paymentByUpdateToken is null while Stripe is not + // configured; while the payments flag is off it still describes a payment + // already made (blockedReason PAYMENTS_DISABLED). + const payment = data?.paymentByUpdateToken + // Deleting a paid registration refunds nothing automatically + const paidOnDelete = + payment?.status === RegistrationPaymentStatus.Paid || + payment?.status === RegistrationPaymentStatus.PaidManually + const payState = payment ? payPageState(true, payment) : null + // If registration is not found redirect to index if (!fetching && !error && !registration && !stale) { return @@ -55,16 +70,76 @@ const UpdateEventRegistrationPage: NextPage = () => { {event?.name[lang]} - {quota?.title[lang]} - + {(payState === "paid" || payState === "paidManually") && ( + + + + + + )} + {payState === "unpaid" && ( + + + + {t("payments:payNow")} + + } + data-cy="updateregistration-unpaid-banner" + message={t("payments:unpaidBanner")} + type="warning" + /> + + + )} + {event && !event.signupOpen ? ( + + + + + + ) : ( + + )} ) } diff --git a/@app/client/src/styles/global.css b/@app/client/src/styles/global.css index 41a8ec01f..26d5bf41d 100644 --- a/@app/client/src/styles/global.css +++ b/@app/client/src/styles/global.css @@ -13,6 +13,13 @@ --layout-footer-background: #f5faff; } +html { + /* Always reserve space for the vertical scrollbar. Otherwise the page + gets narrower whenever content grows past the window height (e.g. when + adding questions in the event form), and wrapping rows jump around. */ + scrollbar-gutter: stable; +} + body { background: var(--layout-footer-background); } diff --git a/@app/client/src/translations/en/admin.json b/@app/client/src/translations/en/admin.json index 4cf92dc9e..743c9cd61 100644 --- a/@app/client/src/translations/en/admin.json +++ b/@app/client/src/translations/en/admin.json @@ -27,6 +27,7 @@ "tabs": { "email": "Email", "generalInfo": "General", + "preview": "Preview", "questions": "Questions", "quotas": "Quotas" }, @@ -35,6 +36,269 @@ "showEvent": "Show event" } }, + "features": { + "adminsOnlyInfo": "Admins only lets you try a feature before release. Signed-in admins see it with a Preview tag. Everyone else does not, and emails and reminders treat it as off.", + "cancel": "Cancel", + "changeHistory": "Change history", + "changedOutside": "Changed outside this page", + "columns": { + "actions": "Actions", + "feature": "Feature", + "lastChanged": "Last changed", + "state": "State" + }, + "confirmOff": { + "genericKeeps": "Data already saved stays as it is, and anything already started completes.", + "genericStops": "Nobody can start using {{name}}.", + "intro": { + "admins_only": "Everyone except signed-in admins stops seeing it, and emails and reminders treat it as off. Anything already started keeps working.", + "off": "Turning off hides the ways in. Anything already started keeps working." + }, + "keeps": "Keeps working", + "ok": { + "admins_only": "Limit to admins only", + "off": "Turn off {{name}}" + }, + "stops": "Stops now", + "title": { + "admins_only": "Limit {{name}} to admins?", + "off": "Turn off {{name}}?" + } + }, + "confirmOn": { + "appliesNow": "The change applies right away. You can turn it off again on this page.", + "generic": "Everything {{name}} adds, on every page and in emails and reminders.", + "neverPreviewed": "Nobody has previewed this yet. Try Admins only first: you see it on real pages, nobody else does, and no emails change.", + "ok": "Turn on for everyone", + "preview": "Preview for admins first", + "previewedSince": "Admins have previewed this since {{date}}. {{actor}} set it to Admins only.", + "previewing": "Admins are previewing this now.", + "title": "Turn on {{name}} for everyone?", + "willSee": "Everyone will start seeing:" + }, + "counts": { + "admins_only": "{{count}} admins only", + "off": "{{count}} off", + "on": "{{count}} on" + }, + "defaultOff": "Default: Off", + "deletedUser": "Deleted user", + "dismiss": "Dismiss", + "empty": "No features yet. Features appear here as they are added to the app, and each one starts as Off.", + "flags": { + "calendar_invites": { + "name": "Calendar invitations", + "turnOn": [ + "Registration confirmation emails carry a calendar invitation.", + "The event page shows calendar links after signing up." + ], + "stops": [ + "New confirmation emails have no calendar invitation and the calendar links are hidden." + ], + "keeps": [ + "Invitations already sent stay in recipients' calendars." + ] + }, + "confetti": { + "name": "Confetti", + "turnOn": [ + "Confetti is shown after an event or a registration has been created, except to users who prefer reduced motion." + ], + "stops": [ + "No more confetti." + ], + "keeps": [ + "Creating events and registrations works as before." + ] + }, + "event_templates": { + "name": "Event templates", + "turnOn": [ + "The quotas and questions tabs of the event form offer templates and ready-made quotas and questions." + ], + "stops": [ + "The template selectors are hidden and the tabs show the plain lists." + ], + "keeps": [ + "Quotas and questions added from a template stay on their events." + ] + }, + "form_preview": { + "name": "Registration form preview", + "turnOn": [ + "The event form gets a Preview tab that shows the registration form as registrants see it." + ], + "stops": [ + "The Preview tab is hidden." + ], + "keeps": [ + "Nothing is ever submitted from the preview, so no data changes." + ] + }, + "keycloak_names": { + "name": "Names from Keycloak", + "turnOn": [ + "The registration form fills in the first and last name stored from Keycloak.", + "Without them, it fills in a display name only when it has at most two words." + ], + "stops": [ + "The registration form goes back to splitting the display name into first and last name." + ], + "keeps": [ + "First and last names are still stored at every Keycloak login.", + "Registrations already made keep their names." + ] + }, + "mcp_server": { + "name": "MCP server", + "turnOn": [ + "The MCP server answers at /mcp: AI assistants signed in through Keycloak can browse events and register, and admins can create draft events." + ], + "stops": [ + "/mcp and its OAuth discovery paths answer 404." + ], + "keeps": [ + "Events and registrations made through MCP are kept." + ] + }, + "payments": { + "name": "Payments", + "turnOn": [ + "Admins can price quotas. Registrants of paid quotas pay after registration closes.", + "Registrants of paid quotas pay through Stripe Checkout, and payment emails and reminders are sent.", + "Admins get the payment tools for their events." + ], + "stops": [ + "Prices are hidden and cannot be set, and paying is blocked.", + "No new payment emails or reminders are sent." + ], + "keeps": [ + "Payments already made stay recorded and are shown to registrants.", + "Stripe payment notifications keep working." + ] + }, + "prefill_answers": { + "name": "Remembered registration answers", + "turnOn": [ + "Admins can mark a text question as asking for the registrant's Telegram handle or dietary restrictions.", + "The registration form prefills those answers from the user's saved registration details, and offers to remember new answers.", + "The profile settings page shows the registration details for editing." + ], + "stops": [ + "Answers are no longer prefilled and the registration form no longer offers to remember them.", + "Registration details can no longer be saved or edited." + ], + "keeps": [ + "Questions keep their Telegram or dietary restriction marking and work as ordinary text questions.", + "Users can still delete the registration details they saved." + ] + }, + "registration_reminders": { + "name": "Registration reminders", + "turnOn": [ + "The event page offers a reminder before registration opens.", + "The settings get a reminders page with the user's reminders and reminder settings.", + "Reminder emails are sent before registration opens." + ], + "stops": [ + "The reminder button, the reminders page and its menu links are hidden.", + "No reminders are sent. A reminder that falls due while the flag is off is not sent later." + ], + "keeps": [ + "Saved reminders and reminder settings are kept." + ] + }, + "ribbon_text": { + "name": "Ribbon text", + "turnOn": [ + "The event form shows ribbon text inputs for highlighted events.", + "Event cards show the custom ribbon text." + ], + "stops": [ + "Event cards show the default ribbon text and the event form hides the inputs." + ], + "keeps": [ + "Stored ribbon texts are kept, also when an event is saved." + ] + }, + "telegram_reminders": { + "name": "Telegram reminders", + "turnOn": [ + "Users can link a Telegram account and choose Telegram for their reminders.", + "Reminders also go out through the Telegram bot." + ], + "stops": [ + "Telegram can no longer be linked or chosen, and no reminders go out through Telegram." + ], + "keeps": [ + "Linked accounts stay linked." + ] + }, + "typed_time_input": { + "name": "Typed times", + "turnOn": [ + "The event form uses typed hour, minute and second boxes for the event and registration times.", + "Clicking a day in the calendar fills in default times." + ], + "stops": [ + "The event form goes back to the time scroll columns." + ], + "keeps": [ + "Saved event and registration times stay as they are." + ] + } + }, + "footer": "New features arrive with app updates and start as Off.", + "history": "History", + "historyDrawer": { + "allFeatures": "All features", + "by": "{{actor}} · {{date}}", + "feature": "Feature", + "footerAll": "Showing all {{count}} changes. Changes cannot be edited or deleted.", + "footerOne": "Before {{date}} {{name}} was Off, the default for new features.", + "none": "No changes yet. New features start as Off.", + "title": "Change history", + "titleFor": "Change history: {{name}}" + }, + "historyLabel": "Change history of {{name}}", + "intro": "Switch features on and off for this site. Changes apply right away.", + "introDevelopers": "Only developers see this page; all admins see features set to Admins only.", + "loadError": { + "description": "Nothing has changed. Every feature keeps its current state for users. Try again in a moment.", + "title": "Could not load features", + "tryAgain": "Try again" + }, + "neverChanged": "Never changed", + "noAdminPreview": "Hidden from everyone. Admins only is not offered: admins have nothing to preview here, so it would behave as Off.", + "retired": "Retired: this feature is permanent and always on.", + "retry": "Retry", + "saveFailed": { + "admins_only": "Could not set {{name}} to Admins only. It is still {{state}}. Check your connection and try again.", + "off": "Could not turn off {{name}}. It is still {{state}}. Check your connection and try again.", + "on": "Could not turn on {{name}}. It is still {{state}}. Check your connection and try again." + }, + "saved": { + "admins_only": "{{name}} is now visible to admins only.", + "off": "{{name}} is now off.", + "on": "{{name}} is now on for everyone." + }, + "saving": "Saving…", + "savingNote": "Saving. The change applies when this finishes.", + "sees": { + "admins_only": "Visible to admins only. Emails and reminders treat it as off.", + "off": "Hidden from everyone", + "on": "Visible to everyone" + }, + "stateGroupLabel": "State of {{name}}", + "states": { + "admins_only": "Admins only", + "off": "Off", + "on": "On" + }, + "title": "Features", + "unavailable": "Not configured: the server lacks the settings this feature needs. A developer needs to add them before this can be switched on.", + "you": "{{name}} (you)" + }, "notifications": { "deleteFailed": "Failed to delete", "deleteSuccess": "Deleted successfully", @@ -93,6 +357,70 @@ "updateEvent": "Update event", "updateEventCategory": "Update event category" }, + "payments": { + "actions": { + "failed": "Updating the payment failed", + "markPaid": "Mark as paid", + "markPaidHelp": "For cash or bank transfer. Sends the payment received email.", + "markPaidSuccess": "Marked as paid", + "more": "More actions", + "undoManual": "Undo manual payment", + "undoManualConfirm": "Remove the manual payment? The registration becomes unpaid.", + "undoManualSuccess": "Manual payment removed" + }, + "cancel": "Cancel", + "delete": { + "body": "The spot goes to the next person in the queue. This can't be undone.", + "confirm": "Delete", + "noRefundWarning": "This registration has been paid. Nothing is refunded automatically: if a refund is due, settle it yourself (card payments in the Stripe Dashboard).", + "title": "Delete registration of {{name}}?" + }, + "filter": { + "all": "All ({{count}})", + "paid": "Paid ({{count}})", + "unpaid": "Unpaid ({{count}})" + }, + "lastReminderSent": "Last reminder sent {{date}} at {{time}}", + "paymentColumn": "Payment", + "quotas": { + "free": "Free", + "guildReceives": "Guild receives", + "invalidPrice": "Price must be 0 € or between 0,25 € and 10 000 €", + "noteFees": "Guild receives = price − 1,5 % × (price + 0,25 €). The customer pays the price plus a 0,25 € service fee, and Stripe takes 0,25 € + 1,5 %. This is an estimate for European cards; cards from outside the EEA cost a little more.", + "noteFree": "0 € makes the quota free. Otherwise the minimum price is 0,25 €.", + "noteOpenQuota": "Open quota spots pay the price of the quota the person registered through.", + "priceChangedWarning": "This quota has {{count}} registrations. Those already paid stay paid. Unpaid ones pay the new price.", + "priceChangedWarning_one": "This quota has {{count}} registration. If it is already paid, it stays paid. Otherwise it pays the new price.", + "ticketPrice": "Ticket price" + }, + "reminder": { + "body": "Everyone with a spot who hasn't paid gets an email with their own payment link. People in the queue and people in free quotas aren't emailed.", + "confirm_one": "Send {{count}} reminder", + "confirm_other": "Send {{count}} reminders", + "failed": "Sending reminders failed", + "lastSent": "Last reminder sent {{date}} at {{time}}.", + "sent_one": "{{count}} reminder sent", + "sent_other": "{{count}} reminders sent", + "title_one": "Send a payment reminder to {{count}} person?", + "title_other": "Send a payment reminder to {{count}} people?" + }, + "sendReminder": "Send reminder to {{count}} unpaid", + "status": { + "NOT_REQUIRED": "Free", + "PAID": "Paid", + "PAID_MANUALLY": "Paid manually", + "UNPAID": "Unpaid" + }, + "summary": { + "guildReceives": "Guild receives", + "paid": "Paid", + "paidOf": "of {{count}}", + "ticketsPaid": "Tickets paid", + "unlinkedCardPayments_one": "{{count}} card payment is not linked to any registration (for example a duplicate payment or a payment for a deleted registration). Refund it by hand in the Stripe Dashboard if needed.", + "unlinkedCardPayments_other": "{{count}} card payments are not linked to any registration (for example duplicate payments or payments for deleted registrations). Refund them by hand in the Stripe Dashboard if needed.", + "unpaid": "Unpaid" + } + }, "registrations": { "delete": { "confirmText": "Are you sure you want to delete this registration?", @@ -110,6 +438,7 @@ "emails": "Emails", "eventCategories": "Event categories", "events": "Events", + "features": "Features", "listEventCategories": "List event categories", "listEvents": "List events", "main": "Dashboard", diff --git a/@app/client/src/translations/en/common.json b/@app/client/src/translations/en/common.json index bb0448cb3..e3a4967ed 100644 --- a/@app/client/src/translations/en/common.json +++ b/@app/client/src/translations/en/common.json @@ -15,6 +15,12 @@ "email": "Email", "emailSwitchLabel": "Show html version", "error": "Error", + "featurePreview": { + "adminHint": "Not released yet. Ask a developer to release it.", + "developerHint": "Other users do not see this yet.", + "manage": "Manage on the Features page", + "tag": "Preview: visible to admins only" + }, "head": { "description": "Prodeko event registration", "title": "Prodeko event registration" @@ -52,6 +58,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/events.json b/@app/client/src/translations/en/events.json index 89617606a..889dca815 100644 --- a/@app/client/src/translations/en/events.json +++ b/@app/client/src/translations/en/events.json @@ -1,5 +1,5 @@ { - "addOpenQuota": "Add open quota", + "addOpenQuota": "Add overflow quota", "addOption": "Add option", "addQuestion": "Add question", "addQuota": "Add quota", @@ -11,15 +11,17 @@ "eventCategoryCreationFailed": "Creating event category failed", "eventCreateFailed": "Creating event failed", "eventUpdateFailed": "Updating event failed", - "formTabErrors": "Other errors", - "mustProvideEventQuota": "Must provide at least one quota for the event" + "mustProvideEventQuota": "The event must have at least one quota. An overflow quota alone is not enough." }, "eventName": "Event", "eventNotFound": "Event not found", "eventSignupNotOpen": "Event signup is not open", "forms": { "eventTime": "Event time", + "fillRequiredToSave": "Fill in all required fields to save", "highlightEvent": "Highlighted event", + "highlightText": "Highlight text", + "highlightTextHelp": "Leave empty to show the default text \"Check this out!\".", "isDraft": "Draft", "isHighlighted": "Highlighted", "isNotDraft": "Published", @@ -74,17 +76,46 @@ "saveAsDraft": "Save as draft", "signupEmail": "Event signup email" }, + "free": "Free", "headerImage": "Event header image", + "inQueueCount": "{{count}} in queue", "languages": "Languages", "numRegistrations": "Registered people", - "openQuota": "Open quota", + "openQuota": "Overflow quota", "organizer": "Organizer", + "overflowQuotaInfo": "The overflow quota is shared by all quotas: when a registrant’s own quota is full, they get a spot in the overflow quota if there is room. After that, registrants go to the queue.", + "paymentMethods": "Paid by card, Apple Pay or Google Pay.", + "prefill": { + "DIETARY_RESTRICTIONS": "Dietary restrictions", + "TELEGRAM": "Telegram", + "placeholder": "Prefilled from (optional)" + }, + "previewInfo": "This is how the registration form looks to registrants. You can try the form, but nothing is submitted from the preview.", + "questionsAutomaticallyCollected": "First name, last name and email are collected from registrants automatically, so you do not need to add them as questions.", "queued": "Queue", "quota": "Quota", "removeOption": "Remove option", "removeQuestion": "Remove question", "removeQuota": "Remove quota", "spots": "spots", + "templates": { + "questions": { + "confirmRemove": "Questions created by the event template will be removed, even if you have edited them. Continue?", + "label": "Event template", + "none": "No event template", + "presets": "Ready-made questions", + "sitsit": "Sitsit" + }, + "quotas": { + "confirmRemove": "Quotas created by the quota template will be removed, even if you have edited them. Continue?", + "label": "Quota template", + "none": "No quota template", + "openQuotaHint": "For a quota anyone can register to, add the “Open quota” quota.", + "presets": "Add individual quotas", + "yearGroups": "Quotas for all year groups", + "yearGroupsNote": "Remember to set a size for each quota." + } + }, "timer": { "instructions": "The page will update automatically once the registration opens. Please do not refresh the page.", "registrationStarts": "Opens", diff --git a/@app/client/src/translations/en/payments.json b/@app/client/src/translations/en/payments.json new file mode 100644 index 000000000..788f84073 --- /dev/null +++ b/@app/client/src/translations/en/payments.json @@ -0,0 +1,63 @@ +{ + "cancel": { + "noRefundNote": "Your payment is not refunded automatically. Contact the organizers about a refund." + }, + "cancelledNotice": "Payment wasn't completed. Your spot is still reserved, and you can try again below or later from your confirmation email.", + "confirmTimeoutNotice": "We haven't received confirmation of your payment yet. If you paid, you'll get a confirmation email shortly. You can also reload this page later.", + "confirmingNotice": "Confirming your payment with Stripe. This page updates on its own in a few seconds.", + "disabled": { + "body": "Online payments are not available right now. Contact the organizers if you have questions about paying.", + "title": "Payments are not available" + }, + "editRegistration": "Edit or cancel your registration", + "errors": { + "checkoutFailed": "Could not open the payment page" + }, + "event": "Event", + "name": "Name", + "notFound": { + "body": "Check the payment link in your email.", + "title": "Registration not found" + }, + "paidBanner": "Paid {{amount}} on {{date}}", + "pay": "Pay {{total}}", + "payNow": "Pay now", + "quota": "Quota", + "serviceFee": "Service fee", + "states": { + "free": { + "body": "Your quota is free. You are all set.", + "title": "No payment needed" + }, + "opensLater": { + "body": "Payment for this event opens when registration closes on {{date}} at {{time}}. The payment link will be emailed to you.", + "title": "Payment opens later" + }, + "paid": { + "body": "You paid {{amount}} on {{date}} at {{time}}. A confirmation has been sent to your email.", + "detail": "Stripe also emails you its own receipt.", + "title": "Payment received" + }, + "paidManually": { + "body": "The organizers have marked your registration as paid.", + "title": "Payment received" + }, + "queued": { + "body": "You are number {{position}} in the queue. You only pay if you get a spot, and we will email you a payment link if you do.", + "title": "You are in the queue" + } + }, + "tags": { + "free": "Free", + "inQueue": "In queue", + "notOpen": "Not yet open", + "paid": "Paid", + "processing": "Processing", + "unpaid": "Unpaid" + }, + "ticket": "Ticket", + "time": "Time", + "title": "Payment", + "total": "Total", + "unpaidBanner": "Your registration has not been paid yet." +} diff --git a/@app/client/src/translations/en/register_event.json b/@app/client/src/translations/en/register_event.json index ffb1a98df..6c8abec5b 100644 --- a/@app/client/src/translations/en/register_event.json +++ b/@app/client/src/translations/en/register_event.json @@ -1,26 +1,41 @@ { + "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?", "deleteRegistrationFailed": "Deleting event registration failed", "errors": { "registrationFailed": "Registering to the event failed", - "registrationUpdateFailed": "Failed to update registration information" + "registrationUpdateFailed": "Failed to update registration information", + "rememberAnswersFailed": "Your registration was saved, but remembering your answers failed" }, "eventSignupComplete": "Event signup saved", "forms": { "email": "E-mail", "firstName": "First name", "lastName": "Last name", + "rememberAnswers": "Remember these answers for my next registrations", "rules": { "emailEmpty": "Please input your E-mail", "emailValid": "The input is not valid E-mail", - "nameContainsSpace": "Name cannot contain spaces", "provideAnswer": "Please answer the question", "provideFirstName": "Please enter your first name", "provideLastName": "Please enter your last name" } }, + "payment": { + "info": "Ticket {{price}} + {{fee}} service fee. You don't pay now. We'll email you a payment link when registration closes on {{date}} at {{time}}.", + "register": "Register", + "title": "Payment" + }, + "previewNotSubmitted": "Preview: no registration was submitted", "recentlyRegisteredHeader": "Recently registered:", "recentlyRegisteredListItem": "recently registered to the quota", "registrationDeleteComplete": "Deleted registration", @@ -30,6 +45,7 @@ }, "title": "Register to event:", "updateRegistration": { + "closed": "Registration for this event has closed, so your registration can no longer be changed. Please contact the event organizers.", "title": "Update event registration information" }, "you": "You!" diff --git a/@app/client/src/translations/en/reminders.json b/@app/client/src/translations/en/reminders.json new file mode 100644 index 000000000..df9337633 --- /dev/null +++ b/@app/client/src/translations/en/reminders.json @@ -0,0 +1,71 @@ +{ + "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", + "offNotice": "Reminders are not in use right now. You can still remove your reminders and disconnect Telegram.", + "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..a280084a1 100644 --- a/@app/client/src/translations/en/settings.json +++ b/@app/client/src/translations/en/settings.json @@ -2,16 +2,20 @@ "buttons": { "addEmail": "Add email", "changePassphrase": "Change passphrase", + "deleteRegistrationProfile": "Delete registration details", "permanentDelete": "PERMANENTLY DELETE MY ACCOUNT", "resetPassphrase": "Reset passphrase", "returnHome": "Return to homepage", "updateProfile": "Update profile", + "updateRegistrationProfile": "Update registration details", "wantToDeleteAccount": "I want to delete my account" }, "errors": { "accountDeleteFailedOrgOwner1": "You cannot delete your account whilst you are the owner of an organization.", "accountDeleteFailedOrgOwner2": "For each organization you are the owner of, please either assign your ownership to another user or delete the organization to continue.", "deleteFailed": "Requesting deletion failed", + "errorDeletingRegistrationProfile": "Deleting registration details failed", + "errorUpdatingRegistrationProfile": "Updating registration details failed", "errorUpdatingUsername": "Error updating username", "incorrectOldPassword": "Incorrect old passphrase", "usernameTaken": "This username is already in use, please pick a different name" @@ -22,18 +26,24 @@ "emailAddFailed": "Error adding email", "passwordChangeFailed": "Changing passphrase failed", "passwordChanged": "Password changed!", - "profileUpdated": "Profile updated" + "profileUpdated": "Profile updated", + "registrationProfileDeleted": "Registration details deleted", + "registrationProfileUpdated": "Registration details updated" }, "label": { + "dietaryRestrictions": "Dietary restrictions", "newEmail": "New email", "newPassphrase": "New passphrase", - "oldPassphrase": "Old passphrase" + "oldPassphrase": "Old passphrase", + "telegram": "Telegram" }, "messages": { + "dietaryRestrictionsTooLong": "Dietary restrictions can be at most 1000 characters", "email": "Please enter an email address", "name": "Please enter your name", "newPassword": "Please confirm your passphrase", "oldPassword": "Please input your passphrase", + "telegramTooLong": "Telegram can be at most 64 characters", "username": "Please choose a username" } }, @@ -84,11 +94,18 @@ "socialLoginNoPassword": "You registered your account through social login, so you do not currently have a passphrase. If you would like a passphrase, press the button below to request a passphrase reset email to '{{email}}' (you can choose a different email by making it primary in)" } }, + "registrationProfile": { + "deleteConfirm": "Delete your saved registration details?", + "description": "These details prefill the Telegram and dietary restriction questions in registration forms. Only you can see them. They are saved here, or when you tick \"Remember these answers\" while registering.", + "offDescription": "Prefilling registration answers is currently turned off. You can still delete the registration details you saved." + }, "titles": { "accounts": "Linked accounts", "delete": "Delete account", "emails": "Email addresses", "index": "Edit profile", + "registrationProfile": "Registration details", + "reminders": "My reminders", "security": "Change passphrase" } } diff --git a/@app/client/src/translations/fi/admin.json b/@app/client/src/translations/fi/admin.json index 06c89b07d..2d07afaa0 100644 --- a/@app/client/src/translations/fi/admin.json +++ b/@app/client/src/translations/fi/admin.json @@ -27,6 +27,7 @@ "tabs": { "email": "Sähköposti", "generalInfo": "Yleistä", + "preview": "Esikatselu", "questions": "Kysymykset", "quotas": "Kiintiöt" }, @@ -35,6 +36,269 @@ "showEvent": "Tapahtumasivulle" } }, + "features": { + "adminsOnlyInfo": "Vain ylläpitäjät -tilassa voit kokeilla ominaisuutta ennen julkaisua. Kirjautuneet ylläpitäjät näkevät sen Esikatselu-merkinnällä. Muut eivät näe sitä, ja sähköpostit ja muistutukset toimivat kuin se olisi pois päältä.", + "cancel": "Peruuta", + "changeHistory": "Muutoshistoria", + "changedOutside": "Muutettu tämän sivun ulkopuolella", + "columns": { + "actions": "Toiminnot", + "feature": "Ominaisuus", + "lastChanged": "Viimeksi muutettu", + "state": "Tila" + }, + "confirmOff": { + "genericKeeps": "Jo tallennetut tiedot säilyvät ennallaan, ja jo aloitettu viedään loppuun.", + "genericStops": "Kukaan ei voi aloittaa ominaisuuden {{name}} käyttöä.", + "intro": { + "admins_only": "Muut kuin kirjautuneet ylläpitäjät lakkaavat näkemästä sen, ja sähköpostit ja muistutukset toimivat kuin se olisi pois päältä. Jo aloitettu jatkuu normaalisti.", + "off": "Pois kytkeminen piilottaa tavat aloittaa käyttö. Jo aloitettu jatkuu normaalisti." + }, + "keeps": "Toimii edelleen", + "ok": { + "admins_only": "Rajaa vain ylläpitäjille", + "off": "Kytke {{name}} pois" + }, + "stops": "Loppuu heti", + "title": { + "admins_only": "Rajataanko {{name}} vain ylläpitäjille?", + "off": "Kytketäänkö {{name}} pois päältä?" + } + }, + "confirmOn": { + "appliesNow": "Muutos tulee voimaan heti. Voit kytkeä sen takaisin pois tältä sivulta.", + "generic": "Kaiken, mitä {{name}} lisää, jokaisella sivulla sekä sähköposteissa ja muistutuksissa.", + "neverPreviewed": "Kukaan ei ole vielä esikatsellut tätä. Kokeile ensin tilaa Vain ylläpitäjät: näet ominaisuuden oikeilla sivuilla, muut eivät näe sitä, eivätkä sähköpostit muutu.", + "ok": "Kytke päälle kaikille", + "preview": "Esikatsele ensin ylläpitäjänä", + "previewedSince": "Ylläpitäjät ovat esikatselleet tätä {{date}} alkaen. {{actor}} asetti tilaksi Vain ylläpitäjät.", + "previewing": "Ylläpitäjät esikatselevat tätä parhaillaan.", + "title": "Kytketäänkö {{name}} päälle kaikille?", + "willSee": "Kaikki alkavat nähdä:" + }, + "counts": { + "admins_only": "{{count}} vain ylläpitäjille", + "off": "{{count}} pois päältä", + "on": "{{count}} päällä" + }, + "defaultOff": "Oletus: Pois", + "deletedUser": "Poistettu käyttäjä", + "dismiss": "Sulje", + "empty": "Ominaisuuksia ei vielä ole. Ne ilmestyvät tänne, kun niitä lisätään sovellukseen, ja jokainen on aluksi pois päältä.", + "flags": { + "calendar_invites": { + "name": "Kalenterikutsut", + "turnOn": [ + "Ilmoittautumisen vahvistussähköpostissa on kalenterikutsu.", + "Tapahtumasivu näyttää kalenterilinkit ilmoittautumisen jälkeen." + ], + "stops": [ + "Uusissa vahvistussähköposteissa ei ole kalenterikutsua ja kalenterilinkit piilotetaan." + ], + "keeps": [ + "Jo lähetetyt kutsut pysyvät vastaanottajien kalentereissa." + ] + }, + "confetti": { + "name": "Konfetti", + "turnOn": [ + "Tapahtuman tai ilmoittautumisen luomisen jälkeen näytetään konfettia, paitsi käyttäjille, jotka haluavat vähemmän liikettä." + ], + "stops": [ + "Konfettia ei enää näytetä." + ], + "keeps": [ + "Tapahtumien ja ilmoittautumisten luominen toimii kuten ennenkin." + ] + }, + "event_templates": { + "name": "Tapahtumapohjat", + "turnOn": [ + "Tapahtumalomakkeen kiintiö- ja kysymysvälilehdet tarjoavat pohjia sekä valmiita kiintiöitä ja kysymyksiä." + ], + "stops": [ + "Pohjien valinnat piilotetaan ja välilehdillä näkyvät pelkät listat." + ], + "keeps": [ + "Pohjasta lisätyt kiintiöt ja kysymykset säilyvät tapahtumissaan." + ] + }, + "form_preview": { + "name": "Ilmoittautumislomakkeen esikatselu", + "turnOn": [ + "Tapahtumalomakkeeseen tulee Esikatselu-välilehti, joka näyttää ilmoittautumislomakkeen niin kuin ilmoittautujat sen näkevät." + ], + "stops": [ + "Esikatselu-välilehti piilotetaan." + ], + "keeps": [ + "Esikatselusta ei koskaan lähetetä mitään, joten tiedot eivät muutu." + ] + }, + "keycloak_names": { + "name": "Nimet Keycloakista", + "turnOn": [ + "Ilmoittautumislomake täyttää Keycloakista tallennetun etu- ja sukunimen.", + "Ilman niitä lomake täyttää näyttönimen vain, jos siinä on enintään kaksi sanaa." + ], + "stops": [ + "Ilmoittautumislomake jakaa taas näyttönimen etu- ja sukunimeksi." + ], + "keeps": [ + "Etu- ja sukunimet tallennetaan edelleen jokaisella Keycloak-kirjautumisella.", + "Jo tehdyt ilmoittautumiset säilyttävät nimensä." + ] + }, + "mcp_server": { + "name": "MCP-palvelin", + "turnOn": [ + "MCP-palvelin vastaa osoitteessa /mcp: Keycloakin kautta kirjautuneet tekoälyavustajat voivat selata tapahtumia ja ilmoittautua, ja ylläpitäjät voivat luoda tapahtumaluonnoksia." + ], + "stops": [ + "/mcp ja sen OAuth-tunnistuspolut vastaavat 404." + ], + "keeps": [ + "MCP:n kautta tehdyt tapahtumat ja ilmoittautumiset säilyvät." + ] + }, + "payments": { + "name": "Maksut", + "turnOn": [ + "Ylläpitäjät voivat hinnoitella kiintiöitä. Maksullisten kiintiöiden ilmoittautujat maksavat ilmoittautumisen sulkeuduttua.", + "Maksullisten kiintiöiden ilmoittautujat maksavat Stripe Checkoutissa, ja maksusähköpostit ja -muistutukset lähetetään.", + "Ylläpitäjät saavat tapahtumiensa maksutyökalut." + ], + "stops": [ + "Hinnat piilotetaan eikä niitä voi asettaa, ja maksaminen estetään.", + "Uusia maksusähköposteja tai -muistutuksia ei lähetetä." + ], + "keeps": [ + "Jo tehdyt maksut pysyvät kirjattuina ja näkyvät ilmoittautujille.", + "Stripen maksuilmoitukset toimivat edelleen." + ] + }, + "prefill_answers": { + "name": "Muistetut ilmoittautumisvastaukset", + "turnOn": [ + "Ylläpitäjät voivat merkitä tekstikysymyksen kysymään ilmoittautujan Telegram-käyttäjänimeä tai erityisruokavalioita.", + "Ilmoittautumislomake esitäyttää nämä vastaukset käyttäjän tallentamista ilmoittautumistiedoista ja tarjoaa uusien vastausten muistamista.", + "Profiilin asetussivulla ilmoittautumistietoja voi muokata." + ], + "stops": [ + "Vastauksia ei enää esitäytetä, eikä ilmoittautumislomake tarjoa niiden muistamista.", + "Ilmoittautumistietoja ei voi enää tallentaa tai muokata." + ], + "keeps": [ + "Kysymykset säilyttävät Telegram- tai erityisruokavaliomerkintänsä ja toimivat tavallisina tekstikysymyksinä.", + "Käyttäjät voivat edelleen poistaa tallentamansa ilmoittautumistiedot." + ] + }, + "registration_reminders": { + "name": "Ilmoittautumismuistutukset", + "turnOn": [ + "Tapahtumasivu tarjoaa muistutusta ennen ilmoittautumisen alkua.", + "Asetuksiin tulee muistutussivu käyttäjän muistutuksille ja muistutusasetuksille.", + "Muistutussähköpostit lähetetään ennen ilmoittautumisen alkua." + ], + "stops": [ + "Muistutuspainike, muistutussivu ja sen valikkolinkit piilotetaan.", + "Muistutuksia ei lähetetä. Muistutusta, jonka aika tulee kun ominaisuus on pois päältä, ei lähetetä myöhemmin." + ], + "keeps": [ + "Tallennetut muistutukset ja muistutusasetukset säilyvät." + ] + }, + "ribbon_text": { + "name": "Nauhan teksti", + "turnOn": [ + "Tapahtumalomake näyttää nauhan tekstikentät korostetuille tapahtumille.", + "Tapahtumakorteissa näkyy oma nauhan teksti." + ], + "stops": [ + "Tapahtumakorteissa näkyy oletusteksti ja tapahtumalomake piilottaa kentät." + ], + "keeps": [ + "Tallennetut nauhan tekstit säilyvät, myös kun tapahtuma tallennetaan." + ] + }, + "telegram_reminders": { + "name": "Telegram-muistutukset", + "turnOn": [ + "Käyttäjät voivat yhdistää Telegram-tilin ja valita Telegramin muistutuksilleen.", + "Muistutukset lähetetään myös Telegram-botin kautta." + ], + "stops": [ + "Telegramia ei voi enää yhdistää tai valita, eikä muistutuksia lähetetä Telegramin kautta." + ], + "keeps": [ + "Yhdistetyt tilit pysyvät yhdistettyinä." + ] + }, + "typed_time_input": { + "name": "Kirjoitettavat ajat", + "turnOn": [ + "Tapahtumalomakkeessa tapahtuman ja ilmoittautumisen ajat kirjoitetaan tunti-, minuutti- ja sekuntikenttiin.", + "Päivän valitseminen kalenterista täyttää oletusajat." + ], + "stops": [ + "Tapahtumalomake palaa vieritettäviin aikasarakkeisiin." + ], + "keeps": [ + "Tallennetut tapahtuman ja ilmoittautumisen ajat pysyvät ennallaan." + ] + } + }, + "footer": "Uudet ominaisuudet tulevat sovelluksen päivitysten mukana ja ovat aluksi pois päältä.", + "history": "Historia", + "historyDrawer": { + "allFeatures": "Kaikki ominaisuudet", + "by": "{{actor}} · {{date}}", + "feature": "Ominaisuus", + "footerAll": "Näytetään kaikki {{count}} muutosta. Muutoksia ei voi muokata eikä poistaa.", + "footerOne": "Ennen {{date}} {{name}} oli pois päältä, mikä on uusien ominaisuuksien oletus.", + "none": "Ei vielä muutoksia. Uudet ominaisuudet ovat aluksi pois päältä.", + "title": "Muutoshistoria", + "titleFor": "Muutoshistoria: {{name}}" + }, + "historyLabel": "Ominaisuuden {{name}} muutoshistoria", + "intro": "Kytke sivuston ominaisuuksia päälle ja pois. Muutokset tulevat voimaan heti.", + "introDevelopers": "Vain kehittäjät näkevät tämän sivun. Kaikki ylläpitäjät näkevät ominaisuudet, joiden tila on Vain ylläpitäjät.", + "loadError": { + "description": "Mikään ei muuttunut. Jokainen ominaisuus pysyy käyttäjille nykyisessä tilassaan. Yritä hetken päästä uudelleen.", + "title": "Ominaisuuksia ei voitu ladata", + "tryAgain": "Yritä uudelleen" + }, + "neverChanged": "Ei koskaan muutettu", + "noAdminPreview": "Piilossa kaikilta. Vain ylläpitäjät -tilaa ei tarjota: ylläpitäjillä ei ole tässä mitään esikatseltavaa, joten se toimisi kuin Pois.", + "retired": "Vakiintunut: tämä ominaisuus on pysyvä ja aina päällä.", + "retry": "Yritä uudelleen", + "saveFailed": { + "admins_only": "Ominaisuutta {{name}} ei voitu asettaa tilaan Vain ylläpitäjät. Sen tila on edelleen {{state}}. Tarkista yhteytesi ja yritä uudelleen.", + "off": "Ominaisuutta {{name}} ei voitu kytkeä pois. Sen tila on edelleen {{state}}. Tarkista yhteytesi ja yritä uudelleen.", + "on": "Ominaisuutta {{name}} ei voitu kytkeä päälle. Sen tila on edelleen {{state}}. Tarkista yhteytesi ja yritä uudelleen." + }, + "saved": { + "admins_only": "{{name}} näkyy nyt vain ylläpitäjille.", + "off": "{{name}} on nyt pois päältä.", + "on": "{{name}} on nyt päällä kaikille." + }, + "saving": "Tallennetaan…", + "savingNote": "Tallennetaan. Muutos tulee voimaan, kun tallennus valmistuu.", + "sees": { + "admins_only": "Näkyy vain ylläpitäjille. Sähköpostit ja muistutukset toimivat kuin se olisi pois päältä.", + "off": "Piilossa kaikilta", + "on": "Näkyy kaikille" + }, + "stateGroupLabel": "Ominaisuuden {{name}} tila", + "states": { + "admins_only": "Vain ylläpitäjät", + "off": "Pois", + "on": "Päällä" + }, + "title": "Ominaisuudet", + "unavailable": "Ei määritetty: palvelimelta puuttuvat tämän ominaisuuden tarvitsemat asetukset. Kehittäjän täytyy lisätä ne, ennen kuin ominaisuuden voi kytkeä päälle.", + "you": "{{name}} (sinä)" + }, "notifications": { "deleteFailed": "Poisto epäonnistui", "deleteSuccess": "Poistettu onnistuneesti", @@ -93,6 +357,70 @@ "updateEvent": "Päivitä tapahtuma", "updateEventCategory": "Päivitä tapahtumakategoria" }, + "payments": { + "actions": { + "failed": "Maksun päivittäminen epäonnistui", + "markPaid": "Merkitse maksetuksi", + "markPaidHelp": "Käteis- tai tilisiirtomaksuille. Lähettää maksuvahvistuksen sähköpostilla.", + "markPaidSuccess": "Merkitty maksetuksi", + "more": "Lisää toimintoja", + "undoManual": "Peru käsin merkitty maksu", + "undoManualConfirm": "Poistetaanko käsin merkitty maksu? Ilmoittautuminen muuttuu maksamattomaksi.", + "undoManualSuccess": "Käsin merkitty maksu poistettu" + }, + "cancel": "Peruuta", + "delete": { + "body": "Paikka siirtyy jonossa seuraavalle. Poistoa ei voi perua.", + "confirm": "Poista", + "noRefundWarning": "Tämä ilmoittautuminen on maksettu. Mitään ei palauteta automaattisesti: hoida mahdollinen palautus itse (korttimaksut Stripen hallintapaneelissa).", + "title": "Poistetaanko käyttäjän {{name}} ilmoittautuminen?" + }, + "filter": { + "all": "Kaikki ({{count}})", + "paid": "Maksettu ({{count}})", + "unpaid": "Maksamatta ({{count}})" + }, + "lastReminderSent": "Viimeisin muistutus lähetetty {{date}} klo {{time}}", + "paymentColumn": "Maksu", + "quotas": { + "free": "Ilmainen", + "guildReceives": "Kilta saa", + "invalidPrice": "Hinnan on oltava 0 € tai 0,25 € – 10 000 €", + "noteFees": "Kilta saa = hinta − 1,5 % × (hinta + 0,25 €). Asiakas maksaa hinnan sekä 0,25 €:n palvelumaksun, ja Stripe perii 0,25 € + 1,5 %. Arvio koskee eurooppalaisia kortteja; ETA-alueen ulkopuoliset kortit maksavat hieman enemmän.", + "noteFree": "0 € tekee kiintiöstä ilmaisen. Muuten vähimmäishinta on 0,25 €.", + "noteOpenQuota": "Avoimen kiintiön paikoista maksetaan sen kiintiön hinta, jonka kautta henkilö ilmoittautui.", + "priceChangedWarning": "Tässä kiintiössä on {{count}} ilmoittautumista. Jo maksetut pysyvät maksettuina. Maksamattomat maksavat uuden hinnan.", + "priceChangedWarning_one": "Tässä kiintiössä on {{count}} ilmoittautuminen. Jos se on jo maksettu, se pysyy maksettuna. Muuten se maksaa uuden hinnan.", + "ticketPrice": "Lipun hinta" + }, + "reminder": { + "body": "Jokainen paikan saanut, joka ei ole maksanut, saa sähköpostin omalla maksulinkillään. Jonossa oleville ja ilmaisten kiintiöiden ilmoittautujille ei lähetetä viestiä.", + "confirm_one": "Lähetä {{count}} muistutus", + "confirm_other": "Lähetä {{count}} muistutusta", + "failed": "Muistutusten lähettäminen epäonnistui", + "lastSent": "Viimeisin muistutus lähetetty {{date}} klo {{time}}.", + "sent_one": "{{count}} muistutus lähetetty", + "sent_other": "{{count}} muistutusta lähetetty", + "title_one": "Lähetetäänkö maksumuistutus {{count}} henkilölle?", + "title_other": "Lähetetäänkö maksumuistutus {{count}} henkilölle?" + }, + "sendReminder": "Lähetä muistutus {{count}} maksamattomalle", + "status": { + "NOT_REQUIRED": "Ilmainen", + "PAID": "Maksettu", + "PAID_MANUALLY": "Maksettu käsin", + "UNPAID": "Maksamatta" + }, + "summary": { + "guildReceives": "Kilta saa", + "paid": "Maksettu", + "paidOf": "/ {{count}}", + "ticketsPaid": "Lippuja maksettu", + "unlinkedCardPayments_one": "{{count}} korttimaksu ei liity mihinkään ilmoittautumiseen (esimerkiksi tuplamaksu tai poistetun ilmoittautumisen maksu). Palauta se tarvittaessa käsin Stripen hallintapaneelissa.", + "unlinkedCardPayments_other": "{{count}} korttimaksua ei liity mihinkään ilmoittautumiseen (esimerkiksi tuplamaksuja tai poistettujen ilmoittautumisten maksuja). Palauta ne tarvittaessa käsin Stripen hallintapaneelissa.", + "unpaid": "Maksamatta" + } + }, "registrations": { "delete": { "confirmText": "Haluatko varmasti poistaa tämän ilmoittautumisen?", @@ -110,6 +438,7 @@ "emails": "Sähköpostit", "eventCategories": "Tapahtumakategoriat", "events": "Tapahtumat", + "features": "Ominaisuudet", "listEventCategories": "Näytä tapahtumakategoriat", "listEvents": "Näytä tapahtumat", "main": "Dashboard", diff --git a/@app/client/src/translations/fi/common.json b/@app/client/src/translations/fi/common.json index c9bcbc1fa..3f755f54c 100644 --- a/@app/client/src/translations/fi/common.json +++ b/@app/client/src/translations/fi/common.json @@ -15,6 +15,12 @@ "email": "Sähköposti", "emailSwitchLabel": "Näytä html-versio", "error": "Virhe", + "featurePreview": { + "adminHint": "Ei vielä julkaistu. Pyydä kehittäjää julkaisemaan se.", + "developerHint": "Muut käyttäjät eivät vielä näe tätä.", + "manage": "Hallitse Ominaisuudet-sivulla", + "tag": "Esikatselu: näkyy vain ylläpitäjille" + }, "head": { "description": "Prodeko ilmo", "title": "Prodeko ilmo" @@ -52,6 +58,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/events.json b/@app/client/src/translations/fi/events.json index d0f131eeb..b0d62b200 100644 --- a/@app/client/src/translations/fi/events.json +++ b/@app/client/src/translations/fi/events.json @@ -1,5 +1,5 @@ { - "addOpenQuota": "Lisää avoin kiintiö", + "addOpenQuota": "Lisää ylivuotokiintiö", "addOption": "Lisää vaihtoehto", "addQuestion": "Lisää kysymys", "addQuota": "Lisää kiintiö", @@ -11,15 +11,17 @@ "eventCategoryCreationFailed": "Tapahtumakategorian luonti epäonnistui", "eventCreateFailed": "Tapahtuman luonti epäonnistui", "eventUpdateFailed": "Tapahtuman päivittäminen epäonnistui", - "formTabErrors": "Muut virheet", - "mustProvideEventQuota": "Tapahtumalle on määritettävä vähintään yksi kiintiö" + "mustProvideEventQuota": "Tapahtumalle on määritettävä vähintään yksi kiintiö. Ylivuotokiintiö ei yksin riitä." }, "eventName": "Tapahtuma", "eventNotFound": "Tapahtumaa ei löytynyt", "eventSignupNotOpen": "Tapahtuman ilmoittautuminen ei ole auki", "forms": { "eventTime": "Tapahtuman ajankohta", + "fillRequiredToSave": "Täytä kaikki pakolliset kentät tallentaaksesi", "highlightEvent": "Korostettu tapahtuma", + "highlightText": "Korostuksen teksti", + "highlightTextHelp": "Jätä tyhjäksi, niin näytetään oletusteksti \"Nätti tapahtuma!\".", "isDraft": "Luonnos", "isHighlighted": "Korostettu", "isNotDraft": "Julkaistu", @@ -74,17 +76,46 @@ "saveAsDraft": "Tallenna luonnoksena", "signupEmail": "Sähköposti" }, + "free": "Maksuton", "headerImage": "Tapahtuman kansikuva", + "inQueueCount": "{{count}} jonossa", "languages": "Kielet", "numRegistrations": "Ilmoittautuneita", - "openQuota": "Avoin kiintiö", + "openQuota": "Ylivuotokiintiö", "organizer": "Järjestäjä", + "overflowQuotaInfo": "Ylivuotokiintiö on yhteinen kaikille kiintiöille: kun ilmoittautujan oma kiintiö on täynnä, hän saa paikan ylivuotokiintiöstä, jos siinä on tilaa. Sen jälkeen ilmoittautujat menevät jonoon.", + "paymentMethods": "Maksu kortilla, Apple Paylla tai Google Paylla.", + "prefill": { + "DIETARY_RESTRICTIONS": "Erityisruokavaliot", + "TELEGRAM": "Telegram", + "placeholder": "Esitäytetään (valinnainen)" + }, + "previewInfo": "Näin ilmoittautumislomake näkyy ilmoittautujille. Voit kokeilla lomaketta, mutta esikatselusta ei lähetetä ilmoittautumista.", + "questionsAutomaticallyCollected": "Etunimi, sukunimi ja sähköposti kysytään ilmoittautujilta automaattisesti, joten niitä ei tarvitse lisätä kysymyksiksi.", "queued": "Jonossa", "quota": "Kiintiö", "removeOption": "Poista vaihtoehto", "removeQuestion": "Poista kysymys", "removeQuota": "Poista kiintiö", "spots": "paikkaa", + "templates": { + "questions": { + "confirmRemove": "Tapahtumapohjan luomat kysymykset poistetaan, myös jos olet muokannut niitä. Jatketaanko?", + "label": "Tapahtumapohja", + "none": "Ei tapahtumapohjaa", + "presets": "Valmiit kysymykset", + "sitsit": "Sitsit" + }, + "quotas": { + "confirmRemove": "Kiintiöpohjan luomat kiintiöt poistetaan, myös jos olet muokannut niitä. Jatketaanko?", + "label": "Kiintiöpohja", + "none": "Ei kiintiöpohjaa", + "openQuotaHint": "Jos haluat kiintiön, johon kuka tahansa voi ilmoittautua, lisää kiintiö “Avoin kiintiö”.", + "presets": "Lisää yksittäiset kiintiöt", + "yearGroups": "Kiintiöt kaikille vuosikursseille", + "yearGroupsNote": "Muista lisätä kiintiöille koot." + } + }, "timer": { "instructions": "Sivu päivittyy automaattisesti kun ilmo aukeaa. Älä päivitä sivua omatoimisesti.", "registrationStarts": "Ilmo aukeaa", diff --git a/@app/client/src/translations/fi/payments.json b/@app/client/src/translations/fi/payments.json new file mode 100644 index 000000000..d9a6f7a52 --- /dev/null +++ b/@app/client/src/translations/fi/payments.json @@ -0,0 +1,63 @@ +{ + "cancel": { + "noRefundNote": "Maksuasi ei palauteta automaattisesti. Ota yhteyttä järjestäjiin palautuksesta." + }, + "cancelledNotice": "Maksu jäi kesken. Paikkasi on edelleen varattu, ja voit yrittää uudelleen alta tai myöhemmin vahvistussähköpostin linkistä.", + "confirmTimeoutNotice": "Emme ole vielä saaneet vahvistusta maksustasi. Jos maksoit, saat pian vahvistuksen sähköpostiisi. Voit myös ladata tämän sivun myöhemmin uudelleen.", + "confirmingNotice": "Vahvistetaan maksuasi Stripeltä. Sivu päivittyy itsestään muutamassa sekunnissa.", + "disabled": { + "body": "Verkkomaksut eivät ole juuri nyt käytössä. Ota yhteyttä järjestäjiin, jos sinulla on kysyttävää maksamisesta.", + "title": "Maksut eivät ole käytössä" + }, + "editRegistration": "Muokkaa tai peru ilmoittautumisesi", + "errors": { + "checkoutFailed": "Maksusivun avaaminen epäonnistui" + }, + "event": "Tapahtuma", + "name": "Nimi", + "notFound": { + "body": "Tarkista sähköpostisi maksulinkki.", + "title": "Ilmoittautumista ei löytynyt" + }, + "paidBanner": "Maksettu {{amount}} {{date}}", + "pay": "Maksa {{total}}", + "payNow": "Maksa nyt", + "quota": "Kiintiö", + "serviceFee": "Palvelumaksu", + "states": { + "free": { + "body": "Kiintiösi on maksuton. Kaikki on valmista.", + "title": "Ei maksettavaa" + }, + "opensLater": { + "body": "Maksaminen avautuu, kun ilmoittautuminen sulkeutuu {{date}} klo {{time}}. Maksulinkki lähetetään sinulle sähköpostitse.", + "title": "Maksaminen avautuu myöhemmin" + }, + "paid": { + "body": "Maksoit {{amount}} {{date}} klo {{time}}. Vahvistus on lähetetty sähköpostiisi.", + "detail": "Stripe lähettää sinulle myös oman kuittinsa.", + "title": "Maksu vastaanotettu" + }, + "paidManually": { + "body": "Järjestäjät ovat merkinneet ilmoittautumisesi maksetuksi.", + "title": "Maksu vastaanotettu" + }, + "queued": { + "body": "Olet jonossa sijalla {{position}}. Maksat vain, jos saat paikan, ja lähetämme sinulle silloin maksulinkin.", + "title": "Olet jonossa" + } + }, + "tags": { + "free": "Maksuton", + "inQueue": "Jonossa", + "notOpen": "Ei vielä auki", + "paid": "Maksettu", + "processing": "Käsitellään", + "unpaid": "Maksamatta" + }, + "ticket": "Lippu", + "time": "Aika", + "title": "Maksu", + "total": "Yhteensä", + "unpaidBanner": "Ilmoittautumistasi ei ole vielä maksettu." +} diff --git a/@app/client/src/translations/fi/register_event.json b/@app/client/src/translations/fi/register_event.json index 4c439c23f..08d7edf2a 100644 --- a/@app/client/src/translations/fi/register_event.json +++ b/@app/client/src/translations/fi/register_event.json @@ -1,26 +1,41 @@ { + "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?", "deleteRegistrationFailed": "Ilmoittautumisen poistaminen epäonnistui", "errors": { "registrationFailed": "Tapahtumaan ilmoittautuminen epäonnistui", - "registrationUpdateFailed": "Tietojen päivittäminen epäonnistui" + "registrationUpdateFailed": "Tietojen päivittäminen epäonnistui", + "rememberAnswersFailed": "Ilmoittautumisesi tallentui, mutta vastaustesi muistaminen epäonnistui" }, "eventSignupComplete": "Ilmoittautuminen tallennettu", "forms": { "email": "Sähköposti", "firstName": "Etunimi", "lastName": "Sukunimi", + "rememberAnswers": "Muista nämä vastaukset seuraavia ilmoittautumisiani varten", "rules": { "emailEmpty": "Sähköpostiosoite ei voi olla tyhjä", "emailValid": "Tarkista sähköpostiosoite", - "nameContainsSpace": "Nimi ei saa sisältää välilyöntejä", "provideAnswer": "Vastaus vaaditaan", "provideFirstName": "Anna etunimi", "provideLastName": "Anna sukunimi" } }, + "payment": { + "info": "Lippu {{price}} + {{fee}} palvelumaksu. Et maksa nyt. Lähetämme sinulle maksulinkin sähköpostitse, kun ilmoittautuminen sulkeutuu {{date}} klo {{time}}.", + "register": "Ilmoittaudu", + "title": "Maksu" + }, + "previewNotSubmitted": "Esikatselu: ilmoittautumista ei lähetetty", "recentlyRegisteredHeader": "Äskettäin ilmoittautuneet:", "recentlyRegisteredListItem": "ilmoittautui juuri kiintiöön", "registrationDeleteComplete": "Ilmoittautuminen poistettu onnistuneesti", @@ -30,6 +45,7 @@ }, "title": "Ilmoittaudu tapahtumaan:", "updateRegistration": { + "closed": "Ilmoittautuminen tähän tapahtumaan on päättynyt, joten ilmoittautumistasi ei voi enää muuttaa. Ota yhteyttä tapahtuman järjestäjiin.", "title": "Päivitä rekisteröitymistiedot" }, "you": "Sinä!" diff --git a/@app/client/src/translations/fi/reminders.json b/@app/client/src/translations/fi/reminders.json new file mode 100644 index 000000000..b755fb090 --- /dev/null +++ b/@app/client/src/translations/fi/reminders.json @@ -0,0 +1,71 @@ +{ + "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ää", + "offNotice": "Muistutukset eivät ole nyt käytössä. Voit silti poistaa muistutuksesi ja katkaista Telegram-yhteyden.", + "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..54871a04c 100644 --- a/@app/client/src/translations/fi/settings.json +++ b/@app/client/src/translations/fi/settings.json @@ -2,16 +2,20 @@ "buttons": { "addEmail": "Lisää sähköposti", "changePassphrase": "Vaihda salasana", + "deleteRegistrationProfile": "Poista ilmoittautumistiedot", "permanentDelete": "POISTA KÄYTTÄJÄ LOPULLISESTI", "resetPassphrase": "Resetoi salasana", "returnHome": "Palaa etusivulle", "updateProfile": "Päivitä tiedot", + "updateRegistrationProfile": "Päivitä ilmoittautumistiedot", "wantToDeleteAccount": "Haluan poistaa käyttäjäni" }, "errors": { "accountDeleteFailedOrgOwner1": "Et voi poistaa tiliäsi, kun olet organisaation omistaja.", "accountDeleteFailedOrgOwner2": "Määritä omistajuutesi toiselle käyttäjälle tai poista organisaatio jokaisen omistamasi organisaation kohdalla.", "deleteFailed": "Poistopyyntö epäonnistui", + "errorDeletingRegistrationProfile": "Ilmoittautumistietojen poistaminen epäonnistui", + "errorUpdatingRegistrationProfile": "Ilmoittautumistietojen päivittäminen epäonnistui", "errorUpdatingUsername": "Virhe päivitettäesssä käyttäjänimeä", "incorrectOldPassword": "Väärä vanha salasana", "usernameTaken": "Tämä käyttäjänimi on jo käytössä, valitse toinen käyttäjänimi" @@ -22,18 +26,24 @@ "emailAddFailed": "Virhe lisättäessä sähköpostia", "passwordChangeFailed": "Salasanan vaihtaminen epäonnistui", "passwordChanged": "Salasana vaihdettu!", - "profileUpdated": "Profiili päivitetty" + "profileUpdated": "Profiili päivitetty", + "registrationProfileDeleted": "Ilmoittautumistiedot poistettu", + "registrationProfileUpdated": "Ilmoittautumistiedot päivitetty" }, "label": { + "dietaryRestrictions": "Erityisruokavaliot", "newEmail": "Uusi sähköpostil", "newPassphrase": "Uusi salasana", - "oldPassphrase": "Vanha salasana" + "oldPassphrase": "Vanha salasana", + "telegram": "Telegram" }, "messages": { + "dietaryRestrictionsTooLong": "Erityisruokavaliot saavat olla enintään 1000 merkkiä", "email": "Kirjoita sähköpostiosoite", "name": "Kirjoita nimesi", "newPassword": "Vahvista tunnuslause", "oldPassword": "Kirjoita salasana", + "telegramTooLong": "Telegram saa olla enintään 64 merkkiä", "username": "Valitse käyttäjätunnus" } }, @@ -84,11 +94,18 @@ "socialLoginNoPassword": "Rekisteröit tilisi sosiaalisen kirjautumisen kautta, joten sinulla ei ole tällä hetkellä salasanaa. Jos haluat tunnuslauseen, paina alla olevaa painiketta ja pyydä salasanan vaihtosähköposti osoitteeseen {{email}} (voit valita toisen sähköpostin asettamalla sen ensisijaiseksi" } }, + "registrationProfile": { + "deleteConfirm": "Poistetaanko tallentamasi ilmoittautumistiedot?", + "description": "Näillä tiedoilla esitäytetään ilmoittautumislomakkeen Telegram- ja erityisruokavaliokysymykset. Tiedot näkyvät vain sinulle. Ne tallentuvat täällä tai kun valitset ilmoittautuessasi \"Muista nämä vastaukset\".", + "offDescription": "Ilmoittautumisvastausten esitäyttö on tällä hetkellä pois käytöstä. Voit silti poistaa tallentamasi ilmoittautumistiedot." + }, "titles": { "accounts": "Linkitetyt tilit", "delete": "Poista käyttäjä", "emails": "Sähköpostiosoitteet", "index": "Muokkaa tiliä", + "registrationProfile": "Ilmoittautumistiedot", + "reminders": "Omat muistutukset", "security": "Vaihda salasana" } } diff --git a/@app/client/src/translations/se/admin.json b/@app/client/src/translations/se/admin.json index 4900dc9d7..6d4c05033 100644 --- a/@app/client/src/translations/se/admin.json +++ b/@app/client/src/translations/se/admin.json @@ -27,6 +27,7 @@ "tabs": { "email": "E-post", "generalInfo": "Allmänt", + "preview": "Förhandsvisning", "questions": "Frågor", "quotas": "Kvoter" }, @@ -35,6 +36,269 @@ "showEvent": "Visa händelse" } }, + "features": { + "adminsOnlyInfo": "Med Bara administratörer kan du prova en funktion innan den publiceras. Inloggade administratörer ser den med en förhandsvisningsetikett. Andra ser den inte, och e-post och påminnelser behandlar den som avslagen.", + "cancel": "Avbryt", + "changeHistory": "Ändringshistorik", + "changedOutside": "Ändrad utanför den här sidan", + "columns": { + "actions": "Åtgärder", + "feature": "Funktion", + "lastChanged": "Senast ändrad", + "state": "Läge" + }, + "confirmOff": { + "genericKeeps": "Data som redan har sparats förblir som den är, och det som redan har påbörjats slutförs.", + "genericStops": "Ingen kan börja använda {{name}}.", + "intro": { + "admins_only": "Alla utom inloggade administratörer slutar se den, och e-post och påminnelser behandlar den som avslagen. Det som redan har påbörjats fortsätter att fungera.", + "off": "Att slå av döljer vägarna in. Det som redan har påbörjats fortsätter att fungera." + }, + "keeps": "Fortsätter att fungera", + "ok": { + "admins_only": "Begränsa till administratörer", + "off": "Slå av {{name}}" + }, + "stops": "Upphör nu", + "title": { + "admins_only": "Begränsa {{name}} till administratörer?", + "off": "Slå av {{name}}?" + } + }, + "confirmOn": { + "appliesNow": "Ändringen gäller direkt. Du kan slå av den igen på den här sidan.", + "generic": "Allt som {{name}} lägger till, på varje sida och i e-post och påminnelser.", + "neverPreviewed": "Ingen har förhandsvisat detta ännu. Prova Bara administratörer först: du ser funktionen på riktiga sidor, ingen annan gör det och ingen e-post ändras.", + "ok": "Slå på för alla", + "preview": "Förhandsvisa för administratörer först", + "previewedSince": "Administratörer har förhandsvisat detta sedan {{date}}. {{actor}} ställde in Bara administratörer.", + "previewing": "Administratörer förhandsvisar detta just nu.", + "title": "Slå på {{name}} för alla?", + "willSee": "Alla börjar se:" + }, + "counts": { + "admins_only": "{{count}} bara administratörer", + "off": "{{count}} av", + "on": "{{count}} på" + }, + "defaultOff": "Standard: Av", + "deletedUser": "Raderad användare", + "dismiss": "Stäng", + "empty": "Inga funktioner ännu. Funktioner visas här när de läggs till i appen, och var och en är först avslagen.", + "flags": { + "calendar_invites": { + "name": "Kalenderinbjudningar", + "turnOn": [ + "Registreringens bekräftelsemejl innehåller en kalenderinbjudan.", + "Evenemangssidan visar kalenderlänkar efter registreringen." + ], + "stops": [ + "Nya bekräftelsemejl har ingen kalenderinbjudan och kalenderlänkarna döljs." + ], + "keeps": [ + "Redan skickade inbjudningar finns kvar i mottagarnas kalendrar." + ] + }, + "confetti": { + "name": "Konfetti", + "turnOn": [ + "Konfetti visas efter att ett evenemang eller en registrering har skapats, utom för användare som föredrar mindre rörelse." + ], + "stops": [ + "Ingen mer konfetti." + ], + "keeps": [ + "Att skapa evenemang och registreringar fungerar som förut." + ] + }, + "event_templates": { + "name": "Evenemangsmallar", + "turnOn": [ + "Evenemangsformulärets flikar för kvoter och frågor erbjuder mallar och färdiga kvoter och frågor." + ], + "stops": [ + "Mallvalen döljs och flikarna visar bara listorna." + ], + "keeps": [ + "Kvoter och frågor som lagts till från en mall finns kvar i sina evenemang." + ] + }, + "form_preview": { + "name": "Förhandsvisning av registreringsformuläret", + "turnOn": [ + "Evenemangsformuläret får fliken Förhandsvisning som visar registreringsformuläret så som de som registrerar sig ser det." + ], + "stops": [ + "Fliken Förhandsvisning döljs." + ], + "keeps": [ + "Ingenting skickas någonsin från förhandsvisningen, så inga uppgifter ändras." + ] + }, + "keycloak_names": { + "name": "Namn från Keycloak", + "turnOn": [ + "Registreringsformuläret fyller i för- och efternamnet som sparats från Keycloak.", + "Utan dem fyller formuläret i visningsnamnet bara om det har högst två ord." + ], + "stops": [ + "Registreringsformuläret delar åter visningsnamnet i för- och efternamn." + ], + "keeps": [ + "För- och efternamn sparas fortfarande vid varje Keycloak-inloggning.", + "Redan gjorda registreringar behåller sina namn." + ] + }, + "mcp_server": { + "name": "MCP-server", + "turnOn": [ + "MCP-servern svarar på /mcp: AI-assistenter som loggat in via Keycloak kan bläddra bland evenemang och registrera sig, och administratörer kan skapa utkast till evenemang." + ], + "stops": [ + "/mcp och dess OAuth-sökvägar svarar 404." + ], + "keeps": [ + "Evenemang och registreringar som gjorts via MCP behålls." + ] + }, + "payments": { + "name": "Betalningar", + "turnOn": [ + "Administratörer kan prissätta kvoter. De som registrerar sig i betalda kvoter betalar efter att anmälan har stängt.", + "De som registrerar sig i betalda kvoter betalar via Stripe Checkout, och betalningsmejl och påminnelser skickas.", + "Administratörer får betalningsverktygen för sina evenemang." + ], + "stops": [ + "Priser döljs och kan inte anges, och betalning blockeras.", + "Inga nya betalningsmejl eller påminnelser skickas." + ], + "keeps": [ + "Redan gjorda betalningar förblir registrerade och visas för de som registrerat sig.", + "Stripes betalningsaviseringar fortsätter att fungera." + ] + }, + "prefill_answers": { + "name": "Sparade anmälningssvar", + "turnOn": [ + "Administratörer kan markera en textfråga som frågar efter deltagarens Telegram-användarnamn eller specialdieter.", + "Anmälningsformuläret fyller i dessa svar från användarens sparade anmälningsuppgifter och erbjuder att komma ihåg nya svar.", + "Profilinställningarna visar anmälningsuppgifterna för redigering." + ], + "stops": [ + "Svaren fylls inte längre i och anmälningsformuläret erbjuder inte längre att komma ihåg dem.", + "Anmälningsuppgifterna kan inte längre sparas eller redigeras." + ], + "keeps": [ + "Frågorna behåller sin Telegram- eller specialdietmarkering och fungerar som vanliga textfrågor.", + "Användare kan fortfarande radera de anmälningsuppgifter de har sparat." + ] + }, + "registration_reminders": { + "name": "Registreringspåminnelser", + "turnOn": [ + "Evenemangssidan erbjuder en påminnelse innan registreringen öppnar.", + "Inställningarna får en sida med användarens påminnelser och påminnelseinställningar.", + "Påminnelsemejl skickas innan registreringen öppnar." + ], + "stops": [ + "Påminnelseknappen, påminnelsesidan och dess menylänkar döljs.", + "Inga påminnelser skickas. En påminnelse som infaller medan funktionen är av skickas inte senare." + ], + "keeps": [ + "Sparade påminnelser och påminnelseinställningar behålls." + ] + }, + "ribbon_text": { + "name": "Bandtext", + "turnOn": [ + "Evenemangsformuläret visar fält för bandtext för framhävda evenemang.", + "Evenemangskorten visar den egna bandtexten." + ], + "stops": [ + "Evenemangskorten visar standardtexten och evenemangsformuläret döljer fälten." + ], + "keeps": [ + "Sparade bandtexter behålls, även när ett evenemang sparas." + ] + }, + "telegram_reminders": { + "name": "Telegram-påminnelser", + "turnOn": [ + "Användare kan koppla ett Telegram-konto och välja Telegram för sina påminnelser.", + "Påminnelser skickas också via Telegram-boten." + ], + "stops": [ + "Telegram kan inte längre kopplas eller väljas, och inga påminnelser skickas via Telegram." + ], + "keeps": [ + "Kopplade konton förblir kopplade." + ] + }, + "typed_time_input": { + "name": "Inskrivna tider", + "turnOn": [ + "Evenemangsformuläret använder fält för timmar, minuter och sekunder för evenemangets och registreringens tider.", + "Ett klick på en dag i kalendern fyller i standardtider." + ], + "stops": [ + "Evenemangsformuläret går tillbaka till rullande tidskolumner." + ], + "keeps": [ + "Sparade evenemangs- och registreringstider förblir oförändrade." + ] + } + }, + "footer": "Nya funktioner kommer med uppdateringar av appen och är först avslagna.", + "history": "Historik", + "historyDrawer": { + "allFeatures": "Alla funktioner", + "by": "{{actor}} · {{date}}", + "feature": "Funktion", + "footerAll": "Visar alla {{count}} ändringar. Ändringar kan inte redigeras eller raderas.", + "footerOne": "Före {{date}} var {{name}} av, standardläget för nya funktioner.", + "none": "Inga ändringar ännu. Nya funktioner är först avslagna.", + "title": "Ändringshistorik", + "titleFor": "Ändringshistorik: {{name}}" + }, + "historyLabel": "Ändringshistorik för {{name}}", + "intro": "Slå på och av funktioner på den här webbplatsen. Ändringarna gäller direkt.", + "introDevelopers": "Bara utvecklare ser den här sidan. Alla administratörer ser funktioner som är inställda på Bara administratörer.", + "loadError": { + "description": "Ingenting har ändrats. Varje funktion behåller sitt nuvarande läge för användarna. Försök igen om en stund.", + "title": "Det gick inte att läsa in funktionerna", + "tryAgain": "Försök igen" + }, + "neverChanged": "Aldrig ändrad", + "noAdminPreview": "Dold för alla. Bara administratörer erbjuds inte: administratörer har inget att förhandsgranska här, så den skulle fungera som Av.", + "retired": "Pensionerad: funktionen är permanent och alltid på.", + "retry": "Försök igen", + "saveFailed": { + "admins_only": "Det gick inte att ställa in {{name}} på Bara administratörer. Läget är fortfarande {{state}}. Kontrollera din anslutning och försök igen.", + "off": "Det gick inte att slå av {{name}}. Läget är fortfarande {{state}}. Kontrollera din anslutning och försök igen.", + "on": "Det gick inte att slå på {{name}}. Läget är fortfarande {{state}}. Kontrollera din anslutning och försök igen." + }, + "saved": { + "admins_only": "{{name}} syns nu bara för administratörer.", + "off": "{{name}} är nu av.", + "on": "{{name}} är nu på för alla." + }, + "saving": "Sparar…", + "savingNote": "Sparar. Ändringen gäller när det är klart.", + "sees": { + "admins_only": "Syns bara för administratörer. E-post och påminnelser behandlar den som avslagen.", + "off": "Dold för alla", + "on": "Syns för alla" + }, + "stateGroupLabel": "Läge för {{name}}", + "states": { + "admins_only": "Bara administratörer", + "off": "Av", + "on": "På" + }, + "title": "Funktioner", + "unavailable": "Inte konfigurerad: servern saknar inställningar som funktionen behöver. En utvecklare måste lägga till dem innan den kan slås på.", + "you": "{{name}} (du)" + }, "notifications": { "deleteFailed": "Det gick inte att ta bort", "deleteSuccess": "Raderades framgångsrikt", @@ -93,6 +357,68 @@ "updateEvent": "Uppdatera händelse", "updateEventCategory": "Uppdatera händelsekategori" }, + "payments": { + "actions": { + "failed": "Det gick inte att uppdatera betalningen", + "markPaid": "Markera som betald", + "markPaidHelp": "För kontant- eller banköverföring. Skickar e-postbekräftelsen om mottagen betalning.", + "markPaidSuccess": "Markerad som betald", + "more": "Fler åtgärder", + "undoManual": "Ångra manuell betalning", + "undoManualSuccess": "Manuell betalning borttagen" + }, + "cancel": "Avbryt", + "delete": { + "body": "Platsen går till nästa person i kön. Detta kan inte ångras.", + "confirm": "Radera", + "noRefundWarning": "Denna anmälan har betalats. Inget återbetalas automatiskt: sköt en eventuell återbetalning själv (kortbetalningar i Stripe Dashboard).", + "title": "Radera anmälan för {{name}}?" + }, + "filter": { + "all": "Alla ({{count}})", + "paid": "Betalda ({{count}})", + "unpaid": "Obetalda ({{count}})" + }, + "lastReminderSent": "Senaste påminnelse skickad {{date}} kl. {{time}}", + "paymentColumn": "Betalning", + "quotas": { + "free": "Gratis", + "guildReceives": "Gillet får", + "invalidPrice": "Priset måste vara 0 € eller mellan 0,25 € och 10 000 €", + "noteFees": "Gillet får = pris − 1,5 % × (pris + 0,25 €). Kunden betalar priset plus en serviceavgift på 0,25 €, och Stripe tar 0,25 € + 1,5 %. Detta är en uppskattning för europeiska kort; kort från länder utanför EES kostar lite mer.", + "noteFree": "0 € gör kvoten gratis. Annars är minimipriset 0,25 €.", + "noteOpenQuota": "Platser i den öppna kvoten betalar priset för den kvot personen anmälde sig via.", + "priceChangedWarning": "Denna kvot har {{count}} anmälningar. De som redan har betalat förblir betalda. Obetalda betalar det nya priset.", + "ticketPrice": "Biljettpris" + }, + "reminder": { + "body": "Alla med en plats som inte har betalat får ett e-postmeddelande med sin egen betalningslänk. Personer i kön och i gratiskvoter får inget meddelande.", + "confirm_one": "Skicka {{count}} påminnelse", + "confirm_other": "Skicka {{count}} påminnelser", + "failed": "Det gick inte att skicka påminnelserna", + "lastSent": "Senaste påminnelse skickad {{date}} kl. {{time}}.", + "sent_one": "{{count}} påminnelse skickad", + "sent_other": "{{count}} påminnelser skickade", + "title_one": "Skicka en betalningspåminnelse till {{count}} person?", + "title_other": "Skicka en betalningspåminnelse till {{count}} personer?" + }, + "sendReminder": "Skicka påminnelse till {{count}} obetalda", + "status": { + "NOT_REQUIRED": "Gratis", + "PAID": "Betald", + "PAID_MANUALLY": "Betald manuellt", + "UNPAID": "Obetald" + }, + "summary": { + "guildReceives": "Gillet får", + "paid": "Betalda", + "paidOf": "av {{count}}", + "ticketsPaid": "Betalda biljetter", + "unlinkedCardPayments_one": "{{count}} kortbetalning är inte kopplad till någon anmälan (till exempel en dubbelbetalning eller en betalning för en raderad anmälan). Återbetala den manuellt i Stripe Dashboard vid behov.", + "unlinkedCardPayments_other": "{{count}} kortbetalningar är inte kopplade till någon anmälan (till exempel dubbelbetalningar eller betalningar för raderade anmälningar). Återbetala dem manuellt i Stripe Dashboard vid behov.", + "unpaid": "Obetalda" + } + }, "registrations": { "delete": { "confirmText": "Är du säker på att du vill ta bort denna registrering?", @@ -110,6 +436,7 @@ "emails": "E-postmeddelanden", "eventCategories": "Händelsekategorier", "events": "Händelser", + "features": "Funktioner", "listEventCategories": "Lista händelsekategorier", "listEvents": "Lista händelser", "main": "Dashboard", diff --git a/@app/client/src/translations/se/common.json b/@app/client/src/translations/se/common.json index e4cc3771d..21a76050e 100644 --- a/@app/client/src/translations/se/common.json +++ b/@app/client/src/translations/se/common.json @@ -15,6 +15,12 @@ "email": "E-post", "emailSwitchLabel": "Visa html-version", "error": "Fel", + "featurePreview": { + "adminHint": "Inte publicerad ännu. Be en utvecklare att publicera den.", + "developerHint": "Andra användare ser inte detta ännu.", + "manage": "Hantera på sidan Funktioner", + "tag": "Förhandsvisning: syns bara för administratörer" + }, "head": { "description": "Prodeko händelseregistrering", "title": "Prodeko event registrering" @@ -52,6 +58,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/events.json b/@app/client/src/translations/se/events.json index d30ac729a..34a3007ab 100644 --- a/@app/client/src/translations/se/events.json +++ b/@app/client/src/translations/se/events.json @@ -1,5 +1,5 @@ { - "addOpenQuota": "Lägg till öppen kvot", + "addOpenQuota": "Lägg till överflödskvot", "addOption": "Lägg till alternativ", "addQuestion": "Lägg till fråga", "addQuota": "Lägg till kvot", @@ -11,15 +11,17 @@ "eventCategoryCreationFailed": "Det gick inte att skapa händelsekategori", "eventCreateFailed": "Det gick inte att skapa händelse", "eventUpdateFailed": "Uppdateringen misslyckades", - "formTabErrors": "Andra fel", - "mustProvideEventQuota": "Måste tillhandahålla minst en kvot för evenemanget" + "mustProvideEventQuota": "Evenemanget måste ha minst en kvot. Enbart en överflödskvot räcker inte." }, "eventName": "Händelse", "eventNotFound": "Händelse hittades inte", "eventSignupNotOpen": "Händelseregistreringen är inte öppen", "forms": { "eventTime": "Händelsetid", + "fillRequiredToSave": "Fyll i alla obligatoriska fält för att spara", "highlightEvent": "Markerad händelse", + "highlightText": "Markeringstext", + "highlightTextHelp": "Lämna tomt för att visa standardtexten \"Kolla in det här!\".", "isDraft": "Utkast", "isHighlighted": "Markerad", "isNotDraft": "Publicerad", @@ -74,17 +76,45 @@ "saveAsDraft": "Spara som utkast", "signupEmail": "E-post för eventregistrering" }, + "free": "Gratis", "headerImage": "Händelsehuvudbild", "languages": "Språk", "numRegistrations": "Registrerade personer", - "openQuota": "Öppen kvot", + "openQuota": "Överflödskvot", "organizer": "Arrangör", + "overflowQuotaInfo": "Överflödskvoten delas av alla kvoter: när en deltagares egen kvot är full får hen en plats i överflödskvoten om det finns plats. Därefter hamnar deltagarna i kön.", + "paymentMethods": "Betalas med kort, Apple Pay eller Google Pay.", + "prefill": { + "DIETARY_RESTRICTIONS": "Specialdieter", + "TELEGRAM": "Telegram", + "placeholder": "Förifylls från (valfritt)" + }, + "previewInfo": "Så här ser anmälningsformuläret ut för deltagarna. Du kan prova formuläret, men inget skickas från förhandsvisningen.", + "questionsAutomaticallyCollected": "Förnamn, efternamn och e-post samlas in automatiskt av alla som anmäler sig, så du behöver inte lägga till dem som frågor.", "queued": "Kö", "quota": "Kvota", "removeOption": "Ta bort alternativ", "removeQuestion": "Ta bort fråga", "removeQuota": "Ta bort kvot", "spots": "spots", + "templates": { + "questions": { + "confirmRemove": "Frågor som skapats av evenemangsmallen tas bort, även om du har redigerat dem. Fortsätta?", + "label": "Evenemangsmall", + "none": "Ingen evenemangsmall", + "presets": "Färdiga frågor", + "sitsit": "Sittning" + }, + "quotas": { + "confirmRemove": "Kvoter som skapats av kvotmallen tas bort, även om du har redigerat dem. Fortsätta?", + "label": "Kvotmall", + "none": "Ingen kvotmall", + "openQuotaHint": "För en kvot som vem som helst kan anmäla sig till, lägg till kvoten ”Öppen kvot”.", + "presets": "Lägg till enskilda kvoter", + "yearGroups": "Kvoter för alla årskurser", + "yearGroupsNote": "Kom ihåg att ange en storlek för varje kvot." + } + }, "timer": { "instructions": "Sidan uppdateras automatiskt när registreringen öppnas. Uppdatera inte sidan.", "registrationStarts": "Öppnar", diff --git a/@app/client/src/translations/se/payments.json b/@app/client/src/translations/se/payments.json new file mode 100644 index 000000000..4da476b5c --- /dev/null +++ b/@app/client/src/translations/se/payments.json @@ -0,0 +1,63 @@ +{ + "cancel": { + "noRefundNote": "Din betalning återbetalas inte automatiskt. Kontakta arrangörerna om återbetalning." + }, + "cancelledNotice": "Betalningen slutfördes inte. Din plats är fortfarande reserverad, och du kan försöka igen nedan eller senare via ditt bekräftelsemejl.", + "confirmTimeoutNotice": "Vi har inte fått någon bekräftelse på din betalning ännu. Om du betalade får du snart ett bekräftelsemejl. Du kan också ladda om sidan senare.", + "confirmingNotice": "Vi bekräftar din betalning med Stripe. Sidan uppdateras automatiskt om några sekunder.", + "disabled": { + "body": "Onlinebetalningar är inte tillgängliga just nu. Kontakta arrangörerna om du har frågor om betalningen.", + "title": "Betalningar är inte tillgängliga" + }, + "editRegistration": "Ändra eller avboka din anmälan", + "errors": { + "checkoutFailed": "Det gick inte att öppna betalningssidan" + }, + "event": "Evenemang", + "name": "Namn", + "notFound": { + "body": "Kontrollera betalningslänken i ditt mejl.", + "title": "Anmälan hittades inte" + }, + "paidBanner": "Betalat {{amount}} {{date}}", + "pay": "Betala {{total}}", + "payNow": "Betala nu", + "quota": "Kvot", + "serviceFee": "Serviceavgift", + "states": { + "free": { + "body": "Din kvot är gratis. Allt är klart.", + "title": "Ingen betalning behövs" + }, + "opensLater": { + "body": "Betalningen öppnar när anmälan stänger {{date}} kl. {{time}}. Betalningslänken mejlas till dig.", + "title": "Betalningen öppnar senare" + }, + "paid": { + "body": "Du betalade {{amount}} {{date}} kl. {{time}}. En bekräftelse har skickats till din e-post.", + "detail": "Stripe mejlar dig också sitt eget kvitto.", + "title": "Betalning mottagen" + }, + "paidManually": { + "body": "Arrangörerna har markerat din anmälan som betald.", + "title": "Betalning mottagen" + }, + "queued": { + "body": "Du är nummer {{position}} i kön. Du betalar bara om du får en plats, och då mejlar vi dig en betalningslänk.", + "title": "Du står i kön" + } + }, + "tags": { + "free": "Gratis", + "inQueue": "I kön", + "notOpen": "Inte öppen än", + "paid": "Betald", + "processing": "Behandlas", + "unpaid": "Obetald" + }, + "ticket": "Biljett", + "time": "Tid", + "title": "Betalning", + "total": "Totalt", + "unpaidBanner": "Din anmälan har inte betalats ännu." +} diff --git a/@app/client/src/translations/se/register_event.json b/@app/client/src/translations/se/register_event.json index f003ddc37..1f8317fc9 100644 --- a/@app/client/src/translations/se/register_event.json +++ b/@app/client/src/translations/se/register_event.json @@ -1,26 +1,41 @@ { + "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?", "deleteRegistrationFailed": "Det gick inte att ta bort händelseregistreringen", "errors": { "registrationFailed": "Registrering till evenemanget misslyckades", - "registrationUpdateFailed": "Det gick inte att uppdatera registreringsinformationen" + "registrationUpdateFailed": "Det gick inte att uppdatera registreringsinformationen", + "rememberAnswersFailed": "Din anmälan sparades, men det gick inte att komma ihåg dina svar" }, "eventSignupComplete": "Händelseregistrering sparad", "forms": { "email": "E-post", "firstName": "Förnamn", "lastName": "Efternamn", + "rememberAnswers": "Kom ihåg dessa svar till mina följande anmälningar", "rules": { "emailEmpty": "Ange din e-post", "emailValid": "Inmatningen är inte giltig e-post", - "nameContainsSpace": "Namnet kan inte innehålla mellanslag", "provideAnswer": "Snälla svara på frågan", "provideFirstName": "Ange ditt förnamn", "provideLastName": "Ange ditt efternamn" } }, + "payment": { + "info": "Biljett {{price}} + {{fee}} serviceavgift. Du betalar inte nu. Vi mejlar dig en betalningslänk när anmälan stänger {{date}} kl. {{time}}.", + "register": "Anmäl dig", + "title": "Betalning" + }, + "previewNotSubmitted": "Förhandsvisning: ingen anmälan skickades", "recentlyRegisteredHeader": "Nyligen registrerad:", "recentlyRegisteredListItem": "nyligen registrerad till kvoten", "registrationDeleteComplete": "Raderad registrering", @@ -30,6 +45,7 @@ }, "title": "Registrera dig till event:", "updateRegistration": { + "closed": "Registreringen till detta evenemang har stängt, så din registrering kan inte längre ändras. Kontakta evenemangets arrangörer.", "title": "Uppdatera information om händelseregistrering" }, "you": "du!" diff --git a/@app/client/src/translations/se/reminders.json b/@app/client/src/translations/se/reminders.json new file mode 100644 index 000000000..0580107c3 --- /dev/null +++ b/@app/client/src/translations/se/reminders.json @@ -0,0 +1,71 @@ +{ + "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", + "offNotice": "Påminnelser används inte just nu. Du kan ändå ta bort dina påminnelser och koppla från Telegram.", + "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..914b0892c 100644 --- a/@app/client/src/translations/se/settings.json +++ b/@app/client/src/translations/se/settings.json @@ -2,16 +2,20 @@ "buttons": { "addEmail": "Lägg till e-post", "changePassphrase": "Ändra lösenfras", + "deleteRegistrationProfile": "Radera anmälningsuppgifter", "permanentDelete": "RADERA MITT KONTO PERMANENT", "resetPassphrase": "Återställ lösenfras", "returnHome": "Återgå till hemsidan", "updateProfile": "Uppdatera profil", + "updateRegistrationProfile": "Uppdatera anmälningsuppgifter", "wantToDeleteAccount": "Jag vill ta bort mitt konto" }, "errors": { "accountDeleteFailedOrgOwner1": "Du kan inte ta bort ditt konto medan du är ägare till en organisation.", "accountDeleteFailedOrgOwner2": "För varje organisation du är ägare till, tilldela antingen ditt ägande till en annan användare eller ta bort organisationen för att fortsätta.", "deleteFailed": "Begäran om borttagning misslyckades", + "errorDeletingRegistrationProfile": "Det gick inte att radera anmälningsuppgifterna", + "errorUpdatingRegistrationProfile": "Det gick inte att uppdatera anmälningsuppgifterna", "errorUpdatingUsername": "Fel vid uppdatering av användarnamn", "incorrectOldPassword": "Felaktig gammal lösenordsfras", "usernameTaken": "Detta användarnamn används redan, välj ett annat namn" @@ -22,18 +26,24 @@ "emailAddFailed": "Fel vid tillägg av e-post", "passwordChangeFailed": "Det gick inte att ändra lösenordsfras", "passwordChanged": "Lösenordet ändrat!", - "profileUpdated": "Profil uppdaterad" + "profileUpdated": "Profil uppdaterad", + "registrationProfileDeleted": "Anmälningsuppgifterna har raderats", + "registrationProfileUpdated": "Anmälningsuppgifterna har uppdaterats" }, "label": { + "dietaryRestrictions": "Specialdieter", "newEmail": "Ny e-post", "newPassphrase": "Ny lösenordsfras", - "oldPassphrase": "Gammal lösenfras" + "oldPassphrase": "Gammal lösenfras", + "telegram": "Telegram" }, "messages": { + "dietaryRestrictionsTooLong": "Specialdieter får vara högst 1000 tecken", "email": "Ange en e-postadress", "name": "Ange ditt namn", "newPassword": "Bekräfta din lösenfras", "oldPassword": "Ange din lösenfras", + "telegramTooLong": "Telegram får vara högst 64 tecken", "username": "Välj ett användarnamn" } }, @@ -84,11 +94,18 @@ "socialLoginNoPassword": "Du registrerade ditt konto genom social inloggning, så du har för närvarande ingen lösenfras. Om du vill ha en lösenfras, tryck på knappen nedan för att begära ett e-postmeddelande för återställning av lösenfras till '{{email}}' (du kan välj en annan e-postadress genom att göra den till primär i)" } }, + "registrationProfile": { + "deleteConfirm": "Radera dina sparade anmälningsuppgifter?", + "description": "Dessa uppgifter fyller i Telegram- och specialdietfrågorna i anmälningsformulär. Endast du kan se dem. De sparas här, eller när du kryssar i \"Kom ihåg dessa svar\" vid anmälan.", + "offDescription": "Förifyllning av anmälningssvar är för tillfället avstängd. Du kan fortfarande radera de anmälningsuppgifter du har sparat." + }, "titles": { "accounts": "Länkade konton", "delete": "Radera konto", "emails": "E-postadresser", "index": "Redigera profil", + "registrationProfile": "Anmälningsuppgifter", + "reminders": "Mina påminnelser", "security": "Ändra lösenfras" } } diff --git a/@app/components/__tests__/EventForm/eventTemplates.test.ts b/@app/components/__tests__/EventForm/eventTemplates.test.ts new file mode 100644 index 000000000..3c3b4e3f5 --- /dev/null +++ b/@app/components/__tests__/EventForm/eventTemplates.test.ts @@ -0,0 +1,138 @@ +import dayjs from "dayjs" + +import { + buildPresetQuestions, + buildPresetQuota, + buildTemplateQuestions, + buildTemplateQuotas, + hasTemplateItems, + presetKeysOf, + replaceTemplateItems, + TemplateItem, + togglePresets, + withoutHandPickedPresets, +} from "../../src/EventForm/eventTemplates" +import { toEventInput } from "../../src/EventForm/values" + +const languages = ["fi", "en"] + +describe("template builders", () => { + it("builds a quota per year group, without sizes, in the event's languages", () => { + const quotas = buildTemplateQuotas("yearGroups", ["fi"]) + expect(quotas.map((q) => q.title)).toEqual( + ["I", "II", "III", "IV", "N"].map((fi) => ({ fi })) + ) + expect(quotas.every((q) => q.templateKey === "yearGroups")).toBe(true) + expect(quotas.some((q) => "size" in q)).toBe(false) + }) + + it("builds the questions of all of a template's presets", () => { + const questions = buildTemplateQuestions("sitsit", languages) + expect(presetKeysOf(questions)).toEqual([ + "telegram", + "alcohol", + "specialDiets", + "seating", + "bindingRegistration", + ]) + // specialDiets adds two questions + expect(questions).toHaveLength(6) + expect(questions[1]).toEqual({ + type: "RADIO", + isRequired: true, + label: { fi: "Alkoholivalinta", en: "Alcohol preference" }, + data: [ + { fi: "Holiton", en: "Non-alcoholic" }, + { fi: "Holillinen", en: "Alcoholic" }, + { fi: "Holittomat shotit", en: "Non-alcoholic shots" }, + ], + presetKey: "alcohol", + templateKey: "sitsit", + }) + }) + + it("falls back to English for a language the presets have no text in", () => { + const [question] = buildPresetQuestions("seating", ["SE"]) + expect(question.label).toEqual({ se: "Seating preferences" }) + expect(question.data).toBeNull() + }) + + it("returns nothing for an unknown template", () => { + expect(buildTemplateQuotas("nope", languages)).toEqual([]) + expect(buildTemplateQuestions("nope", languages)).toEqual([]) + }) +}) + +describe("list helpers", () => { + // An item added by hand + const own: TemplateItem & { title: Record } = { + title: { fi: "Oma" }, + } + const ticked = buildPresetQuota("open", ["fi"]) + const fromTemplate = buildTemplateQuotas("yearGroups", ["fi"]) + + it("adds newly ticked presets and removes unticked ones, keeping own items", () => { + const items = [own, ticked] + const next = togglePresets(items, ["I"], (key) => [ + buildPresetQuota(key, ["fi"]), + ]) + expect(next).toEqual([own, { title: { fi: "I" }, presetKey: "I" }]) + }) + + it("does not add a ticked preset twice", () => { + const build = jest.fn((key: string) => [buildPresetQuota(key, ["fi"])]) + expect(togglePresets([own, ticked], ["open"], build)).toEqual([own, ticked]) + expect(build).not.toHaveBeenCalled() + }) + + it("leaves hand-ticked presets out of a template", () => { + const handTicked = buildPresetQuota("I", ["fi"]) + const built = withoutHandPickedPresets([own, handTicked], fromTemplate) + expect(presetKeysOf(built)).toEqual(["II", "III", "IV", "N"]) + }) + + it("replaces the previous template's items and keeps the rest", () => { + const items = [own, ticked, ...fromTemplate] + expect(hasTemplateItems(items)).toBe(true) + expect(replaceTemplateItems(items, [])).toEqual([own, ticked]) + expect(hasTemplateItems([own, ticked, undefined])).toBe(false) + }) +}) + +describe("a form filled from templates", () => { + it("submits ordinary quotas and questions", () => { + const quotas = buildTemplateQuotas("yearGroups", languages).map((q) => ({ + ...q, + size: 10, + })) + const questions = buildTemplateQuestions("sitsit", languages) + const { quotas: quotaInput, questions: questionInput } = toEventInput({ + name: { fi: "Sitsit" }, + eventTime: [dayjs("2030-05-01T15:00:00Z"), dayjs("2030-05-01T22:00:00Z")], + registrationTime: [ + dayjs("2030-04-01T09:00:00Z"), + dayjs("2030-04-20T20:59:59Z"), + ], + quotas, + questions, + } as any) + + expect(quotaInput[0]).toEqual({ + position: 0, + title: { fi: "I", en: "I" }, + size: 10, + }) + expect(questionInput?.[0]).toEqual({ + position: 0, + type: "TEXT", + label: { fi: "Telegram", en: "Telegram" }, + isRequired: true, + data: null, + prefill: "NONE", + }) + for (const item of [...quotaInput, ...(questionInput ?? [])]) { + expect(item).not.toHaveProperty("presetKey") + expect(item).not.toHaveProperty("templateKey") + } + }) +}) diff --git a/@app/components/__tests__/EventForm/timeRange.test.ts b/@app/components/__tests__/EventForm/timeRange.test.ts new file mode 100644 index 000000000..a0e0d57e8 --- /dev/null +++ b/@app/components/__tests__/EventForm/timeRange.test.ts @@ -0,0 +1,26 @@ +import dayjs from "dayjs" + +import { dayClickRange } from "../../src/EventForm/timeRange" + +const format = "YYYY-MM-DD HH:mm:ss.SSS" + +describe("dayClickRange", () => { + const day = dayjs("2030-05-01T08:15:30.250") + + it("fills a single day from noon to the end of the day", () => { + const [start, end] = dayClickRange(day, 0) + expect(start.format(format)).toBe("2030-05-01 12:00:00.000") + expect(end.format(format)).toBe("2030-05-01 23:59:59.000") + }) + + it("ends the range the given number of days later", () => { + const [start, end] = dayClickRange(day, 7) + expect(start.format(format)).toBe("2030-05-01 12:00:00.000") + expect(end.format(format)).toBe("2030-05-08 23:59:59.000") + }) + + it("crosses a month end", () => { + const [, end] = dayClickRange(dayjs("2030-04-28T00:00:00"), 7) + expect(end.format(format)).toBe("2030-05-05 23:59:59.000") + }) +}) diff --git a/@app/components/__tests__/EventForm/values.test.ts b/@app/components/__tests__/EventForm/values.test.ts new file mode 100644 index 000000000..6fce0eac4 --- /dev/null +++ b/@app/components/__tests__/EventForm/values.test.ts @@ -0,0 +1,319 @@ +import dayjs from "dayjs" + +import { toEventInput, toFormValues } from "../../src/EventForm/values" + +import type { UpdateEventPageQuery } from "@app/graphql" + +const event = { + __typename: "Event", + id: "event-1", + name: { fi: "Vuosijuhla", en: "Annual gala" }, + slug: "2030-5-1-vuosijuhla", + description: { fi: [], en: [] }, + location: "Otaniemi", + eventStartTime: "2030-05-01T15:00:00.000Z", + eventEndTime: "2030-05-01T22:00:00.000Z", + registrationStartTime: "2030-04-01T09:00:00.000Z", + registrationEndTime: "2030-04-20T20:59:59.000Z", + isHighlighted: true, + highlightText: { fi: "Pian täynnä", en: "Filling up" }, + isDraft: false, + headerImageFile: "https://example.com/header.png", + openQuotaSize: 5, + createdAt: "2030-01-01T00:00:00.000Z", + category: { __typename: "EventCategory", id: "category-1", name: {} }, + ownerOrganization: { __typename: "Organization", id: "org-1", name: "Org" }, + quotas: { + nodes: [ + { + __typename: "Quota", + id: "quota-1", + position: 0, + title: { fi: "Kiintiö", en: "Quota" }, + size: 10, + registrations: { totalCount: 2 }, + }, + ], + }, + eventQuestions: { + nodes: [ + { + __typename: "EventQuestion", + id: "question-1", + position: 0, + type: "TEXT", + label: { fi: "Kysymys", en: "Question" }, + isRequired: true, + data: null, + prefill: "TELEGRAM", + }, + ], + }, +} as unknown as UpdateEventPageQuery["event"] + +describe("toFormValues", () => { + it("maps an event to the update form's values", () => { + const values = toFormValues(event) + + expect(values.languages).toEqual(["fi", "en"]) + expect(values.ownerOrganizationId).toBe("org-1") + expect(values.categoryId).toBe("category-1") + expect(values.slug).toBe("2030-5-1-vuosijuhla") + expect(values.openQuotaSize).toBe(5) + expect(values.highlightText).toEqual({ + fi: "Pian täynnä", + en: "Filling up", + }) + expect(values.eventTime.map((d) => d.toISOString())).toEqual([ + "2030-05-01T15:00:00.000Z", + "2030-05-01T22:00:00.000Z", + ]) + expect(values.registrationTime.map((d) => d.toISOString())).toEqual([ + "2030-04-01T09:00:00.000Z", + "2030-04-20T20:59:59.000Z", + ]) + expect(values.quotas).toEqual([ + { + id: "quota-1", + position: 0, + title: { fi: "Kiintiö", en: "Quota" }, + size: 10, + registrations: { totalCount: 2 }, + }, + ]) + expect(values.questions).toEqual([ + { + id: "question-1", + position: 0, + type: "TEXT", + label: { fi: "Kysymys", en: "Question" }, + isRequired: true, + data: null, + prefill: "TELEGRAM", + }, + ]) + expect(values).not.toHaveProperty("id") + expect(values).not.toHaveProperty("createdAt") + }) + + it("edits quota prices in euros", () => { + const values = toFormValues({ + ...event, + quotas: { + nodes: [{ ...event!.quotas.nodes[0], priceCents: 1850 }], + }, + } as unknown as UpdateEventPageQuery["event"]) + + expect(values.quotas?.[0]).toMatchObject({ priceCents: 1850, price: 18.5 }) + }) + + it("gives empty values while the event is loading", () => { + const values = toFormValues(undefined) + + expect(values.languages).toEqual([]) + expect(values.quotas).toBeUndefined() + expect(values.questions).toBeUndefined() + }) +}) + +describe("toEventInput", () => { + const formValues = { + name: { fi: "Vuosijuhla", en: "Annual gala" }, + description: { fi: [], en: [] }, + location: "Otaniemi", + ownerOrganizationId: "org-1", + categoryId: "category-1", + isHighlighted: false, + isDraft: true, + languages: ["fi", "en"], + openQuotaSize: 0, + eventTime: [ + dayjs("2030-05-01T15:00:00.000Z"), + dayjs("2030-05-01T22:00:00.000Z"), + ], + registrationTime: [ + dayjs("2030-04-01T09:00:00.000Z"), + dayjs("2030-04-20T20:59:59.000Z"), + ], + quotas: [ + { id: "quota-2", position: 1, title: { fi: "B" }, size: 3 }, + { title: { fi: "A" }, size: 4, templateKey: "members" }, + ], + questions: [{ type: "TEXT", label: { fi: "Kysymys" }, data: null }], + } as any + + it("maps the form's values to the mutation input", () => { + expect(toEventInput(formValues)).toEqual({ + event: { + ownerOrganizationId: "org-1", + categoryId: "category-1", + name: { fi: "Vuosijuhla", en: "Annual gala" }, + description: { fi: [], en: [] }, + location: "Otaniemi", + isHighlighted: false, + isDraft: true, + slug: "2030-5-1-vuosijuhla", + highlightText: null, + eventStartTime: "2030-05-01T15:00:00.000Z", + eventEndTime: "2030-05-01T22:00:00.000Z", + registrationStartTime: "2030-04-01T09:00:00.000Z", + registrationEndTime: "2030-04-20T20:59:59.000Z", + headerImageFile: undefined, + openQuotaSize: 0, + }, + // Positions follow the list order and form-only keys are dropped + quotas: [ + { id: "quota-2", position: 0, title: { fi: "B" }, size: 3 }, + { position: 1, title: { fi: "A" }, size: 4 }, + ], + questions: [ + { + position: 0, + type: "TEXT", + label: { fi: "Kysymys" }, + isRequired: false, + data: null, + prefill: "NONE", + }, + ], + }) + }) + + it("does not change the form's values", () => { + const before = JSON.stringify(formValues) + toEventInput(formValues) + expect(JSON.stringify(formValues)).toBe(before) + }) + + it("uploads only a newly chosen header image", () => { + const file = { name: "header.png" } + expect( + toEventInput({ + ...formValues, + headerImageFile: { uid: "1", name: "header.png", originFileObj: file }, + }).event.headerImageFile + ).toBe(file) + expect( + toEventInput({ ...formValues, headerImageFile: "https://example.com/a" }) + .event.headerImageFile + ).toBeUndefined() + }) + + it("saves trimmed ribbon texts in the selected languages", () => { + expect( + toEventInput({ + ...formValues, + isHighlighted: true, + languages: ["fi"], + highlightText: { fi: " Pian täynnä ", en: "Filling up" }, + }).event.highlightText + ).toEqual({ fi: "Pian täynnä" }) + }) + + it("clears the ribbon text when it is empty or the event is not highlighted", () => { + expect( + toEventInput({ + ...formValues, + isHighlighted: true, + highlightText: { fi: " ", en: "" }, + }).event.highlightText + ).toBeNull() + expect( + toEventInput({ + ...formValues, + isHighlighted: false, + highlightText: { fi: "Pian täynnä" }, + }).event.highlightText + ).toBeNull() + }) + + describe("quota prices", () => { + const paidValues = { + ...formValues, + quotas: [ + { id: "quota-2", title: { fi: "B" }, size: 3, price: 18.5 }, + { title: { fi: "A" }, size: 4, price: null }, + { title: { fi: "C" }, size: 5 }, + ], + } as any + + it("leaves them out while payments are off", () => { + const input = toEventInput(paidValues) + + input.quotas.forEach((quota) => + expect(quota).not.toHaveProperty("priceCents") + ) + }) + + it("sends them in cents while payments are on", () => { + const input = toEventInput(paidValues, { payments: true }) + + // A cleared price is free; a quota without a price input keeps its + // stored price (or is free when new) + expect(input.quotas.map((q) => q.priceCents)).toEqual([ + 1850, + 0, + undefined, + ]) + expect(input.quotas[2]).not.toHaveProperty("priceCents") + }) + }) + + it("sends a question without a prefill as NONE, which clears it", () => { + const values = toFormValues(event) as any + const input = toEventInput({ + ...values, + questions: [ + { ...values.questions[0], prefill: null }, + { ...values.questions[0], id: undefined, prefill: undefined }, + ], + }) + expect(input.questions?.map((q) => q.prefill)).toEqual(["NONE", "NONE"]) + }) + + it("sends an empty quota list when the form has no quotas", () => { + expect(toEventInput({ ...formValues, quotas: undefined }).quotas).toEqual( + [] + ) + }) + + it("saves an unchanged event as it was loaded", () => { + const input = toEventInput(toFormValues(event) as any) + + expect(input.event).toMatchObject({ + ownerOrganizationId: "org-1", + categoryId: "category-1", + name: { fi: "Vuosijuhla", en: "Annual gala" }, + location: "Otaniemi", + isHighlighted: true, + highlightText: { fi: "Pian täynnä", en: "Filling up" }, + isDraft: false, + slug: "2030-5-1-vuosijuhla", + eventStartTime: "2030-05-01T15:00:00.000Z", + eventEndTime: "2030-05-01T22:00:00.000Z", + registrationStartTime: "2030-04-01T09:00:00.000Z", + registrationEndTime: "2030-04-20T20:59:59.000Z", + openQuotaSize: 5, + headerImageFile: undefined, + }) + expect(input.quotas).toEqual([ + { + id: "quota-1", + position: 0, + title: { fi: "Kiintiö", en: "Quota" }, + size: 10, + }, + ]) + expect(input.questions).toEqual([ + { + id: "question-1", + position: 0, + type: "TEXT", + label: { fi: "Kysymys", en: "Question" }, + isRequired: true, + data: null, + prefill: "TELEGRAM", + }, + ]) + }) +}) diff --git a/@app/components/__tests__/Feature.test.tsx b/@app/components/__tests__/Feature.test.tsx new file mode 100644 index 000000000..a45bf2a48 --- /dev/null +++ b/@app/components/__tests__/Feature.test.tsx @@ -0,0 +1,168 @@ +import { renderToStaticMarkup } from "react-dom/server" + +import { + Feature, + FeatureFlagsProvider, + isDeveloperUser, + useFeature, + useFeaturePreview, +} from "../src/Feature" + +import type { SharedLayout_QueryFragment } from "@app/graphql" +import type { FeatureKey } from "@app/lib" + +// The registry may be empty; these tests use keys of their own. +const ON = "test_on" as FeatureKey +const PREVIEW = "test_preview" as FeatureKey +const OFF = "test_off" as FeatureKey + +const layoutData = ({ + isAdmin = true, + isDeveloper = false, + enabled = [ON, PREVIEW], + preview = [PREVIEW], +}: { + isAdmin?: boolean + isDeveloper?: boolean + enabled?: (string | null)[] + preview?: (string | null)[] +} = {}) => + ({ + currentUser: { isAdmin, isDeveloper }, + enabledFeaturesList: enabled, + adminPreviewFeaturesList: preview, + }) as unknown as SharedLayout_QueryFragment + +const render = ( + data: SharedLayout_QueryFragment | undefined, + node: React.ReactNode +) => + renderToStaticMarkup( + {node} + ) + +const Probe = ({ name }: { name: FeatureKey }) => ( + + {String(useFeature(name))}/{String(useFeaturePreview(name))} + +) + +describe("useFeature and useFeaturePreview", () => { + it("read every feature as off while the layout query is loading", () => { + expect(render(undefined, )).toBe( + "false/false" + ) + }) + + it("read every feature as off without a provider", () => { + expect(renderToStaticMarkup()).toBe( + "false/false" + ) + }) + + it("read a listed key as on and an unlisted key as off", () => { + const data = layoutData() + expect(render(data, )).toBe("true/false") + expect(render(data, )).toBe("false/false") + }) + + it("report a preview only for a key that is also enabled", () => { + expect(render(layoutData(), )).toBe( + "true/true" + ) + expect( + render( + layoutData({ enabled: [ON], preview: [PREVIEW] }), + + ) + ).toBe("false/false") + }) +}) + +describe("Feature", () => { + it("renders the fallback while the feature is off or loading", () => { + const node = ( + old} name={OFF}> + new + + ) + expect(render(layoutData(), node)).toBe("old") + expect(render(undefined, node)).toBe("old") + }) + + it("renders nothing by default while the feature is off", () => { + expect( + render( + layoutData(), + + new + + ) + ).toBe("") + }) + + it("renders its children while the feature is on, without a tag", () => { + expect( + render( + layoutData(), + + new + + ) + ).toBe("new") + }) + + it("passes the preview state to a render function", () => { + const node = (name: FeatureKey) => ( + + {({ preview }) => {preview ? "preview" : "released"}} + + ) + expect(render(layoutData(), node(ON))).toBe("released") + expect(render(layoutData(), node(PREVIEW))).toBe("preview") + }) + + it("renders the preview tag only when asked and only for a preview", () => { + const withTag = render( + layoutData(), + + new + + ) + expect(withTag).toContain('data-cy="preview-tag"') + expect(withTag).toContain("new") + + const withoutTag = render( + layoutData(), + + new + + ) + expect(withoutTag).not.toContain("preview-tag") + }) + + it("links developers to the Features page from the preview tag", () => { + const node = ( + + new + + ) + const developer = render(layoutData({ isDeveloper: true }), node) + expect(developer).toContain('href="/admin/features"') + expect(developer).toContain("featurePreview.developerHint") + + const admin = render(layoutData({ isDeveloper: false }), node) + expect(admin).not.toContain("/admin/features") + expect(admin).toContain("featurePreview.adminHint") + }) +}) + +describe("isDeveloperUser", () => { + it("needs both the admin and the developer flag", () => { + expect(isDeveloperUser({ isAdmin: true, isDeveloper: true })).toBe(true) + expect(isDeveloperUser({ isAdmin: false, isDeveloper: true })).toBe(false) + expect(isDeveloperUser({ isAdmin: true, isDeveloper: false })).toBe(false) + expect(isDeveloperUser(null)).toBe(false) + expect(isDeveloperUser(undefined)).toBe(false) + }) +}) diff --git a/@app/components/__tests__/clientGates.test.tsx b/@app/components/__tests__/clientGates.test.tsx new file mode 100644 index 000000000..2477758c0 --- /dev/null +++ b/@app/components/__tests__/clientGates.test.tsx @@ -0,0 +1,181 @@ +import { renderToStaticMarkup } from "react-dom/server" +import I18nProvider from "next-translate/I18nProvider" +import { Client, fetchExchange, Provider } from "urql" + +import { useCelebrate } from "../src/celebrate" +import { EventCard } from "../src/EventCard" +import { EventForm } from "../src/EventForm" +import { featureEnabledIn, FeatureFlagsProvider } from "../src/Feature" + +import type { Event, SharedLayout_QueryFragment } from "@app/graphql" +import type { FeatureKey } from "@app/lib" + +/* + * The components below render on the server (renderToStaticMarkup). These + * mocks stand in for what a node test cannot load: ESM-only packages, image + * imports, the Next router and the drag and drop backend. + */ +jest.mock("next/router", () => ({ + useRouter: () => ({ push: jest.fn(), query: {}, pathname: "/", asPath: "/" }), +})) +jest.mock("next/image", () => ({ + __esModule: true, + default: ({ alt }: { alt: string }) => + require("react").createElement("img", { alt }), +})) +jest.mock("../assets/header-logo.png", () => "header-logo.png") +jest.mock("antd-img-crop", () => ({ + __esModule: true, + default: ({ children }: { children: unknown }) => children, +})) +jest.mock("@ant-design/icons/es/index", () => require("@ant-design/icons")) +jest.mock("react-dnd", () => ({ + DndProvider: ({ children }: { children: unknown }) => children, + useDrag: () => [{}, () => {}, () => {}], + useDrop: () => [{}, () => {}], +})) +jest.mock("react-dnd-html5-backend", () => ({ HTML5Backend: {} })) +// The typed picker and the scroll column picker render the same input until +// the calendar opens, so the typed one leaves a marker +jest.mock("../src/EventForm/TimeRangePicker", () => ({ + ...jest.requireActual("../src/EventForm/TimeRangePicker"), + TimeRangePicker: () => + require("react").createElement("span", { "data-cy": "typed-time-picker" }), +})) + +const layoutData = (enabled: string[]) => + ({ + currentUser: { isAdmin: false, isDeveloper: false }, + enabledFeaturesList: enabled, + adminPreviewFeaturesList: [], + }) as unknown as SharedLayout_QueryFragment + +describe("featureEnabledIn", () => { + it("reads a feature as off while the query is loading", () => { + expect(featureEnabledIn(undefined, "registration_reminders")).toBe(false) + expect(featureEnabledIn(null, "registration_reminders")).toBe(false) + }) + + it("reads a feature as on only when the server lists it", () => { + const data = layoutData(["registration_reminders"]) + expect(featureEnabledIn(data, "registration_reminders")).toBe(true) + expect(featureEnabledIn(data, "telegram_reminders")).toBe(false) + }) +}) + +describe("useCelebrate", () => { + const Probe = () => {useCelebrate().name} + + it("does nothing while confetti is off", () => { + expect( + renderToStaticMarkup( + + + + ) + ).toBe("noCelebration") + }) + + it("shoots confetti while confetti is on", () => { + expect( + renderToStaticMarkup( + + + + ) + ).toBe("celebrate") + }) +}) + +describe("event form", () => { + const client = new Client({ + url: "http://localhost/graphql", + exchanges: [fetchExchange], + }) + // Page query data: the shared layout fragment and the form's own fields + const pageData = (enabled: string[]) => + ({ + ...layoutData(enabled), + languages: ["FI", "EN"], + organizations: { nodes: [] }, + eventCategories: { nodes: [] }, + }) as any + + const renderForm = (enabled: string[] | undefined) => + renderToStaticMarkup( + + + + + + ) + + // What each client-only flag adds to the form + const gates: Array<[FeatureKey, string]> = [ + ["typed_time_input", 'data-cy="typed-time-picker"'], + ["event_templates", 'data-cy="eventform-quotas-template"'], + ["form_preview", "admin:events.tabs.preview"], + ] + + beforeAll(() => { + // antd warns about Input.Group, which the form still uses + jest.spyOn(console, "error").mockImplementation(() => {}) + }) + + it("waits for the flags before rendering", () => { + const html = renderForm(undefined) + expect(html).toContain("ant-skeleton") + expect(html).not.toContain("eventform-") + }) + + it("renders without the gated parts while their flags are off", () => { + const html = renderForm([]) + expect(html).toContain('data-cy="eventform-input-event-time"') + for (const [, marker] of gates) { + expect(html).not.toContain(marker) + } + }) + + it.each(gates)("adds the part of %s while it is on", (key, marker) => { + expect(renderForm([key])).toContain(marker) + }) +}) + +describe("event card ribbon", () => { + const event = { + slug: "vuosijuhla", + name: { fi: "Vuosijuhla" }, + location: "Otaniemi", + registrationStartTime: "2030-04-01T09:00:00.000Z", + registrationEndTime: "2030-04-20T20:59:59.000Z", + headerImageFile: null, + signupOpen: true, + isHighlighted: true, + highlightText: { fi: "Pian täynnä" }, + quotas: { nodes: [] }, + registrations: { totalCount: 0 }, + } as unknown as Event + + const renderCard = (enabled: string[]) => + renderToStaticMarkup( + + + + + + ) + + it("shows the default ribbon text while ribbon_text is off", () => { + const html = renderCard([]) + expect(html).toContain('highlightText') + expect(html).not.toContain("Pian täynnä") + }) + + it("shows the event's ribbon text while ribbon_text is on", () => { + expect(renderCard(["ribbon_text"])).toContain("Pian täynnä") + }) +}) diff --git a/@app/components/__tests__/featureFlagTransitions.test.ts b/@app/components/__tests__/featureFlagTransitions.test.ts new file mode 100644 index 000000000..ba82d90df --- /dev/null +++ b/@app/components/__tests__/featureFlagTransitions.test.ts @@ -0,0 +1,144 @@ +import { FeatureState } from "@app/graphql" + +import { + eventsOf, + FeatureFlagEvent, + previewInfo, + stateSelectable, + transition, +} from "../src/FeatureFlags/transitions" + +const { Off, AdminsOnly, On } = FeatureState + +const event = ( + key: string, + oldState: FeatureState, + newState: FeatureState, + id: string +): FeatureFlagEvent => ({ + id, + key, + oldState, + newState, + actorId: null, + actorName: "Dev", + actorUsername: "dev", + createdAt: "2026-11-01T10:00:00Z", +}) + +describe("transition", () => { + it("saves Off <-> Admins only at once", () => { + expect(transition(Off, AdminsOnly)).toBe("immediate") + expect(transition(AdminsOnly, Off)).toBe("immediate") + }) + + it("confirms every change into On", () => { + expect(transition(Off, On)).toBe("confirmOn") + expect(transition(AdminsOnly, On)).toBe("confirmOn") + }) + + it("confirms every change out of On", () => { + expect(transition(On, Off)).toBe("confirmLeaveOn") + expect(transition(On, AdminsOnly)).toBe("confirmLeaveOn") + }) + + it("does nothing when the state stays", () => { + for (const state of [Off, AdminsOnly, On]) { + expect(transition(state, state)).toBe("none") + } + }) +}) + +describe("previewInfo", () => { + it("is not previewed when the audit log never had admins_only", () => { + const events = eventsOf( + [event("a", Off, On, "1"), event("b", Off, AdminsOnly, "2")], + "a" + ) + expect(previewInfo({ key: "a", state: Off }, events)).toEqual({ + previewable: true, + previewed: false, + lastPreviewStart: null, + }) + }) + + it("returns the most recent switch into admins_only", () => { + // Newest first, as the API returns them. + const events = [ + event("a", AdminsOnly, Off, "3"), + event("a", Off, AdminsOnly, "2"), + event("a", Off, AdminsOnly, "1"), + ] + const info = previewInfo({ key: "a", state: Off }, events) + expect(info.previewed).toBe(true) + expect(info.lastPreviewStart?.id).toBe("2") + }) + + it("counts the current admins_only state as a preview", () => { + expect(previewInfo({ key: "a", state: AdminsOnly }, [])).toEqual({ + previewable: true, + previewed: true, + lastPreviewStart: null, + }) + }) + + it("is not previewable for a feature admins cannot preview", () => { + expect(previewInfo({ key: "mcp_server", state: Off }, []).previewable).toBe( + false + ) + }) +}) + +describe("eventsOf", () => { + it("keeps one flag's events in order and skips nulls", () => { + const events = [ + event("a", Off, On, "1"), + null, + event("b", Off, On, "2"), + event("a", On, Off, "3"), + ] + expect(eventsOf(events, "a").map((e) => e.id)).toEqual(["1", "3"]) + }) +}) + +describe("stateSelectable", () => { + it("allows every state for an available flag", () => { + const flag = { key: "a", available: true, retiredAt: null } + expect([Off, AdminsOnly, On].map((s) => stateSelectable(flag, s))).toEqual([ + true, + true, + true, + ]) + }) + + it("allows only Off for an unavailable flag", () => { + const flag = { key: "a", available: false, retiredAt: null } + expect([Off, AdminsOnly, On].map((s) => stateSelectable(flag, s))).toEqual([ + true, + false, + false, + ]) + }) + + it("does not offer Admins only for a feature admins cannot preview", () => { + const flag = { key: "mcp_server", available: true, retiredAt: null } + expect([Off, AdminsOnly, On].map((s) => stateSelectable(flag, s))).toEqual([ + true, + false, + true, + ]) + }) + + it("allows nothing for a retired flag", () => { + const flag = { + key: "a", + available: true, + retiredAt: "2026-11-01T10:00:00Z", + } + expect([Off, AdminsOnly, On].map((s) => stateSelectable(flag, s))).toEqual([ + false, + false, + false, + ]) + }) +}) diff --git a/@app/components/jest.config.ts b/@app/components/jest.config.ts new file mode 100644 index 000000000..bc706af0a --- /dev/null +++ b/@app/components/jest.config.ts @@ -0,0 +1,10 @@ +const base = require("../../jest.config.base")(__dirname) + +module.exports = { + ...base, + transform: { + ...base.transform, + // The shared test tsconfig has no JSX setting; components need one. + "^.+\\.tsx?$": ["ts-jest", { tsconfig: "/tsconfig.test.json" }], + }, +} diff --git a/@app/components/package.json b/@app/components/package.json index 808921ce3..059aeb4cf 100644 --- a/@app/components/package.json +++ b/@app/components/package.json @@ -19,6 +19,7 @@ "@hacknug/react-icons": "^4.2.1", "antd": "^5.22.5", "antd-img-crop": "^4.21.0", + "canvas-confetti": "^1.9.4", "dayjs": "^1.11.4", "escape-html": "^1.0.3", "is-hotkey": "^0.2.0", @@ -44,6 +45,7 @@ "urql": "^4.2.2" }, "devDependencies": { + "@types/canvas-confetti": "^1.9.0", "@types/nprogress": "^0.2.0", "@types/react-dom": "^18.0.6", "type-fest": "^2.18.0" diff --git a/@app/components/src/AdminLayout.tsx b/@app/components/src/AdminLayout.tsx index 38feed41d..0e0f75351 100644 --- a/@app/components/src/AdminLayout.tsx +++ b/@app/components/src/AdminLayout.tsx @@ -1,6 +1,6 @@ import qs from "querystring" -import { PlusCircleTwoTone } from "@ant-design/icons" +import { ControlOutlined, PlusCircleTwoTone } from "@ant-design/icons" import { css } from "@emotion/css" import { AiOutlineMail, AiOutlineTag } from "@hacknug/react-icons/ai" import { FiUsers } from "@hacknug/react-icons/fi" @@ -11,6 +11,7 @@ import { useRouter } from "next/router" import { UseQueryState } from "urql" import { AdminSideMenu, MenuItem } from "./AdminSideMenu" +import { isDeveloperUser } from "./Feature" import { Redirect } from "./Redirect" import { AuthRestrict, @@ -42,24 +43,39 @@ interface AdminLayoutProps { query: UseQueryState href: string children: React.ReactNode + /** Defaults to AuthRestrict.NOT_ADMIN; may only add restrictions. */ + forbidWhen?: AuthRestrict } export const AdminLayout: React.FC = ({ query, href: inHref, children, + forbidWhen = AuthRestrict.NOT_ADMIN, }) => { const router = useRouter() const { t } = useTranslation("admin") const { data, fetching } = query - const basicMenuItems = [ + const basicMenuItems: MenuItem[] = [ { key: "/admin/emails", title: t("sider.titles.emails"), icon: , target: "/admin/emails", }, + // Only developers can open the page; other admins do not see the entry. + ...(isDeveloperUser(data?.currentUser) + ? [ + { + key: "/admin/features", + title: t("sider.titles.features"), + icon: , + target: "/admin/features", + cy: "admin-sider-features", + }, + ] + : []), ] // Every organization, not just the ones the user is a member of: this menu @@ -165,6 +181,9 @@ export const AdminLayout: React.FC = ({ } `} collapsedWidth={40} + // Wide enough for the longest menu label ("Evenemangskategorier") + // next to its icon and submenu arrow; antd's default is 200 + width={240} > @@ -173,7 +192,7 @@ export const AdminLayout: React.FC = ({ return ( = ({ ] // See https://github.com/ianstormtaylor/slate/pull/4540#issuecomment-951380551 - editor.children = newValue + if (editor.children !== newValue) { + editor.children = newValue + // The document was replaced from outside the editor (language switch or + // form reset); drop the cursor, pending marks and undo history that + // point into the previous one. Edits made in the editor come back as the + // same array, so typing doesn't reset anything. + editor.selection = null + editor.marks = null + editor.history = { undos: [], redos: [] } + } useEffect(() => { const textValue = newValue.map((val) => serialize(val)).join("") diff --git a/@app/components/src/EventCard.tsx b/@app/components/src/EventCard.tsx index 777959f86..2f4a00930 100644 --- a/@app/components/src/EventCard.tsx +++ b/@app/components/src/EventCard.tsx @@ -7,6 +7,7 @@ import { Badge, Card, Typography } from "antd" import dayjs from "dayjs" import * as NextImage from "next/image" +import { useFeature } from "./Feature" import { H5 } from "./Text" import { ButtonLink, EventQuotaPopover, Link, useTranslation } from "." @@ -39,8 +40,10 @@ export const EventCard: React.FC = ({ event }) => { headerImageFile, signupOpen, isHighlighted, + highlightText, } = event const { t, lang } = useTranslation("home") + const customRibbonText = useFeature("ribbon_text") const title = isHighlighted ? `🔥 ${name[lang]} 🔥 ` : name[lang] @@ -108,7 +111,7 @@ export const EventCard: React.FC = ({ event }) => { {card} diff --git a/@app/components/src/EventForm/EventFormFooter.tsx b/@app/components/src/EventForm/EventFormFooter.tsx new file mode 100644 index 000000000..13aac21e7 --- /dev/null +++ b/@app/components/src/EventForm/EventFormFooter.tsx @@ -0,0 +1,227 @@ +import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react" +import { LeftOutlined, RightOutlined } from "@ant-design/icons" +import { css } from "@emotion/css" +import { + Alert, + Button, + Form, + Space, + Switch, + theme, + Tooltip, + Typography, +} from "antd" + +import { ErrorAlert, useTranslation } from "../." + +interface FooterTab { + key: string + label: string +} + +interface EventFormFooterProps { + type: "update" | "create" + // Tabs the arrow buttons move between, in order + tabs: FooterTab[] + activeTab: string + setActiveTab: (tab: string) => void + // Hides the footer without unmounting it, so the isDraft field stays + // registered in the form while another tab is open + hidden: boolean + canSubmit: boolean + // What still keeps the form from being saved + missingFields: string[] | null + formSubmitting: boolean + formError: any + // Field errors from the last save attempt + submitErrors: string[] | null + isDraft: boolean + setIsDraft: Dispatch> +} + +// Bar fixed to the bottom of the window with tab navigation on the left +// and the draft switch and submit button on the right +export const EventFormFooter: React.FC = ({ + type, + tabs, + activeTab, + setActiveTab, + hidden, + canSubmit, + missingFields, + formSubmitting, + formError, + submitErrors, + isDraft, + setIsDraft, +}) => { + const { t } = useTranslation("events") + const { token } = theme.useToken() + const index = tabs.findIndex(({ key }) => key === activeTab) + const previous = tabs[index - 1] + const next = tabs[index + 1] + + // The bar is fixed to the window, so it follows the placeholder left in + // its place for its horizontal position (the admin side menu collapses), + // and the placeholder takes the bar's height so the end of the form can + // be scrolled above it + const placeholder = useRef(null) + const bar = useRef(null) + const [box, setBox] = useState({ left: 0, width: 0 }) + const [height, setHeight] = useState(0) + + useEffect(() => { + if (!placeholder.current || !bar.current) return + const updateBox = () => { + const rect = placeholder.current?.getBoundingClientRect() + if (rect) setBox({ left: rect.left, width: rect.width }) + } + const boxObserver = new ResizeObserver(updateBox) + boxObserver.observe(placeholder.current) + const heightObserver = new ResizeObserver(([entry]) => + setHeight(entry.borderBoxSize?.[0]?.blockSize ?? 0) + ) + heightObserver.observe(bar.current) + window.addEventListener("resize", updateBox) + return () => { + boxObserver.disconnect() + heightObserver.disconnect() + window.removeEventListener("resize", updateBox) + } + }, []) + + return ( + + ) +} diff --git a/@app/components/src/EventForm/MainTab.tsx b/@app/components/src/EventForm/MainTab.tsx index dc3fd23ad..17a8fd3f0 100644 --- a/@app/components/src/EventForm/MainTab.tsx +++ b/@app/components/src/EventForm/MainTab.tsx @@ -1,11 +1,13 @@ import { Dispatch, SetStateAction } from "react" import { CreateEventPageQuery, UpdateEventPageQuery } from "@app/graphql" -import { range, tailFormItemLayout } from "@app/lib" -import { Button, DatePicker, Form, Input, Row, Select, Switch } from "antd" -import dayjs from "dayjs" +import { range } from "@app/lib" +import { DatePicker, Form, Input, Select, Switch } from "antd" +import dayjs, { Dayjs } from "dayjs" -import { Editor, ErrorAlert, FileUpload, useTranslation } from "../." +import { Editor, FileUpload, useFeature, useTranslation } from "../." +import { HighlightTextField } from "./fields/HighlightTextField" +import { TimeRangePicker, TimeRangePickerProps } from "./TimeRangePicker" import { FormValues } from "." import type { UploadFile } from "antd/lib/upload/interface" @@ -13,18 +15,22 @@ import type { UploadFile } from "antd/lib/upload/interface" const { Option } = Select const { Group } = Input const { RangePicker } = DatePicker +// The scroll column picker has no day click, so it drops that option +const ScrollTimeRangePicker: React.FC = ({ + dayClickEndAfterDays: _, + ...props +}) => + +// Typing a time can store a half-filled range, so require both ends +const bothEndsSet = (_: unknown, value?: Array) => + value?.[0] && value?.[1] ? Promise.resolve() : Promise.reject() interface MainTabProps { type: "update" | "create" formValues: FormValues data: CreateEventPageQuery | UpdateEventPageQuery - formSubmitting: boolean selectedLanguages: string[] setSelectedLanguages: Dispatch> - isDraft: boolean - setIsDraft: Dispatch> - tabErrors: string[] | null - formError: any supportedLanguages: Array | null | undefined } @@ -35,15 +41,17 @@ export const MainTab: React.FC = (props) => { formValues, selectedLanguages, setSelectedLanguages, - isDraft, - setIsDraft, - formError, - tabErrors, - formSubmitting, supportedLanguages, } = props const { t, lang } = useTranslation("events") + // The control for the event and registration times: typed HH : mm : ss + // boxes (TimeRangePicker) or the time scroll columns (RangePicker) + const typedTimes = useFeature("typed_time_input") + const DateTimeRangePicker = typedTimes + ? TimeRangePicker + : ScrollTimeRangePicker + function getUploadDefaultFileList(): Array | undefined { if (type === "update") { const { headerImageFile } = (data as UpdateEventPageQuery)?.event || {} @@ -227,14 +235,15 @@ export const MainTab: React.FC = (props) => { name="eventTime" rules={[ { - type: "array", required: true, message: t("forms.rules.event.provideEventTime"), + validator: bothEndsSet, }, ]} > - @@ -244,17 +253,22 @@ export const MainTab: React.FC = (props) => { name="registrationTime" rules={[ { - type: "array", required: true, message: t("forms.rules.event.provideRegistrationTime"), + validator: bothEndsSet, }, ]} > - @@ -265,6 +279,7 @@ export const MainTab: React.FC = (props) => { > + e[0]} label={t("headerImage")} @@ -279,48 +294,6 @@ export const MainTab: React.FC = (props) => { maxCount={1} /> - - setIsDraft(checked)} - /> - - {formError && ( - - - - )} - {tabErrors ? ( - - {tabErrors?.map((e, i) => ( - - {e} - - ))} - - ) : null} - - - ) } diff --git a/@app/components/src/EventForm/PreviewTab.tsx b/@app/components/src/EventForm/PreviewTab.tsx new file mode 100644 index 000000000..d8e3b5714 --- /dev/null +++ b/@app/components/src/EventForm/PreviewTab.tsx @@ -0,0 +1,48 @@ +import { EventPage_QuestionFragment } from "@app/graphql" +import { FormInstance, Typography } from "antd" + +import { EventRegistrationForm, useTranslation } from "../." + +type LocalizedText = Record | null | undefined + +interface PreviewTabProps { + form: FormInstance + selectedLanguages: string[] +} + +/** + * Shows the registration form as registrants will see it, built from the + * questions currently in the event form. Nothing is submitted. + */ +export const PreviewTab: React.FC = ({ + form, + selectedLanguages, +}) => { + const { t, lang } = useTranslation("events") + + // The registration form shows texts in the page language. Fall back to the + // event's other languages so an untranslated text isn't shown as empty. + const localize = (text: LocalizedText) => ({ + [lang]: + [lang, ...selectedLanguages].map((l) => text?.[l]).find(Boolean) ?? "", + }) + + const questions = ((form.getFieldValue("questions") ?? []) as any[]) + // Skip rows where no question type has been chosen yet + .filter((q) => q?.type) + .map((q, index) => ({ + // New questions don't have an id yet, but answers are keyed by it + id: q.id ?? `preview-${index}`, + type: q.type.toUpperCase(), + isRequired: !!q.isRequired, + label: localize(q.label), + data: q.data?.map(localize) ?? null, + })) as EventPage_QuestionFragment[] + + return ( + <> + {t("previewInfo")} + + + ) +} diff --git a/@app/components/src/EventForm/QuestionsTab.tsx b/@app/components/src/EventForm/QuestionsTab.tsx index 44e33658f..2ef3fee22 100644 --- a/@app/components/src/EventForm/QuestionsTab.tsx +++ b/@app/components/src/EventForm/QuestionsTab.tsx @@ -3,12 +3,12 @@ import { DndProvider } from "react-dnd" import { HTML5Backend } from "react-dnd-html5-backend" import { DragOutlined, - MinusCircleTwoTone, + MinusCircleOutlined, MinusOutlined, - PlusCircleTwoTone, + PlusCircleOutlined, PlusOutlined, } from "@ant-design/icons" -import { QuestionType } from "@app/graphql" +import { QuestionPrefill, QuestionType } from "@app/graphql" import { arePropsEqual } from "@app/lib" import { Button, @@ -21,14 +21,23 @@ import { Row, Select, Space, + theme, Tooltip, + Typography, } from "antd" +import Trans from "next-translate/Trans" -import { useTranslation } from "../." +import { Feature, useTranslation } from "../." import { Draggable } from "../Draggable" import { useIsMobile } from "../hooks" import { H5 } from "../Text" +import { + KeepQuestionPrefill, + QuestionPrefillSelect, +} from "./fields/QuestionPrefillSelect" +import { QuestionTemplateFields } from "./fields/QuestionTemplateFields" + import type { SelectValue } from "antd/lib/select" const { Option } = Select @@ -40,11 +49,15 @@ type QuestionData = { label: string isRequired: boolean data: string[] + prefill?: QuestionPrefill | null } interface QuestionsTabProps { form: FormInstance selectedLanguages: string[] + // Only compared by memo: without it a language switch doesn't re-render + // the tab, which leaves its texts and field messages in the old language + lang: string } const colSpan = { md: { span: 6 }, sm: { span: 12 }, xs: { span: 24 } } @@ -57,6 +70,7 @@ export const QuestionsTab: React.FC = memo( */ const { t } = useTranslation("events") + const { token } = theme.useToken() const isMobile = useIsMobile() const [, forceUpdate] = useReducer((x) => x + 1, 0) const { getFieldValue, setFieldsValue } = form @@ -77,10 +91,12 @@ export const QuestionsTab: React.FC = memo( if (!hasData) { questions[index].data = [""] - setFieldsValue({ - questions, - }) } + // Only TEXT answers can be prefilled + questions[index].prefill = null + setFieldsValue({ + questions, + }) } forceUpdate() } @@ -139,9 +155,9 @@ export const QuestionsTab: React.FC = memo( function renderQuestionDataField(index: number, i: number) { const addDataOption = ( - handleAddOption(index)} /> @@ -160,31 +176,42 @@ export const QuestionsTab: React.FC = memo( const firstLanguage = selectedLanguages?.[0] return selectedLanguages.map((l) => { + const icon = + l !== firstLanguage + ? null + : i === 0 + ? addDataOption + : removeDataOption(index, i) return ( - - - {i === 0 && l === firstLanguage && addDataOption} - {i > 0 && l === firstLanguage && removeDataOption(index, i)} - - } - /> - + + e.preventDefault()} + /> + + {/* Reserve the icon's width on every row so the fields line up */} + {icon} + ) }) } @@ -195,8 +222,18 @@ export const QuestionsTab: React.FC = memo( <> {questionLabel} - {/* TEXT questions don't have any data associated with them. - This Col is included for layout. */} + {/* TEXT questions have no options. An answer can be prefilled + from the registrant's registration profile. */} + } + name="prefill_answers" + > + + ) @@ -279,6 +316,18 @@ export const QuestionsTab: React.FC = memo( return ( <> + + + + + }} + i18nKey="events:questionsAutomaticallyCollected" + /> + {(fields, { add, remove, move }) => ( @@ -303,7 +352,11 @@ export const QuestionsTab: React.FC = memo( key={key} id={key} index={index} - move={move} + move={(from, to) => { + move(from, to) + // Re-read questions so type and options follow the moved row + forceUpdate() + }} > @@ -312,6 +365,10 @@ export const QuestionsTab: React.FC = memo( + {questions?.[index]?.type?.toUpperCase() !== + QuestionType.Text && ( + + )} = memo( - remove(name)} + style={{ color: token.colorError }} + onClick={() => { + remove(name) + forceUpdate() + }} /> diff --git a/@app/components/src/EventForm/QuotasTab.tsx b/@app/components/src/EventForm/QuotasTab.tsx index ffe3398ef..59cdbe835 100644 --- a/@app/components/src/EventForm/QuotasTab.tsx +++ b/@app/components/src/EventForm/QuotasTab.tsx @@ -3,24 +3,44 @@ import { DndProvider } from "react-dnd" import { HTML5Backend } from "react-dnd-html5-backend" import { DragOutlined, - MinusCircleTwoTone, + MinusCircleOutlined, PlusOutlined, } from "@ant-design/icons" import { arePropsEqual } from "@app/lib" -import { Button, Form, Input, InputNumber, Space, Switch, Tooltip } from "antd" +import { + Button, + Form, + Input, + InputNumber, + Space, + Switch, + theme, + Tooltip, + Typography, +} from "antd" -import { useTranslation } from "../." +import { Feature, useFeature, useTranslation } from "../." import { Draggable } from "../Draggable" +import { QuotaPriceField, QuotaPriceWarning } from "./fields/QuotaPriceField" +import { QuotaTemplateFields } from "./fields/QuotaTemplateFields" + interface QuotasTabProps { initialValues?: any selectedLanguages: string[] + // Only compared by memo: without it a language switch doesn't re-render + // the tab, which leaves its texts and field messages in the old language + lang: string } export const QuotasTab: React.FC = memo( ({ initialValues, selectedLanguages }) => { const [hasOpenQuota, setHasOpenQuota] = useState(false) const { t } = useTranslation("events") + const { token } = theme.useToken() + const form = Form.useFormInstance() + // Prices only mean something while payments are enabled + const showPrices = useFeature("payments") useEffect(() => { if (initialValues?.openQuotaSize > 0) setHasOpenQuota(true) @@ -28,15 +48,20 @@ export const QuotasTab: React.FC = memo( return ( + + + { - if ((!quotas || quotas?.length < 1) && !hasOpenQuota) { - return Promise.reject( - new Error(t("errors.mustProvideEventQuota")) - ) + if (!quotas || quotas?.length < 1) { + return Promise.reject() } }, }, @@ -105,11 +130,14 @@ export const QuotasTab: React.FC = memo( placeholder={t("forms.placeholders.quota.size")} /> + {showPrices && ( + + )} {numRegistrations === 0 ? ( - remove(name)} /> @@ -119,6 +147,12 @@ export const QuotasTab: React.FC = memo( )} + {showPrices && ( + + )} ) })} @@ -141,13 +175,24 @@ export const QuotasTab: React.FC = memo( setHasOpenQuota(val)} + onChange={(val) => { + setHasOpenQuota(val) + // A switched off open quota shouldn't keep its size, or the + // event would still get one when saved. A switched on one + // starts empty, so it has to be given a size before saving + if (!val) form.setFieldValue("openQuotaSize", 0) + else if (!form.getFieldValue("openQuotaSize")) { + form.setFieldValue("openQuotaSize", null) + } + }} /> = memo( /> + + {t("overflowQuotaInfo")} + + {` ${t("templates.quotas.openQuotaHint")}`} + + + {showPrices && ( + + + {t("admin:payments.quotas.noteFree")} + + + {t("admin:payments.quotas.noteFees")} + + + {t("admin:payments.quotas.noteOpenQuota")} + + + )} ) }, diff --git a/@app/components/src/EventForm/RegistrationsPayments.tsx b/@app/components/src/EventForm/RegistrationsPayments.tsx new file mode 100644 index 000000000..156dff0d2 --- /dev/null +++ b/@app/components/src/EventForm/RegistrationsPayments.tsx @@ -0,0 +1,268 @@ +import { useCallback, useState } from "react" +import { + EventPaymentSummary, + RegistrationPaymentStatus, + useAdminSendPaymentRemindersMutation, +} from "@app/graphql" +import { formatEuro } from "@app/lib" +import { + Alert, + Button, + Card, + Col, + message, + Modal, + Row, + Segmented, + Space, + Statistic, + Tag, + Typography, +} from "antd" +import dayjs from "dayjs" + +import { ErrorAlert, useTranslation } from "../." + +const { Text, Paragraph } = Typography + +export type PaymentFilter = "all" | "unpaid" | "paid" + +const STATUS_TAG_COLORS: Record = { + [RegistrationPaymentStatus.Paid]: "success", + [RegistrationPaymentStatus.PaidManually]: "success", + [RegistrationPaymentStatus.Unpaid]: "warning", + [RegistrationPaymentStatus.NotRequired]: "default", +} + +interface PaymentStatusTagProps { + paymentStatus: RegistrationPaymentStatus | null | undefined + queued: boolean +} + +/** The Payment column of the registrations table. */ +export const PaymentStatusTag: React.FC = ({ + paymentStatus, + queued, +}) => { + const { t } = useTranslation("admin") + // People in the queue don't pay until they get a spot, unless they have + // somehow paid already. + const isPaid = + paymentStatus === RegistrationPaymentStatus.Paid || + paymentStatus === RegistrationPaymentStatus.PaidManually + if (!paymentStatus || (queued && !isPaid)) { + return — + } + return ( + + {t(`payments.status.${paymentStatus}`)} + + ) +} + +interface PaymentSummaryProps { + summary: EventPaymentSummary | null | undefined +} + +/** + * Summary tiles above the registrations table, and a hint about card + * payments not linked to a registration, which Ilmo never refunds. + */ +export const PaymentSummary: React.FC = ({ summary }) => { + const { t } = useTranslation("admin") + const unlinkedCount = summary?.unlinkedCardPaymentCount ?? 0 + const tiles = [ + { + key: "paid", + title: t("payments.summary.paid"), + value: String(summary?.paidCount ?? 0), + suffix: t("payments.summary.paidOf", { count: summary?.dueCount ?? 0 }), + }, + { + key: "unpaid", + title: t("payments.summary.unpaid"), + value: String(summary?.unpaidCount ?? 0), + valueStyle: summary?.unpaidCount ? { color: "#8a4b00" } : undefined, + }, + { + key: "ticketsPaid", + title: t("payments.summary.ticketsPaid"), + value: formatEuro(summary?.ticketsPaidCents ?? 0), + }, + { + key: "guildReceives", + title: t("payments.summary.guildReceives"), + value: `≈ ${formatEuro(summary?.guildReceivesCents ?? 0)}`, + }, + ] + + return ( + + {tiles.map(({ key, title, value, suffix, valueStyle }) => ( + + + v} + suffix={suffix} + title={title} + value={value} + valueStyle={valueStyle} + /> + + + ))} + {unlinkedCount > 0 && ( + + + + )} + + ) +} + +function formatReminderTime(value: string) { + const date = dayjs(value) + return { date: date.format("l"), time: date.format("LT") } +} + +interface PaymentToolbarProps { + eventId: string + filter: PaymentFilter + onFilterChange: (filter: PaymentFilter) => void + summary: EventPaymentSummary | null | undefined + totalCount: number + hasPaidQuota: boolean + lastReminderSentAt: string | null | undefined + onRemindersSent: () => void +} + +/** + * The All / Unpaid / Paid filter and the "Send reminder to N unpaid" button + * with its confirm dialog (boards 9 and 11). + */ +export const PaymentToolbar: React.FC = ({ + eventId, + filter, + onFilterChange, + summary, + totalCount, + hasPaidQuota, + lastReminderSentAt, + onRemindersSent, +}) => { + const { t } = useTranslation("admin") + const [showConfirm, setShowConfirm] = useState(false) + const [error, setError] = useState(null) + const [{ fetching }, sendReminders] = useAdminSendPaymentRemindersMutation() + const unpaidCount = summary?.unpaidCount ?? 0 + + const doSendReminders = useCallback(async () => { + setError(null) + try { + const { data, error } = await sendReminders({ input: { eventId } }) + if (error) throw error + const count = data?.adminSendPaymentReminders?.integer ?? 0 + message.success(t("payments.reminder.sent", { count })) + setShowConfirm(false) + onRemindersSent() + } catch (e) { + setError(e) + } + }, [eventId, sendReminders, onRemindersSent, t]) + + return ( + + + + data-cy="registrations-payment-filter" + options={[ + { + value: "all", + label: t("payments.filter.all", { count: totalCount }), + }, + { + value: "unpaid", + label: t("payments.filter.unpaid", { count: unpaidCount }), + }, + { + value: "paid", + label: t("payments.filter.paid", { + count: summary?.paidCount ?? 0, + }), + }, + ]} + value={filter} + onChange={onFilterChange} + /> + + {hasPaidQuota && ( + + + {lastReminderSentAt && ( + + {t( + "payments.lastReminderSent", + formatReminderTime(lastReminderSentAt) + )} + + )} + + + + )} + setShowConfirm(false)} + onOk={doSendReminders} + > + {t("payments.reminder.body")} + {lastReminderSentAt && ( + + {t( + "payments.reminder.lastSent", + formatReminderTime(lastReminderSentAt) + )} + + )} + {error && ( + + )} + + + ) +} diff --git a/@app/components/src/EventForm/RegistrationsTab.tsx b/@app/components/src/EventForm/RegistrationsTab.tsx index 041046388..31fa88c89 100644 --- a/@app/components/src/EventForm/RegistrationsTab.tsx +++ b/@app/components/src/EventForm/RegistrationsTab.tsx @@ -1,9 +1,11 @@ -import { memo } from "react" +import { memo, useCallback, useMemo, useState } from "react" import { EventPage_QuestionFragment, ListEventRegistrationsDocument, Registration, + RegistrationPaymentStatus, RegistrationStatus, + useEventPaymentSummaryQuery, } from "@app/graphql" import { arePropsEqual, downloadRegistrations, Sorter } from "@app/lib" import { Typography } from "antd" @@ -17,31 +19,120 @@ import { useTranslation, } from "../." +import { + PaymentFilter, + PaymentStatusTag, + PaymentSummary, + PaymentToolbar, +} from "./RegistrationsPayments" import { RegistrationsTableActions } from "./RegistrationsTableActions" const { Text } = Typography interface RegistrationsTabProps { + eventId: string eventSlug: string questions: EventPage_QuestionFragment[] | undefined + paymentsEnabled?: boolean +} + +// Registrations holding a spot, which are the ones the payment summary counts +const IN_SPOT = [RegistrationStatus.InQuota, RegistrationStatus.InOpenQuota] + +const PAYMENT_FILTER_VARIABLES: Record> = { + all: {}, + unpaid: { + paymentStatus: { equalTo: RegistrationPaymentStatus.Unpaid }, + status: { in: IN_SPOT }, + }, + paid: { + paymentStatus: { + in: [ + RegistrationPaymentStatus.Paid, + RegistrationPaymentStatus.PaidManually, + ], + }, + status: { in: IN_SPOT }, + }, } +// Sort order of the Payment column: unpaid first, as organizers act on them +const PAYMENT_SORT_ORDER: Record = { + [RegistrationPaymentStatus.Unpaid]: 0, + [RegistrationPaymentStatus.Paid]: 1, + [RegistrationPaymentStatus.PaidManually]: 2, + [RegistrationPaymentStatus.NotRequired]: 3, +} + +// The table's sorters get the column values (see ServerPaginatedTable) +const paymentSorter = (a: string | null, b: string | null) => + (PAYMENT_SORT_ORDER[a as RegistrationPaymentStatus] ?? 4) - + (PAYMENT_SORT_ORDER[b as RegistrationPaymentStatus] ?? 4) + export const RegistrationsTab: React.FC = memo( - ({ eventSlug, questions }) => { + ({ eventId, eventSlug, questions, paymentsEnabled = false }) => { const router = useRouter() const { t, lang } = useTranslation("events") const isMobile = useIsMobile() + const [paymentFilter, setPaymentFilter] = useState("all") - const commonColumns = [ + const [{ data: summaryData }, refetchSummary] = useEventPaymentSummaryQuery( { - title: "", - key: "actions", - width: !isMobile ? 160 : 1, - ellipsis: true, - render: (_value: string, row: Registration) => ( - - ), + variables: { id: eventId }, + pause: !paymentsEnabled || !eventId, + } + ) + const paymentEvent = summaryData?.event + const summary = paymentEvent?.paymentSummary + // An event is paid when one of its quotas has a price + const hasPaidQuota = !!paymentEvent?.quotas.nodes.some( + (quota) => quota.priceCents > 0 + ) + // Payments made before every quota was made free are still shown, so + // organizers can see who paid. + const showPayments = + paymentsEnabled && + !!summary && + (hasPaidQuota || + (summary.paidCount ?? 0) > 0 || + (summary.unlinkedCardPaymentCount ?? 0) > 0) + + const onPaymentChange = useCallback(() => { + refetchSummary({ requestPolicy: "network-only" }) + }, [refetchSummary]) + + const actionsColumn = { + title: "", + key: "actions", + width: !isMobile ? (showPayments ? 200 : 160) : 1, + ellipsis: true, + render: (_value: string, row: Registration) => ( + + ), + } + + const paymentColumn = { + title: t("admin:payments.paymentColumn"), + dataIndex: ["paymentStatus"], + key: "paymentStatus", + width: 130, + sorter: { + compare: paymentSorter as (a: string, b: string) => number, }, + render: (value: RegistrationPaymentStatus | null, row: Registration) => ( + + ), + } + + const nameAndQuotaColumns = [ { title: t("common:name"), dataIndex: ["fullName"], @@ -62,74 +153,121 @@ export const RegistrationsTab: React.FC = memo( }, ] - const columns = !isMobile - ? [ - ...commonColumns, - { - title: t("common:email"), - dataIndex: ["email"], - key: "email", - ellipsis: true, - sorter: { - compare: Sorter.TEXT, - }, - }, - { - title: t("events:queued"), - dataIndex: ["status"], - key: "status", - width: 80, - render: (value: string) => - value === RegistrationStatus.InQueue ? ( - {t("common:yes")} - ) : ( - {t("common:no")} - ), - }, - { - title: t("common:answers"), - dataIndex: ["answers"], - key: "answers", - ellipsis: true, - render: (_value: string, row: Registration) => ( - - ), - }, - { - title: t("common:createdAt"), - dataIndex: ["createdAt"], - key: "createdAt", - render: (value: string) => dayjs(value).format("l LT ss.SSS"), - }, - { - title: t("common:updatedAt"), - dataIndex: ["updatedAt"], - key: "updatedAt", - render: (value: string, row: Registration) => - value !== row.createdAt - ? dayjs(value).format("l LT ss.SSS") - : t("common:no"), - }, - ] - : commonColumns + const commonColumns = [actionsColumn, ...nameAndQuotaColumns] + + const emailAndQueuedColumns = [ + { + title: t("common:email"), + dataIndex: ["email"], + key: "email", + ellipsis: true, + sorter: { + compare: Sorter.TEXT, + }, + }, + { + title: t("events:queued"), + dataIndex: ["status"], + key: "status", + width: 80, + render: (value: string) => + value === RegistrationStatus.InQueue ? ( + {t("common:yes")} + ) : ( + {t("common:no")} + ), + }, + ] + + const otherColumns = [ + { + title: t("common:answers"), + dataIndex: ["answers"], + key: "answers", + ellipsis: true, + render: (_value: string, row: Registration) => ( + + ), + }, + { + title: t("common:createdAt"), + dataIndex: ["createdAt"], + key: "createdAt", + render: (value: string) => dayjs(value).format("l LT ss.SSS"), + }, + { + title: t("common:updatedAt"), + dataIndex: ["updatedAt"], + key: "updatedAt", + render: (value: string, row: Registration) => + value !== row.createdAt + ? dayjs(value).format("l LT ss.SSS") + : t("common:no"), + }, + ] + + // With payments the row actions sit at the right end of the row and a + // Payment column follows the queue status. + const columns = showPayments + ? !isMobile + ? [ + ...nameAndQuotaColumns, + ...emailAndQueuedColumns, + paymentColumn, + ...otherColumns, + actionsColumn, + ] + : [...nameAndQuotaColumns, paymentColumn, actionsColumn] + : !isMobile + ? [...commonColumns, ...emailAndQueuedColumns, ...otherColumns] + : commonColumns + + const filter = showPayments ? paymentFilter : "all" + const variables = useMemo( + () => ({ eventId: router.query.id, ...PAYMENT_FILTER_VARIABLES[filter] }), + [router.query.id, filter] + ) return ( - + <> + {showPayments && ( + <> + + + + )} + + t(`admin:payments.status.${status}`), + })} + queryDocument={ListEventRegistrationsDocument} + size="small" + variables={variables} + showDownload + showPagination + showSizeChanger + /> + ) }, arePropsEqual diff --git a/@app/components/src/EventForm/RegistrationsTableActions.tsx b/@app/components/src/EventForm/RegistrationsTableActions.tsx index 6b5402ca3..d1babde24 100644 --- a/@app/components/src/EventForm/RegistrationsTableActions.tsx +++ b/@app/components/src/EventForm/RegistrationsTableActions.tsx @@ -2,30 +2,69 @@ import { useCallback, useState } from "react" import { EventPage_QuestionFragment, Registration, + RegistrationPaymentStatus, + RegistrationStatus, useAdminDeleteRegistrationMutation, + useAdminMarkRegistrationPaidMutation, + useAdminUnmarkRegistrationPaidMutation, useAdminUpdateRegistrationMutation, } from "@app/graphql" -import { Button, Col, message, Popconfirm, Row } from "antd" +import { + Alert, + Button, + Col, + Dropdown, + message, + Modal, + Popconfirm, + Row, + Typography, +} from "antd" import { ErrorAlert, useTranslation } from ".." import { RegistrationUpdateModal } from "./RegistrationUpdateModal" +import type { MenuProps } from "antd" + +const { Paragraph, Text } = Typography + interface RegistrationsTableActionsProps { registration: Registration questions: EventPage_QuestionFragment[] | undefined + // Show the payment actions: the "⋯" menu and the paid delete dialog + showPayments?: boolean + // Called after a payment changed, so the payment summary can be refetched + onPaymentChange?: () => void } export const RegistrationsTableActions: React.FC< RegistrationsTableActionsProps > = (props) => { - const { registration } = props + const { registration, showPayments = false, onPaymentChange } = props const { t } = useTranslation("admin") const [showModal, setShowModal] = useState(false) + const [showDeleteModal, setShowDeleteModal] = useState(false) const [updateToken, setUpdateToken] = useState(undefined) const [error, setError] = useState(null) + const [errorMessage, setErrorMessage] = useState(null) const [, updateRegistration] = useAdminUpdateRegistrationMutation() - const [, deleteRegistration] = useAdminDeleteRegistrationMutation() + const [{ fetching: deleting }, deleteRegistration] = + useAdminDeleteRegistrationMutation() + const [{ fetching: markingPaid }, markPaid] = + useAdminMarkRegistrationPaidMutation() + const [{ fetching: unmarkingPaid }, unmarkPaid] = + useAdminUnmarkRegistrationPaidMutation() + const [confirmUndo, setConfirmUndo] = useState(false) + const paymentRequestRunning = markingPaid || unmarkingPaid + + const { paymentStatus } = registration + // Paid rows always get the delete dialog, even before the payment summary + // has loaded, so that a paid registration is never deleted without the + // organizer seeing that nothing is refunded. + const isPaid = + paymentStatus === RegistrationPaymentStatus.Paid || + paymentStatus === RegistrationPaymentStatus.PaidManually const doDelete = useCallback(async () => { try { @@ -37,10 +76,13 @@ export const RegistrationsTableActions: React.FC< throw new Error(t("register_event:deleteRegistrationFailed")) } message.info(t("notifications.deleteSuccess")) + setShowDeleteModal(false) + if (showPayments) onPaymentChange?.() } catch (e) { + setErrorMessage(null) setError(e) } - }, [registration, deleteRegistration, t]) + }, [registration, deleteRegistration, t, showPayments, onPaymentChange]) const doUpdate = useCallback(async () => { try { @@ -51,14 +93,90 @@ export const RegistrationsTableActions: React.FC< setUpdateToken(data?.adminUpdateRegistration?.updateToken!) setShowModal(true) } catch (e) { + setErrorMessage(null) setError(e) } }, [registration, updateRegistration]) + const doMarkPaid = useCallback(async () => { + try { + const { error } = await markPaid({ + input: { registrationId: registration.id }, + }) + if (error) throw error + message.success(t("payments.actions.markPaidSuccess")) + onPaymentChange?.() + } catch (e) { + setErrorMessage(t("payments.actions.failed")) + setError(e) + } + }, [registration, markPaid, t, onPaymentChange]) + + const doUnmarkPaid = useCallback(async () => { + try { + const { error } = await unmarkPaid({ + input: { registrationId: registration.id }, + }) + if (error) throw error + message.success(t("payments.actions.undoManualSuccess")) + onPaymentChange?.() + } catch (e) { + setErrorMessage(t("payments.actions.failed")) + setError(e) + } + }, [registration, unmarkPaid, t, onPaymentChange]) + + const menuItems: MenuProps["items"] = [ + ...(paymentStatus === RegistrationPaymentStatus.Unpaid && + registration.status !== RegistrationStatus.InQueue + ? [ + { + key: "markPaid", + label: ( + + {t("payments.actions.markPaid")} +
+ + {t("payments.actions.markPaidHelp")} + +
+ ), + disabled: paymentRequestRunning, + onClick: doMarkPaid, + }, + ] + : []), + ...(paymentStatus === RegistrationPaymentStatus.PaidManually + ? [ + { + key: "undoManual", + label: ( + + {t("payments.actions.undoManual")} + + ), + onClick: () => setConfirmUndo(true), + }, + ] + : []), + ] + + const deleteButton = ( + + ) + return ( <> - + - + {deleteButton} + + )} + {showPayments && ( + + setConfirmUndo(false)} + onConfirm={async () => { + setConfirmUndo(false) + await doUnmarkPaid() + }} + > + + + + + + )} {error ? ( ) : null} + {showDeleteModal ? ( + setShowDeleteModal(false)} + onOk={() => doDelete()} + > + {t("payments.delete.body")} + + + ) : null} {showModal ? ( ) : null} diff --git a/@app/components/src/EventForm/RequiredMark.tsx b/@app/components/src/EventForm/RequiredMark.tsx new file mode 100644 index 000000000..6c266e2d0 --- /dev/null +++ b/@app/components/src/EventForm/RequiredMark.tsx @@ -0,0 +1,21 @@ +import { theme } from "antd" + +// The same red asterisk antd shows next to required fields +// (see antd's .ant-form-item-required::before) +export const RequiredMark: React.FC = () => { + const { token } = theme.useToken() + return ( + + * + + ) +} diff --git a/@app/components/src/EventForm/TimeRangePicker.tsx b/@app/components/src/EventForm/TimeRangePicker.tsx new file mode 100644 index 000000000..69387f70c --- /dev/null +++ b/@app/components/src/EventForm/TimeRangePicker.tsx @@ -0,0 +1,173 @@ +import { useRef, useState } from "react" +import { css } from "@emotion/css" +import { DatePicker, Input, InputRef, Space } from "antd" +import { Dayjs } from "dayjs" + +import { dayClickRange } from "./timeRange" + +import type { RangePickerProps } from "antd/es/date-picker" + +const { RangePicker } = DatePicker + +const timeUnits = ["hour", "minute", "second"] as const +// Hide the time scroll columns and put the time boxes on the OK button's row +const timePopup = css` + .ant-picker-time-panel { + display: none; + } + && .ant-picker-footer { + display: flex; + align-items: center; + } + && .ant-picker-footer-extra { + flex: 1; + border-bottom: none; + } +` + +export type TimeRangePickerProps = RangePickerProps & { + // Clicking a new start day in the calendar fills in the whole range at + // once, from 12:00 that day to 23:59:59 this many days later, and closes + // the calendar. Typed times and clicks on the same day work as usual. + dayClickEndAfterDays?: number +} + +// RangePicker whose time is typed into HH : mm : ss boxes below the calendar +// instead of picked from scroll columns +export const TimeRangePicker: React.FC = ({ + value, + onChange, + dayClickEndAfterDays, + ...props +}) => { + const [open, setOpen] = useState(false) + // Typing into the input and clicking a day both report a calendar change, + // so remember whether the latest one started on a day in the calendar + const clickedDay = useRef(false) + const [active, setActive] = useState(0) + // Dates picked in the open popup before OK is pressed + const [pending, setPending] = useState(null) + // Digits typed so far in the focused box, shown unpadded while typing + const [draft, setDraft] = useState<{ box: number; text: string } | null>(null) + const boxes = useRef>([]) + const current = pending ?? value + const date = current?.[active] + + function typeDigits(i: number, input: string) { + if (!date) return + const unit = timeUnits[i] + const text = input.replace(/\D/g, "").slice(0, 2) + setDraft({ box: i, text }) + if (!text) return + + const max = unit === "hour" ? 23 : 59 + const next = [...(current ?? [null, null])] as [Dayjs | null, Dayjs | null] + next[active] = date[unit](Math.min(Number(text), max)) + setPending(next) + onChange?.(next, ["", ""]) + + // Two digits fill the box: continue with the next one + if (text.length === 2 && i < timeUnits.length - 1) focusBox(i + 1) + } + + // Deferred so the boxes are enabled before they get focus + function focusBox(i: number) { + setTimeout(() => boxes.current[i]?.focus()) + } + + return ( + ( +
{ + clickedDay.current = !!(e.target as HTMLElement).closest( + ".ant-picker-cell" + ) + }} + > + {panel} +
+ )} + renderExtraFooter={() => ( + + {timeUnits.map((unit, i) => ( + { + boxes.current[i] = el + }} + data-cy={`eventform-input-time-${unit}`} + disabled={!date} + inputMode="numeric" + maxLength={2} + size="small" + style={{ width: 40, textAlign: "center" }} + value={ + draft?.box === i + ? draft.text + : date + ? String(date[unit]()).padStart(2, "0") + : "" + } + onBlur={() => setDraft(null)} + onChange={(e) => typeDigits(i, e.target.value)} + onFocus={(e) => { + setDraft(null) + e.target.select() + }} + onKeyDown={(e) => { + if (e.key === "ArrowRight" && i < timeUnits.length - 1) { + e.preventDefault() + focusBox(i + 1) + } else if (e.key === "ArrowLeft" && i > 0) { + e.preventDefault() + focusBox(i - 1) + } + }} + /> + ))} + + )} + value={value} + onCalendarChange={(dates, _, info) => { + const changed = info.range === "end" ? 1 : 0 + const clicked = clickedDay.current + clickedDay.current = false + const day = dates?.[0] + const previousDay = current?.[0] + if ( + dayClickEndAfterDays !== undefined && + clicked && + changed === 0 && + day && + !(previousDay && day.isSame(previousDay, "day")) + ) { + onChange?.(dayClickRange(day, dayClickEndAfterDays), ["", ""]) + setPending(null) + setOpen(false) + return + } + let next = dates + // A start moved past the end clears the end (order={false} keeps + // the picker from swapping them instead) + if (changed === 0 && dates?.[0] && dates[1]?.isBefore(dates[0])) { + next = [dates[0], null] + onChange?.(next, ["", ""]) + } + setPending(next) + // A date was picked: continue with its hours + if (next?.[changed]) focusBox(0) + }} + onChange={onChange} + onFocus={(_, info) => setActive(info.range === "end" ? 1 : 0)} + onOpenChange={(nextOpen) => { + setOpen(nextOpen) + if (!nextOpen) setPending(null) + }} + /> + ) +} diff --git a/@app/components/src/EventForm/eventTemplates.ts b/@app/components/src/EventForm/eventTemplates.ts new file mode 100644 index 000000000..16502fc8b --- /dev/null +++ b/@app/components/src/EventForm/eventTemplates.ts @@ -0,0 +1,250 @@ +import { QuestionType } from "@app/graphql" + +type LocalizedText = { fi: string; en: string } + +type TemplateQuestion = { + type: QuestionType + isRequired: boolean + label: LocalizedText + data?: LocalizedText[] +} + +type TemplateQuota = { + title: LocalizedText +} + +// Ready-made questions the event creator can add with checkboxes on the +// questions tab. A preset can add more than one question. Question +// templates are built from these. +export const questionPresets: Record = { + telegram: [ + { + type: QuestionType.Text, + isRequired: true, + label: { fi: "Telegram", en: "Telegram" }, + }, + ], + alcohol: [ + { + type: QuestionType.Radio, + isRequired: true, + label: { fi: "Alkoholivalinta", en: "Alcohol preference" }, + data: [ + { fi: "Holiton", en: "Non-alcoholic" }, + { fi: "Holillinen", en: "Alcoholic" }, + { fi: "Holittomat shotit", en: "Non-alcoholic shots" }, + ], + }, + ], + // Common diets as checkboxes, plus a free text field for anything else + specialDiets: [ + { + type: QuestionType.Checkbox, + isRequired: false, + label: { fi: "Erityisruokavalio", en: "Special diet" }, + data: [ + { fi: "Kasvis", en: "Vegetarian" }, + { fi: "Laktoositon", en: "Lactose-free" }, + { fi: "Gluteeniton", en: "Gluten-free" }, + { fi: "Vegaani", en: "Vegan" }, + ], + }, + { + type: QuestionType.Text, + isRequired: false, + label: { + fi: "Muu erityisruokavalio tai allergia", + en: "Other special diet or allergy", + }, + }, + ], + seating: [ + { + type: QuestionType.Text, + isRequired: false, + label: { fi: "Paikkatoiveet", en: "Seating preferences" }, + }, + ], + avec: [ + { + type: QuestionType.Text, + isRequired: false, + label: { fi: "Avec", en: "Avec" }, + }, + ], + // A required checkbox with a single option, i.e. the registrant must tick it + bindingRegistration: [ + { + type: QuestionType.Checkbox, + isRequired: true, + label: { fi: "Sitova ilmoittautuminen", en: "Binding registration" }, + data: [ + { + fi: "Ymmärrän, että osallistumismaksu muuttuu sitovaksi ilmoittautumisen päätyttyä", + en: "I understand that the participation fee becomes binding once registration closes", + }, + ], + }, + ], +} + +// The `key` of a template is used as the value of the template selector and +// for its UI translation `events:templates..` +export type QuestionTemplate = { key: string; presets: string[] } +export type QuotaTemplate = { key: string; presets: string[] } + +export const NO_TEMPLATE = "none" + +export const questionTemplates: QuestionTemplate[] = [ + { + key: "sitsit", + presets: [ + "telegram", + "alcohol", + "specialDiets", + "seating", + "bindingRegistration", + ], + }, +] + +// Ready-made quotas the event creator can add with checkboxes on the quotas +// tab, one per year group. Quota templates are built from these. +const yearGroups = ["I", "II", "III", "IV", "N"] +export const quotaPresets: Record = { + // A regular quota anyone can register to, e.g. for events without year + // groups. Not the same as the event's overflow ("open") quota. + open: { title: { fi: "Avoin kiintiö", en: "Open quota" } }, + ...Object.fromEntries( + yearGroups.map((title) => [title, { title: { fi: title, en: title } }]) + ), +} + +export const quotaTemplates: QuotaTemplate[] = [ + { + key: "yearGroups", + presets: yearGroups, + }, +] + +function localize(text: LocalizedText, languages: string[]) { + return Object.fromEntries( + languages.map((l) => { + const lang = l.toLowerCase() + return [lang, text[lang as keyof LocalizedText] ?? text.en] + }) + ) +} + +/** + * The build functions below return EventForm list values. Texts are only + * filled in for the event's selected languages. Each item is marked with + * `presetKey` and/or `templateKey` so it can be removed again from the + * checkboxes or the template selector; the keys are dropped when the form is + * submitted. + */ + +export function buildPresetQuestions( + presetKey: string, + languages: string[], + templateKey?: string +) { + return questionPresets[presetKey].map((q) => ({ + type: q.type, + isRequired: q.isRequired, + label: localize(q.label, languages), + data: q.data ? q.data.map((d) => localize(d, languages)) : null, + presetKey, + templateKey, + })) +} + +export function buildTemplateQuestions( + templateKey: string, + languages: string[] +) { + const template = questionTemplates.find((t) => t.key === templateKey) + if (!template) return [] + + return template.presets.flatMap((presetKey) => + buildPresetQuestions(presetKey, languages, templateKey) + ) +} + +export function buildPresetQuota( + presetKey: string, + languages: string[], + templateKey?: string +) { + // Size is left empty on purpose so the event creator has to set it + return { + title: localize(quotaPresets[presetKey].title, languages), + presetKey, + templateKey, + } +} + +export function buildTemplateQuotas(templateKey: string, languages: string[]) { + const template = quotaTemplates.find((t) => t.key === templateKey) + if (!template) return [] + + return template.presets.map((presetKey) => + buildPresetQuota(presetKey, languages, templateKey) + ) +} + +/** + * The helpers below change an EventForm list (quotas or questions) when a + * preset checkbox or the template selector changes. Items without a + * `presetKey` or `templateKey` were added by hand and are always kept. + */ + +export type TemplateItem = { presetKey?: string; templateKey?: string } + +// The presets that have items in the list. A preset can add several items. +export function presetKeysOf(items: Array = []) { + const keys = items.map((item) => item?.presetKey).filter(Boolean) + return [...new Set(keys)] as string[] +} + +// The list after the preset checkboxes changed to `checked`: items of +// unticked presets are removed and newly ticked presets are added at the end +export function togglePresets( + items: Array, + checked: string[], + buildPreset: (presetKey: string) => T[] +) { + const present = presetKeysOf(items) + const kept = items.filter( + (item) => !item?.presetKey || checked.includes(item.presetKey) + ) + const added = checked + .filter((key) => !present.includes(key)) + .flatMap((key) => buildPreset(key)) + return [...kept, ...added] +} + +// A template's items, leaving out the presets that were ticked by hand so +// they are not added twice +export function withoutHandPickedPresets( + items: Array, + templateItems: T[] +) { + const ticked = presetKeysOf(items.filter((item) => !item?.templateKey)) + return templateItems.filter( + (item) => !item.presetKey || !ticked.includes(item.presetKey) + ) +} + +// The list after switching templates: the previous template's items are +// replaced by the new template's items +export function replaceTemplateItems( + items: Array, + templateItems: T[] +) { + return [...items.filter((item) => !item?.templateKey), ...templateItems] +} + +export function hasTemplateItems(items: Array) { + return items.some((item) => item?.templateKey) +} diff --git a/@app/components/src/EventForm/fields/HighlightTextField.tsx b/@app/components/src/EventForm/fields/HighlightTextField.tsx new file mode 100644 index 000000000..b5977575f --- /dev/null +++ b/@app/components/src/EventForm/fields/HighlightTextField.tsx @@ -0,0 +1,58 @@ +import { Form, Input } from "antd" + +import { useFeature, useTranslation } from "../.." + +const { Group } = Input + +// Holds a form value without showing it +const KeepValue: React.FC<{ value?: unknown }> = () => null + +interface HighlightTextFieldProps { + selectedLanguages: string[] +} + +/** + * The ribbon text of a highlighted event, one input per selected language. + * Shown while the event is highlighted. When the feature is off, the inputs + * are hidden but the stored text stays in the submitted values, so saving the + * event keeps it. + */ +export const HighlightTextField: React.FC = ({ + selectedLanguages, +}) => { + const { t } = useTranslation("events") + const customRibbonText = useFeature("ribbon_text") + const isHighlighted = Form.useWatch("isHighlighted") + + if (!customRibbonText) { + return ( + + ) + } + + if (!isHighlighted) { + return null + } + + return ( + + + {selectedLanguages.map((l, i) => ( + + 0 ? { marginTop: 5 } : undefined} + /> + + ))} + + + ) +} diff --git a/@app/components/src/EventForm/fields/QuestionPrefillSelect.tsx b/@app/components/src/EventForm/fields/QuestionPrefillSelect.tsx new file mode 100644 index 000000000..fe49fd0fb --- /dev/null +++ b/@app/components/src/EventForm/fields/QuestionPrefillSelect.tsx @@ -0,0 +1,119 @@ +import { QuestionPrefill } from "@app/graphql" +import { Form, Select } from "antd" + +import { useTranslation } from "../.." + +// Holds a form value without showing it +const KeepValue: React.FC<{ value?: unknown }> = () => null + +// The prefills an admin can choose. NONE is only sent to clear a prefill, see +// toEventInput. +type ProfilePrefill = Exclude + +// A prefill question is a TEXT question with a fixed label, filled in for +// every selected language when the admin picks what the answer prefills from +const PREFILL_LABELS: Record> = { + [QuestionPrefill.Telegram]: { + fi: "Telegram-käyttäjänimi", + en: "Telegram username", + }, + [QuestionPrefill.DietaryRestrictions]: { + fi: "Erityisruokavaliot ja allergiat", + en: "Dietary restrictions and allergies", + }, +} + +const AUTO_LABELS = Object.values(PREFILL_LABELS) +const PROFILE_PREFILLS = Object.keys(PREFILL_LABELS) as ProfilePrefill[] + +/** + * Labels for a question that now prefills from `prefill`. A label the admin + * has written is kept; an empty label or one filled in for another prefill is + * replaced. + */ +export function prefillQuestionLabel( + prefill: ProfilePrefill, + selectedLanguages: string[], + currentLabel: Record | null | undefined +): Record { + return Object.fromEntries( + selectedLanguages.map((l) => { + const lang = l.toLowerCase() + const current = currentLabel?.[lang] + const isAuto = + !current || AUTO_LABELS.some((labels) => labels[lang] === current) + const label = PREFILL_LABELS[prefill][lang] ?? PREFILL_LABELS[prefill].en + return [lang, isAuto ? label : current] + }) + ) +} + +interface QuestionPrefillFieldProps { + /** The question's index in the `questions` form list. */ + name: number +} + +/** + * Keeps a question's `prefill` value in the submitted values without showing + * it: for questions that cannot prefill, and while prefill_answers is off, so + * saving the event keeps the stored marking. + */ +export const KeepQuestionPrefill: React.FC = ({ + name, +}) => ( + +) + +interface QuestionPrefillSelectProps extends QuestionPrefillFieldProps { + selectedLanguages: string[] + /** Called after the question's label has been filled in. */ + onChange?: () => void +} + +/** + * Which registration profile field prefills the answer to a TEXT question. + * Placed inside ``. + */ +export const QuestionPrefillSelect: React.FC = ({ + name, + selectedLanguages, + onChange, +}) => { + const { t } = useTranslation("events") + const form = Form.useFormInstance() + + function handleChange(prefill: ProfilePrefill | undefined) { + if (prefill) { + const label = form.getFieldValue(["questions", name, "label"]) + form.setFieldValue( + ["questions", name, "label"], + prefillQuestionLabel(prefill, selectedLanguages, label) + ) + } + onChange?.() + } + + return ( + value ?? null} + name={[name, "prefill"]} + noStyle + > + ({ + value: flag.key, + label: nameOf(flag.key), + })), + ]} + style={{ width: "100%" }} + value={scope ?? ALL} + onChange={(value) => onScopeChange(value === ALL ? null : value)} + /> + + {shown.length > 0 ? ( + ( + + + {scope ? null : ( + + {nameOf(event.key ?? "")} + {event.key} + + )} + + {stateTag(event.oldState)} + + {stateTag(event.newState)} + + + {t("features.historyDrawer.by", { + actor: actorOf(event), + date: dayjs(event.createdAt).format("l LT"), + })} + + + + )} + /> + ) : ( + + )} + {footer} + + + ) +} diff --git a/@app/components/src/FeatureFlags/FeatureStateControl.tsx b/@app/components/src/FeatureFlags/FeatureStateControl.tsx new file mode 100644 index 000000000..76c08b354 --- /dev/null +++ b/@app/components/src/FeatureFlags/FeatureStateControl.tsx @@ -0,0 +1,159 @@ +import { CheckOutlined, LoadingOutlined, LockOutlined } from "@ant-design/icons" +import { FeatureState } from "@app/graphql" +import { featureAdminPreview } from "@app/lib" +import { + Button, + ConfigProvider, + Segmented, + Space, + theme, + Typography, +} from "antd" +import useTranslation from "next-translate/useTranslation" + +import { FEATURE_STATES, stateKey, stateSelectable } from "./transitions" + +import type { AdminFeatures_FeatureFlagFragment } from "@app/graphql" + +const { Text } = Typography + +// Colours back up the labels and never replace them. +const ADMINS_ONLY_COLOR = "#ad6800" +const OFF_COLOR = "#595959" +const LOCKED_SELECTED_BG = "#d9d9d9" + +interface FeatureStateControlProps { + flag: AdminFeatures_FeatureFlagFragment + name: string + /** The state being saved, if any. The control is locked meanwhile. */ + saving?: FeatureState + /** The state a failed save tried to reach, if any. */ + failed?: FeatureState + /** Smaller control for narrow screens. */ + compact?: boolean + onPick: (state: FeatureState) => void + onRetry: () => void + onDismiss: () => void +} + +/** + * The three-way control of one flag with its "who sees it" line, the saving + * and save-failed states, and the reason when the flag cannot be switched. + */ +export function FeatureStateControl({ + flag, + name, + saving, + failed, + compact = false, + onPick, + onRetry, + onDismiss, +}: FeatureStateControlProps) { + const { t } = useTranslation("admin") + const { token } = theme.useToken() + const key = flag.key + const locked = Boolean(flag.retiredAt) || !flag.available + const lockedAll = locked && flag.state === FeatureState.Off + const fill = { + [FeatureState.Off]: OFF_COLOR, + [FeatureState.AdminsOnly]: ADMINS_ONLY_COLOR, + [FeatureState.On]: token.colorPrimary, + } + + const options = FEATURE_STATES.map((state) => { + const checked = state === flag.state + const isSaving = state === saving + return { + value: state, + disabled: Boolean(saving) || !stateSelectable(flag, state), + label: ( + + + {isSaving ? ( + + ) : checked ? ( + + ) : null} + {isSaving + ? t("features.saving") + : t(`features.states.${stateKey(state)}`)} + + + ), + } + }) + + let note: React.ReactNode + let noteType: "secondary" | "warning" | "danger" = "secondary" + if (flag.retiredAt) { + note = t("features.retired") + } else if (!flag.available) { + note = t(`features.flags.${key}.notConfigured`, null, { + default: t("features.unavailable"), + }) + noteType = "warning" + } else if (saving) { + note = t("features.savingNote") + } else if (failed) { + note = t(`features.saveFailed.${stateKey(failed)}`, { + name, + state: t(`features.states.${stateKey(flag.state)}`), + }) + noteType = "danger" + } else if (!featureAdminPreview(key) && flag.state !== FeatureState.On) { + // Admins only is not offered; a flag already in it behaves as off + note = t("features.noAdminPreview") + } else { + note = t(`features.sees.${stateKey(flag.state)}`) + } + + return ( + + + {/* Scrolls instead of overflowing when a translation is long. */} +
+ onPick(value as FeatureState)} + /> +
+
+ + {locked ? : null} + {note} + + {failed && !saving ? ( + + + + + ) : null} +
+ ) +} diff --git a/@app/components/src/FeatureFlags/index.ts b/@app/components/src/FeatureFlags/index.ts new file mode 100644 index 000000000..604303a0b --- /dev/null +++ b/@app/components/src/FeatureFlags/index.ts @@ -0,0 +1 @@ +export * from "./FeatureFlagsAdmin" diff --git a/@app/components/src/FeatureFlags/transitions.ts b/@app/components/src/FeatureFlags/transitions.ts new file mode 100644 index 000000000..2e3f46750 --- /dev/null +++ b/@app/components/src/FeatureFlags/transitions.ts @@ -0,0 +1,100 @@ +import { FeatureState } from "@app/graphql" +import { featureAdminPreview } from "@app/lib" + +import type { + AdminFeatures_FeatureFlagEventFragment, + AdminFeatures_FeatureFlagFragment, +} from "@app/graphql" + +/** + * Rules of the Features page that do not depend on rendering. + */ + +export const FEATURE_STATES = [ + FeatureState.Off, + FeatureState.AdminsOnly, + FeatureState.On, +] as const + +/** The state as stored in the database and used in translation keys. */ +export const stateKey = (state: FeatureState) => + ({ + [FeatureState.Off]: "off", + [FeatureState.AdminsOnly]: "admins_only", + [FeatureState.On]: "on", + })[state] as "off" | "admins_only" | "on" + +/** + * What switching a flag from one state to another needs: + * - `none`: nothing changes. + * - `immediate`: Off <-> Admins only only affects admins; save at once. + * - `confirmOn`: everyone starts seeing the feature. + * - `confirmLeaveOn`: everyone but admins (or everyone) stops seeing it. + */ +export type Transition = "none" | "immediate" | "confirmOn" | "confirmLeaveOn" + +export const transition = (from: FeatureState, to: FeatureState): Transition => + from === to + ? "none" + : to === FeatureState.On + ? "confirmOn" + : from === FeatureState.On + ? "confirmLeaveOn" + : "immediate" + +export type FeatureFlagEvent = AdminFeatures_FeatureFlagEventFragment + +/** The events of one flag, newest first (the order the API returns). */ +export const eventsOf = ( + events: readonly (FeatureFlagEvent | null)[], + key: string +): FeatureFlagEvent[] => + events.filter((event): event is FeatureFlagEvent => event?.key === key) + +export interface PreviewInfo { + /** Whether Admins only lets admins preview the feature at all. */ + previewable: boolean + /** Whether admins have previewed the feature before it goes on. */ + previewed: boolean + /** The most recent switch into admins_only, if the audit log has one. */ + lastPreviewStart: FeatureFlagEvent | null +} + +/** + * Whether the flag has been in admins_only, according to the audit log, or is + * in it now. + */ +export const previewInfo = ( + flag: Pick, + flagEvents: readonly FeatureFlagEvent[] +): PreviewInfo => { + const lastPreviewStart = + flagEvents.find((event) => event.newState === FeatureState.AdminsOnly) ?? + null + return { + previewable: featureAdminPreview(flag.key), + previewed: + lastPreviewStart !== null || flag.state === FeatureState.AdminsOnly, + lastPreviewStart, + } +} + +/** + * Whether a state can be chosen for a flag. Off is always reachable; Admins + * only is not offered for a feature admins cannot preview. + */ +export const stateSelectable = ( + flag: Pick< + AdminFeatures_FeatureFlagFragment, + "key" | "available" | "retiredAt" + >, + state: FeatureState +): boolean => { + if (flag.retiredAt) { + return false + } + if (state === FeatureState.AdminsOnly && !featureAdminPreview(flag.key)) { + return false + } + return flag.available || state === FeatureState.Off +} diff --git a/@app/components/src/PaymentCard.tsx b/@app/components/src/PaymentCard.tsx new file mode 100644 index 000000000..115a84e5e --- /dev/null +++ b/@app/components/src/PaymentCard.tsx @@ -0,0 +1,234 @@ +import { PayPage_RegistrationPaymentFragment } from "@app/graphql" +import { formatEuro, PayPageState } from "@app/lib" +import { Alert, Button, Card, Space, Tag, theme, Typography } from "antd" +import dayjs from "dayjs" + +import { useTranslation } from "./hooks" +import { Link, PaymentNote, PriceBreakdown } from "." + +import type { CSSProperties, ReactNode } from "react" + +/** Event time as on the pay page design: full year and an en dash. */ +function formatEventTime(start: string, end: string) { + const format = "D.M.YYYY HH:mm" + return `${dayjs(start).format(format)} – ${dayjs(end).format(format)}` +} + +const { Text, Title } = Typography + +type CardState = Exclude + +// Tag text key and antd preset colour for each state (boards 4 and 5) +const TAGS: Record = { + unpaid: { key: "unpaid", color: "gold" }, + confirming: { key: "processing", color: "blue" }, + paid: { key: "paid", color: "green" }, + paidManually: { key: "paid", color: "green" }, + queued: { key: "inQueue", color: "blue" }, + opensLater: { key: "notOpen", color: "blue" }, + free: { key: "free" }, +} + +const detailsStyle: CSSProperties = { + display: "grid", + gridTemplateColumns: "minmax(80px, 140px) 1fr", + rowGap: 8, + columnGap: 12, +} + +function translated( + field: Record | null | undefined, + lang: string +): string { + return field?.[lang] || field?.en || field?.fi || "" +} + +interface PaymentCardProps { + payment: PayPage_RegistrationPaymentFragment + state: CardState + // The status query parameter Stripe returned with + returnStatus?: string | null + onPay: () => void + paying: boolean + error?: ReactNode +} + +/** The /pay page card (boards 4 and 5). */ +export const PaymentCard: React.FC = ({ + payment, + state, + returnStatus, + onPay, + paying, + error, +}) => { + const { t, lang } = useTranslation("payments") + const { token } = theme.useToken() + const divider = `1px solid ${token.colorSplit}` + const { + eventSlug, + eventName, + eventStartTime, + eventEndTime, + registrationEndTime, + quotaTitle, + firstName, + lastName, + priceCents, + serviceFeeCents, + totalCents, + paidTotalCents, + paidAt, + queuePosition, + } = payment + const euro = (cents: number | null | undefined) => + formatEuro(cents ?? 0, lang) + const date = (value: string | null | undefined) => + value ? dayjs(value).format("D.M.YYYY") : "" + const time = (value: string | null | undefined) => + value ? dayjs(value).format("HH:mm") : "" + + const payable = state === "unpaid" || state === "confirming" + const tag = TAGS[state] + + let body: ReactNode = null + let detail: ReactNode = null + switch (state) { + case "paid": + body = t("states.paid.body", { + amount: euro(paidTotalCents), + date: date(paidAt), + time: time(paidAt), + }) + detail = t("states.paid.detail") + break + case "paidManually": + body = t("states.paidManually.body") + break + case "queued": + body = t("states.queued.body", { position: queuePosition ?? "" }) + break + case "opensLater": + body = t("states.opensLater.body", { + date: date(registrationEndTime), + time: time(registrationEndTime), + }) + break + case "free": + body = t("states.free.body") + break + } + + return ( + + {state === "unpaid" && returnStatus === "cancelled" && ( + + )} + {state === "unpaid" && returnStatus === "success" && ( + + )} + {state === "confirming" && ( + + )} + + +
+ + {payable ? t("title") : t(`states.${state}.title`)} + + + {t(`tags.${tag.key}`)} + +
+
+ {t("event")} + + + {translated(eventName, lang)} + + + {t("time")} + {formatEventTime(eventStartTime, eventEndTime)} + {(firstName || lastName) && ( + <> + {t("name")} + {[firstName, lastName].filter(Boolean).join(" ")} + + )} + {t("quota")} + {translated(quotaTitle, lang)} +
+ {payable ? ( + <> +
+ +
+ {error} + {state === "unpaid" && ( + + )} + + ) : ( + + {body} + {detail && ( +
+ {detail} +
+ )} +
+ )} +
+
+
+ ) +} diff --git a/@app/components/src/PaymentSummary.tsx b/@app/components/src/PaymentSummary.tsx new file mode 100644 index 000000000..1d769b634 --- /dev/null +++ b/@app/components/src/PaymentSummary.tsx @@ -0,0 +1,92 @@ +import { formatEuro } from "@app/lib" +import { Typography } from "antd" + +import type { CSSProperties, ReactNode } from "react" + +const { Text } = Typography + +export const paymentBoxStyle: CSSProperties = { + border: "1px solid #d9e3f2", + background: "#f5faff", + borderRadius: 8, + padding: "12px 16px", + display: "flex", + flexDirection: "column", + gap: 6, +} + +const rowStyle: CSSProperties = { + display: "flex", + justifyContent: "space-between", + gap: 16, +} + +interface AmountRowProps { + label: ReactNode + cents: number + lang?: string + strong?: boolean + "data-cy"?: string +} + +/** One "label … 18,00 €" line of a price breakdown. */ +export const AmountRow: React.FC = ({ + label, + cents, + lang, + strong = false, + "data-cy": dataCy, +}) => ( +
+ {label} + {formatEuro(cents, lang)} +
+) + +interface PriceBreakdownProps { + ticketLabel: ReactNode + serviceFeeLabel: ReactNode + totalLabel: ReactNode + priceCents: number + serviceFeeCents: number + totalCents: number + lang?: string +} + +/** Ticket, service fee and total, as on boards 2 and 4. */ +export const PriceBreakdown: React.FC = ({ + ticketLabel, + serviceFeeLabel, + totalLabel, + priceCents, + serviceFeeCents, + totalCents, + lang, +}) => ( + <> + + + + +) + +export const PaymentNote: React.FC<{ children: ReactNode }> = ({ + children, +}) => ( + + {children} + +) diff --git a/@app/components/src/PreviewTag.tsx b/@app/components/src/PreviewTag.tsx new file mode 100644 index 000000000..697d3a2ca --- /dev/null +++ b/@app/components/src/PreviewTag.tsx @@ -0,0 +1,52 @@ +import { EyeOutlined } from "@ant-design/icons" +import { Space, Tag, Typography } from "antd" +import * as NextLink from "next/link" +import useTranslation from "next-translate/useTranslation" + +import { useFeatureFlags } from "./Feature" + +const { Text } = Typography + +// See SharedLayout.tsx for why the default export is read this way. +const Link = NextLink.default + +interface PreviewTagProps { + /** Only the tag, without the line on who can release the feature. */ + compact?: boolean +} + +/** + * Marks UI that the viewer sees only because its feature is in admins_only. + * Developers get a link to the Features page; other admins are told to ask a + * developer. + */ +export function PreviewTag({ compact = false }: PreviewTagProps) { + const { t } = useTranslation("common") + const { isDeveloper } = useFeatureFlags() + + const tag = ( + }> + {t("featurePreview.tag")} + + ) + if (compact) { + return tag + } + return ( + + {tag} + + {isDeveloper ? ( + <> + {t("featurePreview.developerHint")}{" "} + + {t("featurePreview.manage")} + + + ) : ( + t("featurePreview.adminHint") + )} + + + ) +} diff --git a/@app/components/src/ProgressBar.tsx b/@app/components/src/ProgressBar.tsx index 06e52d4ce..9ecc7348d 100644 --- a/@app/components/src/ProgressBar.tsx +++ b/@app/components/src/ProgressBar.tsx @@ -4,9 +4,16 @@ interface Props { percentageFilled: number filled: number size: number + /** Appended to the "filled / size" label, e.g. " · 3 in queue". */ + labelSuffix?: string } -export const ProgressBar = ({ percentageFilled, size, filled }: Props) => { +export const ProgressBar = ({ + percentageFilled, + size, + filled, + labelSuffix = "", +}: Props) => { const [color, setColor] = useState("#5eb95e") useEffect(() => { @@ -58,7 +65,7 @@ export const ProgressBar = ({ percentageFilled, size, filled }: Props) => { {`${ filled <= size ? filled.toString() : size - } / ${size}`} + } / ${size}${labelSuffix}`} ) } diff --git a/@app/components/src/SettingsLayout.tsx b/@app/components/src/SettingsLayout.tsx index 2572cc07d..c1ea6b1ed 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, @@ -21,6 +22,7 @@ import { import { Redirect, SettingsSideMenu, useIsMobile, useTranslation } from "." import type { User } from "@app/graphql" +import type { FeatureKey } from "@app/lib" import type { TextProps } from "antd/lib/typography/Text" const { Sider } = Layout @@ -30,9 +32,20 @@ interface SettingsPageSpec { cy: string warnIfUnverified?: boolean titleProps?: TextProps + /** + * Left out of the menu while this feature is off; the page itself decides + * what it shows. + */ + feature?: FeatureKey } export const pages = (t: Translate) => ({ + "/settings/reminders": { + title: t("titles.reminders"), + icon: , + cy: "settingslayout-link-reminders", + feature: "registration_reminders", + } as SettingsPageSpec, "/settings/profile": { title: t("titles.index"), icon: , diff --git a/@app/components/src/SettingsSideMenu.tsx b/@app/components/src/SettingsSideMenu.tsx index f0c20cc28..72b434e7b 100644 --- a/@app/components/src/SettingsSideMenu.tsx +++ b/@app/components/src/SettingsSideMenu.tsx @@ -1,7 +1,7 @@ import { Menu, Typography } from "antd" import { pages } from "./SettingsLayout" -import { Link, Warn } from "." +import { Link, useFeatureFlags, Warn } from "." import type { User } from "@app/graphql" import type { MenuProps } from "antd" @@ -19,7 +19,12 @@ export const SettingsSideMenu: React.FC = ({ items, initialKey, }) => { - const menuItems: MenuProps["items"] = Object.keys(items).map((pageHref) => { + const { enabled } = useFeatureFlags() + const visible = Object.keys(items).filter((pageHref) => { + const { feature } = items[pageHref] + return !feature || enabled.includes(feature) + }) + const menuItems: MenuProps["items"] = visible.map((pageHref) => { const { cy, icon, warnIfUnverified, titleProps, title } = items[pageHref] return { key: pageHref, diff --git a/@app/components/src/SharedLayout.tsx b/@app/components/src/SharedLayout.tsx index da145e6e2..c551ca4f1 100644 --- a/@app/components/src/SharedLayout.tsx +++ b/@app/components/src/SharedLayout.tsx @@ -26,6 +26,11 @@ import { CombinedError, UseQueryState } from "urql" import headerLogo from "../assets/header-logo.png" +import { + featureEnabledIn, + FeatureFlagsProvider, + isDeveloperUser, +} from "./Feature" import { ErrorResult, H3, @@ -66,6 +71,8 @@ export enum AuthRestrict { LOGGED_OUT = 1 << 0, LOGGED_IN = 1 << 1, NOT_ADMIN = 1 << 2, + /** Not an admin with the developer role (feature flag management). */ + NOT_DEVELOPER = 1 << 3, } export interface SharedLayoutProps { @@ -116,6 +123,7 @@ export function SharedLayout({ const forbidsLoggedIn = forbidWhen & AuthRestrict.LOGGED_IN const forbidsLoggedOut = forbidWhen & AuthRestrict.LOGGED_OUT const forbidsNotAdmin = forbidWhen & AuthRestrict.NOT_ADMIN + const forbidsNotDeveloper = forbidWhen & AuthRestrict.NOT_DEVELOPER const isSSR = typeof window === "undefined" @@ -163,7 +171,9 @@ export function SharedLayout({ if ( data && data.currentUser && - (forbidsLoggedIn || (forbidsNotAdmin && !data.currentUser.isAdmin)) + (forbidsLoggedIn || + (forbidsNotAdmin && !data.currentUser.isAdmin) || + (forbidsNotDeveloper && !isDeveloperUser(data.currentUser))) ) { if (!isSSR && !noHandleErrors) { // Antd messages don't work with SSR @@ -188,6 +198,9 @@ export function SharedLayout({ } const { data, fetching, error, stale } = query + // This layout provides the flags to its children, so it reads its own + // from the same query instead of useFeature + const registrationReminders = featureEnabledIn(data, "registration_reminders") /* * This will set up a GraphQL subscription monitoring for changes to the @@ -203,164 +216,189 @@ export function SharedLayout({ }) return ( - -
- - {title ? `${title} — ${projectName}` : projectName} - - - - - Prodeko - - - {!isMobile ? ( - -

- {titleHref ? ( + + +
+ + {title ? `${title} — ${projectName}` : projectName} + + + + + Prodeko + + + {!isMobile ? ( + +

+ {titleHref ? ( + + {title} + + ) : ( + title + )} +

+ + ) : null} + + + + {data && data.currentUser ? ( + + {t("admin")} + + ), + }, + ] + : []), + { + key: "settings", + label: ( + + + {t("settings")} + + + ), + }, + ...(registrationReminders + ? [ + { + key: "reminders", + label: ( + + {t("reminders")} + + ), + }, + ] + : []), + { + key: "logout", + label: {t("logout")}, + }, + ], + }} + trigger={["click"]} + > + + {data?.currentUser?.name?.[0] || "?"} + + + {data.currentUser.name} + + + + + + ) : forbidsLoggedIn ? null : ( - {title} + {t("signin")} - ) : ( - title )} -

+ - ) : null} - - - - {data && data.currentUser ? ( - - {t("admin")} - - ), - }, - ] - : []), - { - key: "settings", - label: ( - - - {t("settings")} - - - ), - }, - { - key: "logout", - label: {t("logout")}, - }, - ], - }} - trigger={["click"]} - > - - {data?.currentUser?.name?.[0] || "?"} - - - {data.currentUser.name} - - - - - - ) : forbidsLoggedIn ? null : ( - - {t("signin")} - - )} - - -
-
- - {sider ? sider : null} - - {renderChildren({ - error, - stale, - fetching, - currentUser: data?.currentUser, - })} - - + + + + {sider ? sider : null} + {/* Without the footer the content fills the rest of the window, so + the light body background doesn't show below short pages */} + + {renderChildren({ + error, + stale, + fetching, + currentUser: data?.currentUser, + })} + + - {displayFooter && ( -
- - - - - © {new Date().getFullYear()} {orgName}{" "} - - - {process.env.PRIVACY_URL && ( - + {displayFooter && ( + - )} - + {process.env.PRIVACY_URL && ( + + + + + {t("privacyPolicy")} + + + + + )} + + +
+ )} +
+ ) } diff --git a/@app/components/src/celebrate.ts b/@app/components/src/celebrate.ts new file mode 100644 index 000000000..4ea10fbde --- /dev/null +++ b/@app/components/src/celebrate.ts @@ -0,0 +1,31 @@ +import { useFeature } from "./Feature" + +/** + * Shoots confetti from both bottom corners of the screen, e.g. after an + * event or a registration has been created. The confetti is drawn on its + * own canvas over the page, so it keeps going through a page change. + * Nothing is shown to users who prefer reduced motion. + */ +async function celebrate() { + // Loaded on demand: the library needs the browser and is only used here + const { default: confetti } = await import("canvas-confetti") + const shared = { + particleCount: 80, + spread: 70, + startVelocity: 55, + disableForReducedMotion: true, + } + confetti({ ...shared, angle: 60, origin: { x: 0, y: 1 } }) + confetti({ ...shared, angle: 120, origin: { x: 1, y: 1 } }) +} + +async function noCelebration() {} + +/** + * Returns the function to call after a new event or registration has been + * saved (also from the registration form preview). + */ +export function useCelebrate() { + const withConfetti = useFeature("confetti") + return withConfetti ? celebrate : noCelebration +} diff --git a/@app/components/src/index.tsx b/@app/components/src/index.tsx index 6ff860e32..e41e6ce78 100644 --- a/@app/components/src/index.tsx +++ b/@app/components/src/index.tsx @@ -17,6 +17,8 @@ export * from "./EventQuotasCard" export * from "./EventRegistrationAnswersPopover" export * from "./EventRegistrationForm" export * from "./EventRegistrationsTables" +export * from "./Feature" +export * from "./FeatureFlags" export * from "./FileUpload" export * from "./FourOhFour" export * from "./Head" @@ -27,6 +29,9 @@ export * from "./LocaleSelect" export * from "./OrganizationMembers" export * from "./PageHeader" export * from "./PasswordStrength" +export * from "./PaymentCard" +export * from "./PaymentSummary" +export * from "./PreviewTag" export * from "./ProdekoIcon" export * from "./ProgressBar" export * from "./RecentRegistrationsList" diff --git a/@app/components/tsconfig.test.json b/@app/components/tsconfig.test.json new file mode 100644 index 000000000..944233385 --- /dev/null +++ b/@app/components/tsconfig.test.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.test.json", + "compilerOptions": { + "jsx": "react-jsx", + // Transpile only: `tsc -b` type-checks the components, and a type-checking + // ts-jest program for them (antd's types) costs the shared in-band jest + // process about 250 MB of heap. + "isolatedModules": true + } +} diff --git a/@app/config/extra.js b/@app/config/extra.js index 198a0e0ee..3166b8951 100644 --- a/@app/config/extra.js +++ b/@app/config/extra.js @@ -31,7 +31,9 @@ process.env.SHADOW_AUTH_DATABASE_URL = process.env.SHADOW_AUTH_DATABASE_URL process.env.TEST_DATABASE_URL = `postgres://${process.env.DATABASE_OWNER}:${process.env.DATABASE_OWNER_PASSWORD}@${process.env.DATABASE_HOST}/${process.env.DATABASE_NAME}_test` // Use a different redis database in tests -process.env.TEST_REDIS_URL = `${process.env.REDIS_URL}/1` +// An explicit TEST_REDIS_URL lets parallel test runs use separate redis dbs +process.env.TEST_REDIS_URL = + process.env.TEST_REDIS_URL || `${process.env.REDIS_URL}/1` // https://docs.cypress.io/guides/guides/environment-variables.html#Option-3-CYPRESS process.env.CYPRESS_ROOT_URL = process.env.ROOT_URL diff --git a/@app/db/.gmrc b/@app/db/.gmrc index 52b4fcc02..0e3168a9e 100644 --- a/@app/db/.gmrc +++ b/@app/db/.gmrc @@ -69,7 +69,7 @@ "!afterReset.sql", { "_": "command", - "command": "DATABASE_URL=\"$GM_DBURL\" pnpm --filter @app/worker run install-db-schema" + "command": "cross-env DATABASE_URL=\"$GM_DBURL\" pnpm --filter @app/worker run install-db-schema" } ], diff --git a/@app/db/__tests__/app_private/functions/link_or_register_user.test.ts b/@app/db/__tests__/app_private/functions/link_or_register_user.test.ts index 77905771f..234d6d6b2 100644 --- a/@app/db/__tests__/app_private/functions/link_or_register_user.test.ts +++ b/@app/db/__tests__/app_private/functions/link_or_register_user.test.ts @@ -51,9 +51,12 @@ describe("when account doesn't already exist", () => { { "avatar_url": "http://example.com/avatar.jpg", "created_at": "[DATE]", + "first_name": null, "id": "[ID]", "is_admin": false, + "is_developer": false, "is_verified": true, + "last_name": null, "name": "Webbitiimi", "updated_at": "[DATE]", "username": "webbitiimi", diff --git a/@app/db/__tests__/app_private/functions/login.test.ts b/@app/db/__tests__/app_private/functions/login.test.ts index a72382c7b..e7e872005 100644 --- a/@app/db/__tests__/app_private/functions/login.test.ts +++ b/@app/db/__tests__/app_private/functions/login.test.ts @@ -37,7 +37,9 @@ it("can login with username+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -53,7 +55,9 @@ it("can login with uSeRnAmE+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -69,7 +73,9 @@ it("can login with email+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -85,7 +91,9 @@ it("can login with EmAiL+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } diff --git a/@app/db/__tests__/app_private/functions/really_create_user.test.ts b/@app/db/__tests__/app_private/functions/really_create_user.test.ts index 88d2326a7..d2e0da2cf 100644 --- a/@app/db/__tests__/app_private/functions/really_create_user.test.ts +++ b/@app/db/__tests__/app_private/functions/really_create_user.test.ts @@ -47,9 +47,12 @@ test("can register user with a password", () => { "avatar_url": "http://example.com", "created_at": "[DATE]", + "first_name": null, "id": "[ID]", "is_admin": false, + "is_developer": false, "is_verified": false, + "last_name": null, "name": "Test One", "updated_at": "[DATE]", "username": "testuser", @@ -89,9 +92,12 @@ test("can register user with just a username and email", () => { "avatar_url": null, "created_at": "[DATE]", + "first_name": null, "id": "[ID]", "is_admin": false, + "is_developer": false, "is_verified": false, + "last_name": null, "name": null, "updated_at": "[DATE]", "username": "testuser", diff --git a/@app/db/__tests__/app_private/functions/set_feature_available.test.ts b/@app/db/__tests__/app_private/functions/set_feature_available.test.ts new file mode 100644 index 000000000..79598911f --- /dev/null +++ b/@app/db/__tests__/app_private/functions/set_feature_available.test.ts @@ -0,0 +1,59 @@ +import { + upsertFeatureFlag, + withDeveloperUserDb, + withRootDb, +} from "../../helpers" + +describe("app_private.set_feature_available", () => { + it("sets availability without touching the state change timestamp", () => + withRootDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + await client.query( + "update app_public.feature_flags set updated_at = '2020-01-01T00:00:00Z' where key = 'test_flag'" + ) + + const { + rows: [{ found }], + } = await client.query( + "select app_private.set_feature_available('test_flag', false) as found" + ) + expect(found).toBe(true) + + const { + rows: [flag], + } = await client.query( + "select available, state, updated_at from app_public.feature_flags where key = 'test_flag'" + ) + expect(flag.available).toBe(false) + expect(flag.state).toBe("on") + expect(flag.updated_at.toISOString()).toBe( + new Date("2020-01-01").toISOString() + ) + + const { + rows: [{ enabled }], + } = await client.query( + "select app_public.feature_enabled('test_flag') as enabled" + ) + expect(enabled).toBe(false) + })) + + it("returns false for an unknown key", () => + withRootDb(async (client) => { + const { + rows: [{ found }], + } = await client.query( + "select app_private.set_feature_available('test_does_not_exist', true) as found" + ) + expect(found).toBe(false) + })) + + it("cannot be called by the visitor role, even by developers", () => + withDeveloperUserDb(async (client) => { + await expect( + client.query( + "select app_private.set_feature_available('test_flag', true)" + ) + ).rejects.toThrow("permission denied") + })) +}) diff --git a/@app/db/__tests__/app_public/functions/admin_preview_features.test.ts b/@app/db/__tests__/app_public/functions/admin_preview_features.test.ts new file mode 100644 index 000000000..4781d72e6 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/admin_preview_features.test.ts @@ -0,0 +1,52 @@ +import { PoolClient } from "pg" + +import { + upsertFeatureFlag, + withAdminUserDb, + withAnonymousDb, + withUserDb, +} from "../../helpers" + +const previewFeatures = async (client: PoolClient) => { + const { rows } = await client.query( + "select key from app_public.admin_preview_features() as key" + ) + return rows.map((r) => r.key as string) +} + +const seedFlags = async (client: PoolClient) => { + await upsertFeatureFlag(client, "test_off", "off") + await upsertFeatureFlag(client, "test_admins_only", "admins_only") + await upsertFeatureFlag(client, "test_on", "on") + await upsertFeatureFlag(client, "test_unavailable", "admins_only", { + available: false, + }) + await upsertFeatureFlag(client, "test_retired", "admins_only", { + retired: true, + }) +} + +describe("app_public.admin_preview_features", () => { + it("lists only available, unretired admins_only keys to admins", () => + withAdminUserDb(async (client) => { + await seedFlags(client) + const keys = await previewFeatures(client) + expect(keys).toContain("test_admins_only") + expect(keys).not.toContain("test_off") + expect(keys).not.toContain("test_on") + expect(keys).not.toContain("test_unavailable") + expect(keys).not.toContain("test_retired") + })) + + it("is empty for regular users", () => + withUserDb(async (client) => { + await seedFlags(client) + expect(await previewFeatures(client)).toEqual([]) + })) + + it("is empty for anonymous users", () => + withAnonymousDb(async (client) => { + await seedFlags(client) + expect(await previewFeatures(client)).toEqual([]) + })) +}) diff --git a/@app/db/__tests__/app_public/functions/event_input_round_trip.test.ts b/@app/db/__tests__/app_public/functions/event_input_round_trip.test.ts new file mode 100644 index 000000000..60db673f2 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/event_input_round_trip.test.ts @@ -0,0 +1,537 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + createEventCategories, + createOrganizations, + upsertFeatureFlag, + withAdminUserDb, +} from "../../helpers" + +/* + * Round-trip test for the event write path. + * + * `app_public.create_event` and `app_public.update_event` are redefined in + * full whenever an attribute is added to one of their input types. A body + * written on top of an older version silently stops persisting an attribute + * that another change added. This test reads the attributes of every input + * type from the catalog, sends a value for each one through both functions + * and reads the stored rows back, so a new attribute is covered without + * editing this file, as long as a value generator exists for its type. + * + * Every event is written twice: created with one variant of the values and + * updated with the other. Two events run the variants in opposite order, so + * both values of every attribute go through both functions. The variants + * differ for every attribute, which makes an update that keeps the old value + * fail, and one of them always differs from the column default, which makes + * a create that leaves the column out fail. + * + * Adding an attribute: if its type has no entry in GENERATORS_BY_TYPE, add + * one there (or, when the attribute has constraints of its own, a per + * attribute entry in OVERRIDES). An attribute that is deliberately not stored + * in a column of the same name goes into NOT_COLUMNS with the reason. + */ + +type Variant = 0 | 1 + +interface InputType { + /** Composite type in app_public that create_event / update_event take. */ + name: string + /** Table in app_public that stores the attributes. */ + table: string +} + +const EVENT_INPUT: InputType = { name: "event_input", table: "events" } +const CREATE_QUOTAS: InputType = { + name: "create_event_quotas", + table: "quotas", +} +const UPDATE_QUOTAS: InputType = { + name: "update_event_quotas", + table: "quotas", +} +const CREATE_QUESTIONS: InputType = { + name: "create_event_questions", + table: "event_questions", +} +const UPDATE_QUESTIONS: InputType = { + name: "update_event_questions", + table: "event_questions", +} +const INPUT_TYPES = [ + EVENT_INPUT, + CREATE_QUOTAS, + UPDATE_QUOTAS, + CREATE_QUESTIONS, + UPDATE_QUESTIONS, +] + +interface Attribute { + name: string + /** Schema qualified type name, `[]` appended for arrays. */ + type: string + /** Labels in sort order when the type is an enum. */ + enumLabels: string[] | null + /** Whether the table has a column of the same name and (base) type. */ + hasColumn: boolean +} + +interface GeneratorContext { + variant: Variant + /** Unique per event, keeps unique columns (slug) apart. */ + tag: string + attribute: Attribute + organizationIds: [string, string] + categoryIds: [string, string] + /** Id of the existing quota or question row in an update. */ + rowId: string | null +} + +type Generator = (ctx: GeneratorContext) => unknown + +const text = ({ attribute, tag, variant }: GeneratorContext) => + `${attribute.name}-${tag}-v${variant}` + +const translated = (ctx: GeneratorContext) => ({ + fi: `${text(ctx)} fi`, + en: `${text(ctx)} en`, +}) + +const BASE_TIME = Date.parse("2031-03-03T12:00:00Z") +const HOUR = 60 * 60 * 1000 +const DAY = 24 * HOUR +const timeAt = + (days: number): Generator => + ({ variant }) => + new Date(BASE_TIME + days * DAY + variant * HOUR).toISOString() + +/* + * Values by type. Each generator returns a different value for variant 0 and + * variant 1. Values are sent as JSON and converted with + * jsonb_populate_record, so they use the JSON form of the type. Enums need + * no entry: they take their first and second label. + */ +const GENERATORS_BY_TYPE: Record = { + "pg_catalog.text": text, + "public.citext": text, + "pg_catalog.bool": ({ variant }) => variant === 1, + "pg_catalog.int2": ({ variant }) => 100 + variant, + "pg_catalog.int4": ({ variant }) => 100 + variant, + "pg_catalog.jsonb": (ctx) => ({ [ctx.attribute.name]: text(ctx) }), + "pg_catalog.timestamptz": timeAt(30), + "app_public.translated_field": translated, + "app_public.translated_field[]": (ctx) => [translated(ctx)], +} + +/* + * Values for single attributes whose constraints a value by type cannot + * meet: ordered timestamps, foreign keys, the id an update matches on, + * jsonb stored in a translated_field column and question types, options and + * prefills that depend on each other. + */ +const rowId: Generator = ({ rowId }) => rowId +// Only a TEXT question can prefill its answer, and a TEXT question has no +// answer options, so variant 0 is a prefilled TEXT question and variant 1 a +// RADIO question with options +const questionType: Generator = ({ variant }) => + (["TEXT", "RADIO"] as const)[variant] +const questionData: Generator = (ctx) => + ctx.variant === 0 ? null : [translated(ctx)] +const questionPrefill: Generator = ({ variant }) => + variant === 0 ? "TELEGRAM" : null +const questionOverrides = { + type: questionType, + data: questionData, + prefill: questionPrefill, +} + +const OVERRIDES: Record> = { + [EVENT_INPUT.name]: { + registration_start_time: timeAt(0), + registration_end_time: timeAt(1), + event_start_time: timeAt(2), + event_end_time: timeAt(3), + owner_organization_id: ({ organizationIds, variant }) => + organizationIds[variant], + category_id: ({ categoryIds, variant }) => categoryIds[variant], + }, + // Typed jsonb in the input, stored in a translated_field column + [CREATE_QUOTAS.name]: { title: translated }, + [UPDATE_QUOTAS.name]: { id: rowId, title: translated }, + [CREATE_QUESTIONS.name]: questionOverrides, + [UPDATE_QUESTIONS.name]: { id: rowId, ...questionOverrides }, +} + +/* + * Attributes that are deliberately not stored in a column of the same name, + * with the reason. They are sent as null and not read back. + */ +const NOT_COLUMNS: Record> = {} + +/******************************************************************************/ + +async function loadAttributes( + client: PoolClient, + inputType: InputType +): Promise { + const { rows } = await client.query( + `select + a.attname as name, + case + when et.oid is not null then etn.nspname || '.' || et.typname || '[]' + else tn.nspname || '.' || t.typname + end as type, + case when t.typtype = 'e' then array( + select e.enumlabel::text from pg_catalog.pg_enum as e + where e.enumtypid = t.oid order by e.enumsortorder + ) end as enum_labels, + c.attname is not null as has_column + from pg_catalog.pg_attribute as a + join pg_catalog.pg_type as t on t.oid = a.atttypid + join pg_catalog.pg_namespace as tn on tn.oid = t.typnamespace + left join pg_catalog.pg_type as et + on t.typcategory = 'A' and et.oid = t.typelem + left join pg_catalog.pg_namespace as etn on etn.oid = et.typnamespace + left join ( + pg_catalog.pg_attribute as c + join pg_catalog.pg_type as ct on ct.oid = c.atttypid + ) + on c.attrelid = to_regclass('app_public.' || $2) + and c.attname = a.attname + and c.attnum > 0 + and not c.attisdropped + -- A domain column (translated_field) may take an attribute of its + -- base type (jsonb) + and a.atttypid in (c.atttypid, ct.typbasetype) + where a.attrelid = to_regclass('app_public.' || $1) + and a.attnum > 0 + and not a.attisdropped + order by a.attnum`, + [inputType.name, inputType.table] + ) + return rows.map((row) => ({ + name: row.name, + type: row.type, + enumLabels: row.enum_labels, + hasColumn: row.has_column, + })) +} + +function generatorFor( + inputType: InputType, + attribute: Attribute +): Generator | null { + const override = OVERRIDES[inputType.name]?.[attribute.name] + if (override) { + return override + } + if (attribute.enumLabels && attribute.enumLabels.length >= 2) { + const labels = attribute.enumLabels + return ({ variant }) => labels[variant] + } + return GENERATORS_BY_TYPE[attribute.type] ?? null +} + +const isRoundTripped = (inputType: InputType, attribute: Attribute) => + !NOT_COLUMNS[inputType.name]?.[attribute.name] + +/** Problems that stop the round trip before any function is called. */ +function setupProblems( + inputType: InputType, + attributes: Attribute[] +): string[] { + const where = `app_public.${inputType.name}` + if (attributes.length === 0) { + return [ + `${where} has no attributes or does not exist. Update INPUT_TYPES in this test.`, + ] + } + return attributes.flatMap((attribute) => { + if (!isRoundTripped(inputType, attribute)) { + return [] + } + const problems: string[] = [] + if (!generatorFor(inputType, attribute)) { + problems.push( + `${where}.${attribute.name} (${attribute.type}) has no value generator. ` + + `Add one for the type to GENERATORS_BY_TYPE, or for the attribute to OVERRIDES, in this test.` + ) + } + if (!attribute.hasColumn) { + problems.push( + `${where}.${attribute.name} (${attribute.type}) has no column of the same name and type in app_public.${inputType.table}. ` + + `Add the column, or list the attribute in NOT_COLUMNS in this test with the reason.` + ) + } + return problems + }) +} + +function buildInput( + inputType: InputType, + attributes: Attribute[], + ctx: Omit +): Record { + const input: Record = {} + for (const attribute of attributes) { + if (!isRoundTripped(inputType, attribute)) { + input[attribute.name] = null + continue + } + const generator = generatorFor(inputType, attribute) + if (!generator) { + throw new Error( + `No value generator for app_public.${inputType.name}.${attribute.name} (${attribute.type})` + ) + } + input[attribute.name] = generator({ ...ctx, attribute }) + } + return input +} + +/** The input as Postgres stores it, in the JSON form of to_jsonb. */ +async function normalize( + client: PoolClient, + inputType: InputType, + input: Record +): Promise> { + const { + rows: [{ value }], + } = await client.query( + `select to_jsonb(jsonb_populate_record(null::app_public.${inputType.name}, $1::jsonb)) as value`, + [JSON.stringify(input)] + ) + return value +} + +async function readRows( + client: PoolClient, + table: string, + column: "id" | "event_id", + id: string +): Promise[]> { + const { rows } = await asRoot(client, () => + client.query( + `select to_jsonb(t) as value from app_public.${table} as t where t.${column} = $1`, + [id] + ) + ) + return rows.map((row) => row.value) +} + +/******************************************************************************/ + +describe("Round trip of event input types through create_event and update_event", () => { + it("every input attribute has a value generator and a column", () => + withAdminUserDb(async (client) => { + const problems: string[] = [] + for (const inputType of INPUT_TYPES) { + const attributes = await loadAttributes(client, inputType) + problems.push(...setupProblems(inputType, attributes)) + } + expect(problems).toEqual([]) + })) + + it("create_event and update_event persist every input attribute", () => + withAdminUserDb(async (client, user) => { + const [organization0, organization1] = await createOrganizations( + client, + 2 + ) + const [category0] = await createEventCategories( + client, + 1, + organization0.id + ) + const [category1] = await createEventCategories( + client, + 1, + organization1.id + ) + // The fixture helpers switch to the root role, run as the admin again + await becomeUser(client, user.id) + // Quota prices are refused while payments are off + await upsertFeatureFlag(client, "payments", "on") + + const attributes: Record = {} + const problems: string[] = [] + for (const inputType of INPUT_TYPES) { + attributes[inputType.name] = await loadAttributes(client, inputType) + problems.push(...setupProblems(inputType, attributes[inputType.name])) + } + if (problems.length > 0) { + throw new Error(problems.join("\n")) + } + + const runId = Date.now().toString(36) + const failures: string[] = [] + + const input = async ( + inputType: InputType, + variant: Variant, + tag: string, + rowId: string | null = null + ) => { + const raw = buildInput(inputType, attributes[inputType.name], { + variant, + tag, + organizationIds: [organization0.id, organization1.id], + categoryIds: [category0.id, category1.id], + rowId, + }) + return { raw, sent: await normalize(client, inputType, raw) } + } + + const compare = ( + fn: string, + inputType: InputType, + sent: Record, + stored: Record[] + ) => { + if (stored.length !== 1) { + failures.push( + `${fn}: expected 1 row in app_public.${inputType.table}, found ${stored.length}` + ) + return + } + for (const attribute of attributes[inputType.name]) { + if (!isRoundTripped(inputType, attribute)) { + continue + } + const expected = sent[attribute.name] + const actual = stored[0][attribute.name] + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + failures.push( + `${fn} did not persist app_public.${inputType.name}.${attribute.name}: ` + + `sent ${JSON.stringify(expected)}, stored ${JSON.stringify(actual)}` + ) + } + } + } + + const checkVariantsDiffer = ( + inputType: InputType, + first: Record, + second: Record + ) => { + for (const attribute of attributes[inputType.name]) { + if ( + isRoundTripped(inputType, attribute) && + OVERRIDES[inputType.name]?.[attribute.name] !== rowId && + JSON.stringify(first[attribute.name]) === + JSON.stringify(second[attribute.name]) + ) { + failures.push( + `The value generator for app_public.${inputType.name}.${attribute.name} ` + + `returns the same value for both variants, so update_event is not tested for it` + ) + } + } + } + + for (const createVariant of [0, 1] as const) { + const updateVariant: Variant = createVariant === 0 ? 1 : 0 + const tag = `${runId}-e${createVariant}` + + // create_event + const event = await input(EVENT_INPUT, createVariant, tag) + const quota = await input(CREATE_QUOTAS, createVariant, tag) + const question = await input(CREATE_QUESTIONS, createVariant, tag) + const { + rows: [{ id: eventId }], + } = await client.query( + `select (app_public.create_event( + jsonb_populate_record(null::app_public.event_input, $1::jsonb), + array[jsonb_populate_record(null::app_public.create_event_quotas, $2::jsonb)], + array[jsonb_populate_record(null::app_public.create_event_questions, $3::jsonb)] + )).id`, + [ + JSON.stringify(event.raw), + JSON.stringify(quota.raw), + JSON.stringify(question.raw), + ] + ) + const createdQuotas = await readRows( + client, + "quotas", + "event_id", + eventId + ) + const createdQuestions = await readRows( + client, + "event_questions", + "event_id", + eventId + ) + compare( + "create_event", + EVENT_INPUT, + event.sent, + await readRows(client, "events", "id", eventId) + ) + compare("create_event", CREATE_QUOTAS, quota.sent, createdQuotas) + compare( + "create_event", + CREATE_QUESTIONS, + question.sent, + createdQuestions + ) + if (createdQuotas.length !== 1 || createdQuestions.length !== 1) { + break + } + + // update_event, with the other variant + const newEvent = await input(EVENT_INPUT, updateVariant, tag) + const newQuota = await input( + UPDATE_QUOTAS, + updateVariant, + tag, + createdQuotas[0].id as string + ) + const newQuestion = await input( + UPDATE_QUESTIONS, + updateVariant, + tag, + createdQuestions[0].id as string + ) + checkVariantsDiffer(EVENT_INPUT, event.sent, newEvent.sent) + checkVariantsDiffer(UPDATE_QUOTAS, quota.sent, newQuota.sent) + checkVariantsDiffer(UPDATE_QUESTIONS, question.sent, newQuestion.sent) + await client.query( + `select app_public.update_event( + $1::uuid, + jsonb_populate_record(null::app_public.event_input, $2::jsonb), + array[jsonb_populate_record(null::app_public.update_event_quotas, $3::jsonb)], + array[jsonb_populate_record(null::app_public.update_event_questions, $4::jsonb)] + )`, + [ + eventId, + JSON.stringify(newEvent.raw), + JSON.stringify(newQuota.raw), + JSON.stringify(newQuestion.raw), + ] + ) + compare( + "update_event", + EVENT_INPUT, + newEvent.sent, + await readRows(client, "events", "id", eventId) + ) + compare( + "update_event", + UPDATE_QUOTAS, + newQuota.sent, + await readRows(client, "quotas", "event_id", eventId) + ) + compare( + "update_event", + UPDATE_QUESTIONS, + newQuestion.sent, + await readRows(client, "event_questions", "event_id", eventId) + ) + } + + expect(failures).toEqual([]) + })) +}) diff --git a/@app/db/__tests__/app_public/functions/feature_enabled.test.ts b/@app/db/__tests__/app_public/functions/feature_enabled.test.ts new file mode 100644 index 000000000..f0056bfda --- /dev/null +++ b/@app/db/__tests__/app_public/functions/feature_enabled.test.ts @@ -0,0 +1,125 @@ +import { PoolClient } from "pg" + +import { + becomeUser, + createUsers, + upsertFeatureFlag, + withAdminUserDb, + withAnonymousDb, + withRootDb, + withUserDb, +} from "../../helpers" + +const isEnabled = async (client: PoolClient, key: string) => { + const { + rows: [row], + } = await client.query("select app_public.feature_enabled($1) as enabled", [ + key, + ]) + return row.enabled as boolean +} + +const enabledFeatures = async (client: PoolClient) => { + const { rows } = await client.query( + "select key from app_public.enabled_features() as key" + ) + return rows.map((r) => r.key as string) +} + +const seedFlags = async (client: PoolClient) => { + await upsertFeatureFlag(client, "test_off", "off") + await upsertFeatureFlag(client, "test_admins_only", "admins_only") + await upsertFeatureFlag(client, "test_on", "on") + await upsertFeatureFlag(client, "test_unavailable", "on", { + available: false, + }) + await upsertFeatureFlag(client, "test_retired", "off", { + available: false, + retired: true, + }) +} + +describe("app_public.feature_enabled", () => { + it("reads an unknown key as off", () => + withAdminUserDb(async (client) => { + expect(await isEnabled(client, "test_does_not_exist")).toBe(false) + })) + + it("reads an off flag as off, also for admins", () => + withAdminUserDb(async (client) => { + await upsertFeatureFlag(client, "test_off", "off") + expect(await isEnabled(client, "test_off")).toBe(false) + })) + + it("reads an on flag as on for anonymous users", () => + withAnonymousDb(async (client) => { + await upsertFeatureFlag(client, "test_on", "on") + expect(await isEnabled(client, "test_on")).toBe(true) + })) + + it("enables an admins_only flag for admins only", () => + withRootDb(async (client) => { + await upsertFeatureFlag(client, "test_admins_only", "admins_only") + const [user, admin] = [ + ...(await createUsers(client, 1)), + ...(await createUsers(client, 1, true, true)), + ] + + await becomeUser(client, admin.id) + expect(await isEnabled(client, "test_admins_only")).toBe(true) + + await becomeUser(client, user.id) + expect(await isEnabled(client, "test_admins_only")).toBe(false) + + await becomeUser(client, null) + expect(await isEnabled(client, "test_admins_only")).toBe(false) + })) + + it("reads an unavailable flag as off even when its state is on", () => + withAdminUserDb(async (client) => { + await upsertFeatureFlag(client, "test_unavailable", "on", { + available: false, + }) + expect(await isEnabled(client, "test_unavailable")).toBe(false) + })) + + it("reads a retired flag as on whatever its state and availability", () => + withAnonymousDb(async (client) => { + await upsertFeatureFlag(client, "test_retired", "off", { + available: false, + retired: true, + }) + expect(await isEnabled(client, "test_retired")).toBe(true) + })) +}) + +describe("app_public.enabled_features", () => { + it("lists only keys enabled for everyone to anonymous users", () => + withAnonymousDb(async (client) => { + await seedFlags(client) + const keys = await enabledFeatures(client) + expect(keys).toEqual(expect.arrayContaining(["test_on", "test_retired"])) + expect(keys).not.toContain("test_off") + expect(keys).not.toContain("test_admins_only") + expect(keys).not.toContain("test_unavailable") + })) + + it("lists only keys enabled for everyone to regular users", () => + withUserDb(async (client) => { + await seedFlags(client) + const keys = await enabledFeatures(client) + expect(keys).toContain("test_on") + expect(keys).not.toContain("test_admins_only") + })) + + it("adds admins_only keys for admins", () => + withAdminUserDb(async (client) => { + await seedFlags(client) + const keys = await enabledFeatures(client) + expect(keys).toEqual( + expect.arrayContaining(["test_on", "test_retired", "test_admins_only"]) + ) + expect(keys).not.toContain("test_off") + expect(keys).not.toContain("test_unavailable") + })) +}) diff --git a/@app/db/__tests__/app_public/functions/payment_actions.test.ts b/@app/db/__tests__/app_public/functions/payment_actions.test.ts new file mode 100644 index 000000000..de7e9be3f --- /dev/null +++ b/@app/db/__tests__/app_public/functions/payment_actions.test.ts @@ -0,0 +1,504 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + createUsers, + getJobs, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withAdminUserDb, + withRootDb, +} from "../../helpers" +import { + createOrganizationMember, + createPaidEventData, + insertPayment, + register, +} from "../../payments" + +// The payments flag is on (and available) for this file; what the database +// refuses while it is off is tested in payments_flag_off.test.ts +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await resetFeatureFlags(pool) + await setFeatureFlag(pool, "payments", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +/* + * Organizer actions (mark paid, undo, reminders), and what happens to + * payments when a paid registration or event is deleted: nothing is refunded + * and the payment rows stay. + */ + +const jobPayloads = async ( + client: PoolClient, + taskIdentifier: string, + key: string, + ids: string[] +) => { + const jobs = await getJobs(client, taskIdentifier) + return jobs.map((job) => job.payload).filter((p) => ids.includes(p[key])) +} + +const sortById = >(rows: T[], key: string) => + [...rows].sort((a, b) => a[key].localeCompare(b[key])) + +/** + * The registrations ordered as the database ranks them: those holding a + * spot first, the queued ones last (ties on created_at are broken by the + * database, not by creation order). + */ +const byQueueStatus = async ( + client: PoolClient, + registrations: T[] +) => + asRoot(client, async () => { + const { rows } = await client.query<{ id: string; status: string }>( + `select id, status from app_hidden.registrations_status_and_position + where id = any($1::uuid[])`, + [registrations.map((r) => r.id)] + ) + const queued = new Set( + rows.filter((r) => r.status === "IN_QUEUE").map((r) => r.id) + ) + return [ + ...registrations.filter((r) => !queued.has(r.id)), + ...registrations.filter((r) => queued.has(r.id)), + ] + }) + +const paymentsOf = (client: PoolClient, eventId: string) => + asRoot(client, async () => { + const { rows } = await client.query( + `select * from app_public.payments where event_id = $1 order by created_at`, + [eventId] + ) + return rows + }) + +describe("admin_mark_registration_paid", () => { + it("records a manual payment and queues the payment received email", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 1800, + }) + const { registration } = await register(client, event.id, quota.id) + await becomeUser(client, admin.id) + + const { + rows: [payment], + } = await client.query( + "select * from app_public.admin_mark_registration_paid($1)", + [registration.id] + ) + expect(payment).toMatchObject({ + registration_id: registration.id, + event_id: event.id, + quota_id: quota.id, + event_name: event.name, + quota_title: quota.title, + method: "MANUAL", + status: "PAID", + ticket_amount_cents: 1800, + service_fee_cents: 0, + currency: "eur", + created_by: admin.id, + }) + expect(payment.paid_at).toBeTruthy() + + expect( + await jobPayloads(client, "payment__send_received_email", "paymentId", [ + payment.id, + ]) + ).toEqual([{ paymentId: payment.id }]) + + const { rows } = await client.query( + `select app_public.registrations_payment_status(r) as status + from app_public.registrations r where r.id = $1`, + [registration.id] + ) + expect(rows[0].status).toBe("PAID_MANUALLY") + })) + + it("lets members of the event's organization mark registrations paid", () => + withRootDb(async (client) => { + const { organization, event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + const member = await createOrganizationMember(client, organization.id) + await becomeUser(client, member.id) + + const { rows } = await client.query( + "select method from app_public.admin_mark_registration_paid($1)", + [registration.id] + ) + expect(rows).toEqual([{ method: "MANUAL" }]) + })) + + it("refuses an already paid registration", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration, { method: "STRIPE" }) + await becomeUser(client, admin.id) + + await expect( + client.query("select app_public.admin_mark_registration_paid($1)", [ + registration.id, + ]) + ).rejects.toThrow("already been paid") + })) + + it("refuses a registration of a free quota, which needs no payment", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 0, + }) + const { registration } = await register(client, event.id, quota.id) + await becomeUser(client, admin.id) + + await expect( + client.query("select app_public.admin_mark_registration_paid($1)", [ + registration.id, + ]) + ).rejects.toThrow("does not require payment") + })) + + it("records the current quota price", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 1800, + }) + const { registration } = await register(client, event.id, quota.id) + await asRoot(client, () => + client.query( + "update app_public.quotas set price_cents = 2200 where id = $1", + [quota.id] + ) + ) + await becomeUser(client, admin.id) + + const { rows } = await client.query( + "select ticket_amount_cents from app_public.admin_mark_registration_paid($1)", + [registration.id] + ) + expect(rows).toEqual([{ ticket_amount_cents: 2200 }]) + })) + + it("refuses a queued registration", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + quotaSize: 1, + }) + const registrations = [] + for (let i = 0; i < 2; i++) { + const { registration } = await register(client, event.id, quota.id) + registrations.push(registration) + } + const [inSpot, queued] = await byQueueStatus(client, registrations) + await becomeUser(client, admin.id) + + await client.query("savepoint queued") + await expect( + client.query("select app_public.admin_mark_registration_paid($1)", [ + queued.id, + ]) + ).rejects.toThrow("in the queue") + await client.query("rollback to savepoint queued") + const { rows } = await client.query( + "select method from app_public.admin_mark_registration_paid($1)", + [inSpot.id] + ) + expect(rows).toEqual([{ method: "MANUAL" }]) + })) +}) + +describe("admin_unmark_registration_paid", () => { + it("removes the manual payment", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration, { method: "MANUAL" }) + // An old expired card attempt is left alone + await insertPayment(client, registration, { + method: "STRIPE", + status: "EXPIRED", + }) + await becomeUser(client, admin.id) + + const { rows } = await client.query( + "select app_public.admin_unmark_registration_paid($1) as ok", + [registration.id] + ) + expect(rows).toEqual([{ ok: true }]) + + const payments = await paymentsOf(client, event.id) + expect(payments.map((p) => [p.method, p.status])).toEqual([ + ["STRIPE", "EXPIRED"], + ]) + })) + + it("does not undo a card payment", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration, { method: "STRIPE" }) + await becomeUser(client, admin.id) + + await expect( + client.query("select app_public.admin_unmark_registration_paid($1)", [ + registration.id, + ]) + ).rejects.toThrow("no manual payment") + })) +}) + +describe("admin_send_payment_reminders", () => { + it("queues one reminder per unpaid registration holding a spot", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + quotaSize: 3, + }) + const registrations = [] + for (let i = 0; i < 4; i++) { + const { registration } = await register(client, event.id, quota.id) + registrations.push(registration) + } + // Registrations made in one transaction share created_at, so which + // one is queued is decided by the database: read it back + const [paid, unpaid1, unpaid2] = await byQueueStatus( + client, + registrations + ) + await insertPayment(client, paid) + await becomeUser(client, admin.id) + + const { rows } = await client.query( + "select app_public.admin_send_payment_reminders($1) as count", + [event.id] + ) + expect(rows).toEqual([{ count: 2 }]) + + const ids = registrations.map((r) => r.id) + const payloads = await jobPayloads( + client, + "payment__send_reminder", + "registrationId", + ids + ) + expect(sortById(payloads, "registrationId")).toEqual( + sortById( + [{ registrationId: unpaid1.id }, { registrationId: unpaid2.id }], + "registrationId" + ) + ) + + const { + rows: [updated], + } = await client.query( + "select last_payment_reminder_sent_at from app_public.events where id = $1", + [event.id] + ) + expect(updated.last_payment_reminder_sent_at).toBeTruthy() + })) + + it("sends nothing and keeps the timestamp empty when nobody is unpaid", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 0, + }) + const { registration } = await register(client, event.id, quota.id) + await becomeUser(client, admin.id) + + const { rows } = await client.query( + "select app_public.admin_send_payment_reminders($1) as count", + [event.id] + ) + expect(rows).toEqual([{ count: 0 }]) + expect( + await jobPayloads(client, "payment__send_reminder", "registrationId", [ + registration.id, + ]) + ).toEqual([]) + + const { + rows: [updated], + } = await client.query( + "select last_payment_reminder_sent_at from app_public.events where id = $1", + [event.id] + ) + expect(updated.last_payment_reminder_sent_at).toBeNull() + })) + + it("refuses to send again within 10 minutes", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await asRoot(client, () => + client.query( + `update app_public.events + set last_payment_reminder_sent_at = now() - interval '9 minutes' + where id = $1`, + [event.id] + ) + ) + await becomeUser(client, admin.id) + await client.query("savepoint cooldown") + await expect( + client.query("select app_public.admin_send_payment_reminders($1)", [ + event.id, + ]) + ).rejects.toThrow("less than 10 minutes ago") + await client.query("rollback to savepoint cooldown") + + await asRoot(client, () => + client.query( + `update app_public.events + set last_payment_reminder_sent_at = now() - interval '11 minutes' + where id = $1`, + [event.id] + ) + ) + const { rows } = await client.query( + "select app_public.admin_send_payment_reminders($1) as count", + [event.id] + ) + expect(rows).toEqual([{ count: 1 }]) + expect( + await jobPayloads(client, "payment__send_reminder", "registrationId", [ + registration.id, + ]) + ).toEqual([{ registrationId: registration.id }]) + })) +}) + +describe("organizer action permissions", () => { + type ArgumentFor = ( + client: PoolClient, + event: { id: string }, + quota: { id: string } + ) => Promise + + const registrationId: ArgumentFor = async (client, event, quota) => { + const { registration } = await register(client, event.id, quota.id) + return registration.id + } + const manuallyPaidRegistrationId: ArgumentFor = async ( + client, + event, + quota + ) => { + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration, { method: "MANUAL" }) + return registration.id + } + const eventId: ArgumentFor = async (_client, event) => event.id + + it.each([ + ["admin_mark_registration_paid", registrationId], + ["admin_unmark_registration_paid", manuallyPaidRegistrationId], + ["admin_send_payment_reminders", eventId], + ])("%s refuses users without event permissions", (fn, argumentFor) => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const argument = await argumentFor(client, event, quota) + const [user] = await createUsers(client, 1) + await becomeUser(client, user.id) + + await expect( + client.query(`select app_public.${fn}($1)`, [argument]) + ).rejects.toThrow("Access denied") + }) + ) +}) + +describe("deleting paid registrations and events", () => { + it("admin_delete_registration deletes a paid registration and keeps its payment, detached", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + const payment = await insertPayment(client, registration) + await becomeUser(client, admin.id) + + await client.query("select app_public.admin_delete_registration($1)", [ + registration.id, + ]) + + expect(await paymentsOf(client, event.id)).toMatchObject([ + { id: payment.id, registration_id: null, status: "PAID" }, + ]) + // Nothing is refunded: no job is queued for the payment + const jobs = await getJobs(client) + expect( + jobs.filter((job) => job.payload?.paymentId === payment.id) + ).toEqual([]) + })) + + it("delete_registration lets a participant delete a paid registration while signup is open", () => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const { registration, updateToken } = await register( + client, + event.id, + quota.id + ) + const payment = await insertPayment(client, registration) + await becomeUser(client, null) + + const { rows } = await client.query( + "select app_public.delete_registration($1) as ok", + [updateToken] + ) + expect(rows).toEqual([{ ok: true }]) + expect(await paymentsOf(client, event.id)).toMatchObject([ + { id: payment.id, registration_id: null, status: "PAID" }, + ]) + })) + + it("deleting an event keeps every payment row", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration: card } = await register(client, event.id, quota.id) + const { registration: manual } = await register( + client, + event.id, + quota.id + ) + const { registration: pending } = await register( + client, + event.id, + quota.id + ) + const cardPayment = await insertPayment(client, card) + const manualPayment = await insertPayment(client, manual, { + method: "MANUAL", + }) + const pendingPayment = await insertPayment(client, pending, { + status: "PENDING", + }) + await becomeUser(client, admin.id) + + // As the deleteEvent CRUD mutation does; registrations cascade + const { rowCount } = await client.query( + "delete from app_public.events where id = $1", + [event.id] + ) + expect(rowCount).toBe(1) + + const rows = await asRoot(client, async () => { + const { rows } = await client.query( + `select id, registration_id, event_id, status from app_public.payments + where id = any($1)`, + [[cardPayment.id, manualPayment.id, pendingPayment.id]] + ) + return rows + }) + expect(rows).toHaveLength(3) + for (const row of rows) { + expect(row).toMatchObject({ registration_id: null, event_id: null }) + } + })) +}) diff --git a/@app/db/__tests__/app_public/functions/payment_settings.test.ts b/@app/db/__tests__/app_public/functions/payment_settings.test.ts new file mode 100644 index 000000000..150d89a34 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/payment_settings.test.ts @@ -0,0 +1,273 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withAdminUserDb, +} from "../../helpers" +import { createPaidEventData, insertPayment, register } from "../../payments" + +// The payments flag is on (and available) for this file; what the database +// refuses while it is off is tested in payments_flag_off.test.ts +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await resetFeatureFlags(pool) + await setFeatureFlag(pool, "payments", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +/* + * Quota prices, what changing them does to payments made already, and the + * close email timestamp that reopening registration clears. + */ + +const quotaInput = (quota: any, overrides: Record = {}) => ({ + id: quota.id, + position: quota.position, + title: quota.title, + size: quota.size, + ...overrides, +}) + +/** Calls update_event like the admin UI does, as the current user. */ +const updateEvent = ( + client: PoolClient, + eventId: string, + event: Record, + quotas: Record[] +) => + client.query( + `select * from app_public.update_event( + $1, + jsonb_populate_record(null::app_public.event_input, $2::jsonb), + array( + select jsonb_populate_record(null::app_public.update_event_quotas, q) + from jsonb_array_elements($3::jsonb) as q + ), + '{}' + )`, + [eventId, JSON.stringify(event), JSON.stringify(quotas)] + ) + +/** Calls create_event like the admin UI does, as the current user. */ +const createEvent = async ( + client: PoolClient, + organizationId: string, + categoryId: string, + event: Record, + quotas: Record[] +) => { + const now = Date.now() + const day = 24 * 60 * 60 * 1000 + const { + rows: [created], + } = await client.query( + `select * from app_public.create_event( + jsonb_populate_record(null::app_public.event_input, $1::jsonb), + array( + select jsonb_populate_record(null::app_public.create_event_quotas, q) + from jsonb_array_elements($2::jsonb) as q + ), + '{}' + )`, + [ + JSON.stringify({ + slug: `payments-${now}-${Math.random()}`, + name: { fi: "Maksullinen", en: "Paid" }, + description: { fi: "", en: "" }, + location: "Otaniemi", + registration_start_time: new Date(now - day), + registration_end_time: new Date(now + day), + event_start_time: new Date(now + 2 * day), + event_end_time: new Date(now + 3 * day), + is_highlighted: false, + is_draft: false, + open_quota_size: 0, + owner_organization_id: organizationId, + category_id: categoryId, + ...event, + }), + JSON.stringify(quotas), + ] + ) + const { rows: createdQuotas } = await client.query( + "select price_cents from app_public.quotas where event_id = $1 order by position", + [created.id] + ) + return { event: created, quotas: createdQuotas } +} + +const newQuota = (position: number, extra: Record = {}) => ({ + position, + title: { fi: `Kiintiö ${position}`, en: `Quota ${position}` }, + size: 10, + ...extra, +}) + +const paymentStatus = async (client: PoolClient, registrationId: string) => { + const { rows } = await asRoot(client, () => + client.query( + `select app_private.registration_payment_status(r) as status + from app_public.registrations r where r.id = $1`, + [registrationId] + ) + ) + return rows[0].status +} + +describe("create_event quota prices", () => { + it("writes the quota prices", () => + withAdminUserDb(async (client, admin) => { + const { organization, eventCategory } = await createPaidEventData(client) + await becomeUser(client, admin.id) + const { quotas } = await createEvent( + client, + organization.id, + eventCategory.id, + {}, + [newQuota(0, { price_cents: 1800 }), newQuota(1, { price_cents: 0 })] + ) + expect(quotas).toEqual([{ price_cents: 1800 }, { price_cents: 0 }]) + })) +}) + +describe("update_event quota prices", () => { + it("updates quota prices", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 0, + }) + await becomeUser(client, admin.id) + await updateEvent(client, event.id, {}, [ + quotaInput(quota, { price_cents: 1000 }), + ]) + + const { rows } = await client.query( + "select price_cents from app_public.quotas where id = $1", + [quota.id] + ) + expect(rows).toEqual([{ price_cents: 1000 }]) + })) + + it("keeps prices when the field is left out, and adds new quotas as free unless a price is given", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 1800, + }) + await becomeUser(client, admin.id) + const { + rows: [updated], + } = await updateEvent(client, event.id, { location: "Dipoli" }, [ + quotaInput(quota), + { + position: 1, + title: { fi: "Ilmainen", en: "Free" }, + size: 5, + }, + { + position: 2, + title: { fi: "Maksullinen", en: "Paid" }, + size: 5, + price_cents: 25, + }, + ]) + expect(updated.location).toBe("Dipoli") + + const { rows } = await client.query( + "select price_cents from app_public.quotas where event_id = $1 order by position", + [event.id] + ) + expect(rows).toEqual([ + { price_cents: 1800 }, + { price_cents: 0 }, + { price_cents: 25 }, + ]) + })) + + it("allows changing a price after payments; paid registrations stay paid and unpaid ones owe the new price", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client, { + priceCents: 1800, + }) + const { registration: paid } = await register(client, event.id, quota.id) + const { registration: unpaid } = await register( + client, + event.id, + quota.id + ) + await insertPayment(client, paid, { ticketAmountCents: 1800 }) + + await becomeUser(client, admin.id) + for (const priceCents of [2200, 0]) { + await updateEvent(client, event.id, {}, [ + quotaInput(quota, { price_cents: priceCents }), + ]) + expect(await paymentStatus(client, paid.id)).toBe("PAID") + } + expect(await paymentStatus(client, unpaid.id)).toBe("NOT_REQUIRED") + + await updateEvent(client, event.id, {}, [ + quotaInput(quota, { price_cents: 2500 }), + ]) + expect(await paymentStatus(client, unpaid.id)).toBe("UNPAID") + // What was paid is kept on the payment + const { rows } = await asRoot(client, () => + client.query( + "select ticket_amount_cents from app_public.payments where registration_id = $1", + [paid.id] + ) + ) + expect(rows).toEqual([{ ticket_amount_cents: 1800 }]) + })) +}) + +describe("unpaid_close_email_sent_at", () => { + const closeEmailSentAt = async (client: PoolClient, eventId: string) => { + const { rows } = await asRoot(client, () => + client.query( + "select unpaid_close_email_sent_at from app_public.events where id = $1", + [eventId] + ) + ) + return rows[0].unpaid_close_email_sent_at + } + + const hour = 60 * 60 * 1000 + // The fake event starts a random time after registration closes, so moving + // the close later goes only halfway to the start to keep it before it + const halfwayToStart = (end: number, start: number) => (start - end) / 2 + it.each([ + [ + "is cleared when registration_end_time moves later", + halfwayToStart, + false, + ], + ["is kept when registration_end_time moves earlier", () => -hour, true], + ["is kept when registration_end_time is unchanged", () => 0, true], + ])("%s", (_case, shift, kept) => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + await asRoot(client, () => + client.query( + "update app_public.events set unpaid_close_email_sent_at = now() where id = $1", + [event.id] + ) + ) + const end = new Date(event.registration_end_time).getTime() + const start = new Date(event.event_start_time).getTime() + const newEnd = new Date(end + shift(end, start)) + await becomeUser(client, admin.id) + await updateEvent( + client, + event.id, + { location: "Dipoli", registration_end_time: newEnd }, + [quotaInput(quota)] + ) + expect(!!(await closeEmailSentAt(client, event.id))).toBe(kept) + }) + ) +}) diff --git a/@app/db/__tests__/app_public/functions/payment_status.test.ts b/@app/db/__tests__/app_public/functions/payment_status.test.ts new file mode 100644 index 000000000..4700d7075 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/payment_status.test.ts @@ -0,0 +1,309 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withRootDb, +} from "../../helpers" +import { + createOrganizationMember, + createPaidEventData, + insertPayment, + register, +} from "../../payments" + +// The payments flag is on (and available) for this file; what the database +// refuses while it is off is tested in payments_flag_off.test.ts +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await resetFeatureFlags(pool) + await setFeatureFlag(pool, "payments", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +/* + * registrations_payment_status and events_payment_summary: the organizer-only + * computed columns. + */ + +const paymentStatus = async (client: PoolClient, registrationId: string) => { + const { rows } = await client.query( + `select app_public.registrations_payment_status(r) as status + from app_public.registrations r where r.id = $1`, + [registrationId] + ) + return rows[0].status +} + +const paymentSummary = async (client: PoolClient, eventId: string) => { + const { rows } = await client.query( + `select (app_public.events_payment_summary(e)).* from app_public.events e where e.id = $1`, + [eventId] + ) + return rows[0] +} + +/** Makes the user the test then views as, returning their id (null: anonymous). */ +type Viewer = (client: PoolClient) => Promise + +const anAdmin: Viewer = async (client) => { + const [admin] = await createUsers(client, 1, true, true) + return admin.id +} +const anonymous: Viewer = async () => null +const aUserWithoutEventPermissions: Viewer = async (client) => { + const [user] = await createUsers(client, 1) + return user.id +} + +describe("registrations_payment_status", () => { + it("returns every state for a member of the event's organization", () => + withRootDb(async (client) => { + const { organization, event, quota } = await createPaidEventData(client) + const freeQuota = await asRoot(client, async () => { + const { rows } = await client.query( + `insert into app_public.quotas(event_id, position, title, size) + values ($1, 1, '{"fi": "Ilmainen", "en": "Free"}', 10) returning *`, + [event.id] + ) + return rows[0] + }) + + const { registration: unpaid } = await register( + client, + event.id, + quota.id + ) + const { registration: paid } = await register(client, event.id, quota.id) + const { registration: paidManually } = await register( + client, + event.id, + quota.id + ) + const { registration: free } = await register( + client, + event.id, + freeQuota.id + ) + // Expired and pending checkout sessions don't count as paid + await insertPayment(client, unpaid, { status: "EXPIRED" }) + await insertPayment(client, unpaid, { status: "PENDING" }) + await insertPayment(client, paid, { status: "EXPIRED" }) + await insertPayment(client, paid, { status: "PAID" }) + await insertPayment(client, paidManually, { + method: "MANUAL", + status: "PAID", + }) + + const member = await createOrganizationMember(client, organization.id) + await becomeUser(client, member.id) + + expect(await paymentStatus(client, unpaid.id)).toBe("UNPAID") + expect(await paymentStatus(client, paid.id)).toBe("PAID") + expect(await paymentStatus(client, paidManually.id)).toBe("PAID_MANUALLY") + expect(await paymentStatus(client, free.id)).toBe("NOT_REQUIRED") + })) + + it("is NOT_REQUIRED for an unpaid registration once its quota is free, and PAID for a paid one whatever the price", () => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const { registration: unpaid } = await register( + client, + event.id, + quota.id + ) + const { registration: paid } = await register(client, event.id, quota.id) + // Paid less than the quota costs now + await insertPayment(client, paid, { ticketAmountCents: 900 }) + await client.query( + "update app_public.quotas set price_cents = 0 where id = $1", + [quota.id] + ) + const [admin] = await createUsers(client, 1, true, true) + await becomeUser(client, admin.id) + + expect(await paymentStatus(client, unpaid.id)).toBe("NOT_REQUIRED") + expect(await paymentStatus(client, paid.id)).toBe("PAID") + })) + + it("is NOT_REQUIRED for an unfinished registration", () => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const { + rows: [tokens], + } = await client.query( + "select * from app_public.claim_registration_token($1, $2)", + [event.id, quota.id] + ) + const { + rows: [{ registration_id }], + } = await client.query( + "select registration_id from app_private.registration_secrets where registration_token = $1", + [tokens.registration_token] + ) + const [admin] = await createUsers(client, 1, true, true) + await becomeUser(client, admin.id) + + expect(await paymentStatus(client, registration_id)).toBe("NOT_REQUIRED") + })) + + type AddPayments = ( + client: PoolClient, + registration: { id: string; event_id: string; quota_id: string } + ) => Promise + const noPayment: AddPayments = async () => undefined + const aCardPayment: AddPayments = (client, registration) => + insertPayment(client, registration) + + it.each([ + ["is visible to admins", anAdmin, noPayment, "UNPAID"], + ["is null for anonymous users", anonymous, aCardPayment, null], + [ + "is null for users without event permissions", + aUserWithoutEventPermissions, + aCardPayment, + null, + ], + ])("%s", (_case, viewer, addPayments, expected) => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await addPayments(client, registration) + await becomeUser(client, await viewer(client)) + expect(await paymentStatus(client, registration.id)).toBe(expected) + }) + ) +}) + +describe("events_payment_summary", () => { + it("counts registrations holding a spot and sums paid tickets", () => + withRootDb(async (client) => { + // Four spots in the quota and one in the open quota; the sixth + // registration is queued. + const { organization, event, quota } = await createPaidEventData(client, { + priceCents: 1000, + quotaSize: 4, + openQuotaSize: 1, + }) + const registrations = [] + for (let i = 0; i < 6; i++) { + const { registration } = await register(client, event.id, quota.id) + registrations.push(registration) + } + // Registrations made in one transaction share created_at, so the + // database decides who gets which spot: assign the roles from that + const { rows: statuses } = await client.query( + `select id, status from app_hidden.registrations_status_and_position where event_id = $1`, + [event.id] + ) + const withStatus = (status: string) => + registrations.filter( + (r) => statuses.find((s) => s.id === r.id)?.status === status + ) + const [stripe, manual, unpaid1, unpaid2] = withStatus("IN_QUOTA") + const [inOpenQuota] = withStatus("IN_OPEN_QUOTA") + const [queued] = withStatus("IN_QUEUE") + expect(unpaid1 && unpaid2 && inOpenQuota && queued).toBeTruthy() + + await insertPayment(client, stripe, { ticketAmountCents: 1000 }) + await insertPayment(client, manual, { + method: "MANUAL", + ticketAmountCents: 1000, + }) + await insertPayment(client, inOpenQuota, { + status: "PENDING", + ticketAmountCents: 1000, + }) + // A queued registration that paid anyway still counts towards the money + await insertPayment(client, queued, { ticketAmountCents: 1000 }) + // A card payment of a deleted registration, and a manual one + const { registration: deleted } = await register( + client, + event.id, + quota.id + ) + const { registration: deletedManual } = await register( + client, + event.id, + quota.id + ) + await insertPayment(client, deleted, { ticketAmountCents: 1000 }) + await insertPayment(client, deletedManual, { + method: "MANUAL", + ticketAmountCents: 1000, + }) + await client.query( + "delete from app_public.registrations where id = any($1)", + [[deleted.id, deletedManual.id]] + ) + + const member = await createOrganizationMember(client, organization.id) + await becomeUser(client, member.id) + + expect(await paymentSummary(client, event.id)).toEqual({ + paid_count: 2, + unpaid_count: 3, + due_count: 5, + tickets_paid_cents: 5000, + // Three card payments: 1000 - 1,5 % × 1025 = 984,625 → 985 each. + // The manual payments reach the guild in full. + guild_receives_cents: 985 + 1000 + 985 + 985 + 1000, + // Only the card payment of the deleted registration + unlinked_card_payment_count: 1, + }) + })) + + type AddRegistrations = ( + client: PoolClient, + event: { id: string }, + quota: { id: string } + ) => Promise + const noRegistrations: AddRegistrations = async () => undefined + const aPaidRegistration: AddRegistrations = async (client, event, quota) => { + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration) + } + const hidden = { + paid_count: null, + unpaid_count: null, + due_count: null, + tickets_paid_cents: null, + guild_receives_cents: null, + unlinked_card_payment_count: null, + } + + it.each([ + [ + "is all zeros for an event without registrations", + anAdmin, + noRegistrations, + { + paid_count: 0, + unpaid_count: 0, + due_count: 0, + tickets_paid_cents: 0, + guild_receives_cents: 0, + unlinked_card_payment_count: 0, + }, + ], + ["is null for anonymous users", anonymous, aPaidRegistration, hidden], + [ + "is null for users without event permissions", + aUserWithoutEventPermissions, + aPaidRegistration, + hidden, + ], + ])("%s", (_case, viewer, addRegistrations, expected) => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + await addRegistrations(client, event, quota) + await becomeUser(client, await viewer(client)) + expect(await paymentSummary(client, event.id)).toEqual(expected) + }) + ) +}) diff --git a/@app/db/__tests__/app_public/functions/payments_flag_off.test.ts b/@app/db/__tests__/app_public/functions/payments_flag_off.test.ts new file mode 100644 index 000000000..3d321de97 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/payments_flag_off.test.ts @@ -0,0 +1,246 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + upsertFeatureFlag, + withAdminUserDb, +} from "../../helpers" +import { createPaidEventData, insertPayment, register } from "../../payments" + +/* + * While the `payments` flag is off nobody can start a payment: quota prices + * are refused (errcode FTOFF) and the organizer payment actions refuse to + * run. What is already there stays: stored prices are kept, paid + * registrations stay paid. + */ + +const day = 24 * 60 * 60 * 1000 + +const eventInput = ( + organizationId: string, + categoryId: string, + extra: Record = {} +) => { + const now = Date.now() + return { + slug: `payments-off-${now}-${Math.random()}`, + name: { fi: "Tapahtuma", en: "Event" }, + description: { fi: "", en: "" }, + location: "Otaniemi", + registration_start_time: new Date(now - day), + registration_end_time: new Date(now + day), + event_start_time: new Date(now + 2 * day), + event_end_time: new Date(now + 3 * day), + is_highlighted: false, + is_draft: false, + open_quota_size: 0, + owner_organization_id: organizationId, + category_id: categoryId, + ...extra, + } +} + +const newQuota = (extra: Record = {}) => ({ + position: 0, + title: { fi: "Kiintiö", en: "Quota" }, + size: 10, + ...extra, +}) + +const createEvent = ( + client: PoolClient, + event: Record, + quotas: Record[] +) => + client.query( + `select * from app_public.create_event( + jsonb_populate_record(null::app_public.event_input, $1::jsonb), + array( + select jsonb_populate_record(null::app_public.create_event_quotas, q) + from jsonb_array_elements($2::jsonb) as q + ), + '{}' + )`, + [JSON.stringify(event), JSON.stringify(quotas)] + ) + +const updateEvent = ( + client: PoolClient, + eventId: string, + event: Record, + quotas: Record[] +) => + client.query( + `select * from app_public.update_event( + $1, + jsonb_populate_record(null::app_public.event_input, $2::jsonb), + array( + select jsonb_populate_record(null::app_public.update_event_quotas, q) + from jsonb_array_elements($3::jsonb) as q + ), + '{}' + )`, + [eventId, JSON.stringify(event), JSON.stringify(quotas)] + ) + +const quotaInput = (quota: any, extra: Record = {}) => ({ + id: quota.id, + position: quota.position, + title: quota.title, + size: quota.size, + ...extra, +}) + +/** A paid event made while payments were on, with the flag now off. */ +async function paidEventWithFlagOff(client: PoolClient, userId: string) { + const data = await createPaidEventData(client) + await upsertFeatureFlag(client, "payments", "off") + await becomeUser(client, userId) + return data +} + +describe("while the payments flag is off", () => { + describe("create_event", () => { + it("refuses a quota price", () => + withAdminUserDb(async (client, admin) => { + const { organization, eventCategory } = await paidEventWithFlagOff( + client, + admin.id + ) + await expect( + createEvent(client, eventInput(organization.id, eventCategory.id), [ + newQuota({ price_cents: 1800 }), + ]) + ).rejects.toMatchObject({ code: "FTOFF" }) + })) + + it("accepts free quotas", () => + withAdminUserDb(async (client, admin) => { + const { organization, eventCategory } = await paidEventWithFlagOff( + client, + admin.id + ) + const { + rows: [event], + } = await createEvent( + client, + eventInput(organization.id, eventCategory.id), + [newQuota({ price_cents: 0 }), newQuota({ position: 1 })] + ) + const { rows } = await client.query( + "select price_cents from app_public.quotas where event_id = $1", + [event.id] + ) + expect(rows).toEqual([{ price_cents: 0 }, { price_cents: 0 }]) + })) + }) + + describe("update_event", () => { + it("refuses a non-zero quota price, also the stored one", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await paidEventWithFlagOff(client, admin.id) + await expect( + updateEvent(client, event.id, {}, [ + quotaInput(quota, { price_cents: quota.price_cents }), + ]) + ).rejects.toMatchObject({ code: "FTOFF" }) + })) + + it("keeps the stored prices when they are left out", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await paidEventWithFlagOff(client, admin.id) + const { + rows: [updated], + } = await updateEvent(client, event.id, { location: "Espoo" }, [ + quotaInput(quota), + ]) + expect(updated).toMatchObject({ location: "Espoo" }) + const { + rows: [stored], + } = await client.query( + "select price_cents from app_public.quotas where id = $1", + [quota.id] + ) + expect(stored.price_cents).toBe(1800) + })) + + it("lets an organizer make a paid quota free", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await paidEventWithFlagOff(client, admin.id) + await updateEvent(client, event.id, {}, [ + quotaInput(quota, { price_cents: 0 }), + ]) + const { rows } = await client.query( + "select price_cents from app_public.quotas where id = $1", + [quota.id] + ) + expect(rows).toEqual([{ price_cents: 0 }]) + })) + }) + + describe("organizer payment actions", () => { + it("refuses admin_mark_registration_paid and admin_unmark_registration_paid", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await upsertFeatureFlag(client, "payments", "off") + await becomeUser(client, admin.id) + for (const fn of [ + "admin_mark_registration_paid", + "admin_unmark_registration_paid", + ]) { + await client.query("savepoint flag_off") + await expect( + client.query(`select app_public.${fn}($1)`, [registration.id]) + ).rejects.toMatchObject({ code: "FTOFF" }) + await client.query("rollback to savepoint flag_off") + } + })) + + it("refuses admin_send_payment_reminders", () => + withAdminUserDb(async (client, admin) => { + const { event } = await paidEventWithFlagOff(client, admin.id) + await expect( + client.query("select app_public.admin_send_payment_reminders($1)", [ + event.id, + ]) + ).rejects.toMatchObject({ code: "FTOFF" }) + })) + }) + + it("keeps showing a card payment as paid, also after its registration is deleted", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + const { registration: deleted } = await register( + client, + event.id, + quota.id + ) + await insertPayment(client, registration) + const detached = await insertPayment(client, deleted) + await upsertFeatureFlag(client, "payments", "off") + await becomeUser(client, admin.id) + + const { + rows: [{ status }], + } = await client.query( + `select app_public.registrations_payment_status(r) as status + from app_public.registrations r where r.id = $1`, + [registration.id] + ) + expect(status).toBe("PAID") + + await client.query("select app_public.admin_delete_registration($1)", [ + deleted.id, + ]) + const { rows } = await asRoot(client, () => + client.query( + "select registration_id, status from app_public.payments where id = $1", + [detached.id] + ) + ) + expect(rows).toEqual([{ registration_id: null, status: "PAID" }]) + })) +}) diff --git a/@app/db/__tests__/app_public/functions/reminder_feature_flags.test.ts b/@app/db/__tests__/app_public/functions/reminder_feature_flags.test.ts new file mode 100644 index 000000000..f89f6836e --- /dev/null +++ b/@app/db/__tests__/app_public/functions/reminder_feature_flags.test.ts @@ -0,0 +1,171 @@ +import { PoolClient } from "pg" + +import { + asRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createUsers, + setFeatureFlag, + withRootDb, +} from "../../helpers" + +/* + * The SQL gates of registration_reminders and telegram_reminders: ways in + * raise FTOFF while a flag is off, ways out keep working. + */ + +async function setup(client: PoolClient) { + 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, (c) => + c.query( + "insert into app_public.telegram_accounts (user_id, chat_id) values ($1, 4242)", + [user.id] + ) + ) + await becomeUser(client, user.id) + return { user, event } +} + +/** Runs the query in a savepoint and returns its error code, or null. */ +async function errorCode(client: PoolClient, sql: string, values: any[] = []) { + await client.query("savepoint gate") + try { + await client.query(sql, values) + await client.query("release savepoint gate") + return null + } catch (e) { + await client.query("rollback to savepoint gate") + return e.code + } +} + +const enableReminder = (method = "email") => [ + "select app_public.set_event_registration_reminder($1, true, 'fi', 30, $2)", + method, +] + +describe("while registration_reminders is off", () => { + it("refuses to enable a reminder or save preferences", () => + withRootDb(async (client) => { + const { event } = await setup(client) + const [sql, method] = enableReminder() + expect(await errorCode(client, sql, [event.id, method])).toBe("FTOFF") + expect( + await errorCode( + client, + "select app_public.save_reminder_preferences(30, 'email')" + ) + ).toBe("FTOFF") + expect( + await errorCode(client, "select app_public.enable_event_reminder($1)", [ + event.id, + ]) + ).toBe("FTOFF") + const { rows } = await client.query( + "select * from app_public.event_registration_reminders" + ) + expect(rows).toEqual([]) + })) + + it("still lets the user cancel a reminder", () => + withRootDb(async (client) => { + const { user, event } = await setup(client) + await setFeatureFlag(client, "registration_reminders", "on") + const [sql, method] = enableReminder() + await client.query(sql, [event.id, method]) + await setFeatureFlag(client, "registration_reminders", "off") + + const { + rows: [result], + } = await client.query( + "select app_public.set_event_registration_reminder($1, false) as enabled", + [event.id] + ) + expect(result.enabled).toBe(false) + const { rows } = await asRoot(client, (c) => + c.query( + "select * from app_public.event_registration_reminders where user_id = $1", + [user.id] + ) + ) + expect(rows).toEqual([]) + })) + + it("is on for admins only in admins_only", () => + withRootDb(async (client) => { + const { user, event } = await setup(client) + await setFeatureFlag(client, "registration_reminders", "admins_only") + const [sql, method] = enableReminder() + expect(await errorCode(client, sql, [event.id, method])).toBe("FTOFF") + await asRoot(client, (c) => + c.query("update app_public.users set is_admin = true where id = $1", [ + user.id, + ]) + ) + expect(await errorCode(client, sql, [event.id, method])).toBeNull() + })) +}) + +describe("while telegram_reminders is off", () => { + it.each(["telegram", "both"])( + "refuses the %s channel and keeps email", + (method) => + withRootDb(async (client) => { + const { event } = await setup(client) + await setFeatureFlag(client, "registration_reminders", "on") + const [sql] = enableReminder() + expect(await errorCode(client, sql, [event.id, method])).toBe("FTOFF") + expect( + await errorCode( + client, + "select app_public.save_reminder_preferences(30, $1)", + [method] + ) + ).toBe("FTOFF") + expect(await errorCode(client, sql, [event.id, "email"])).toBeNull() + expect( + await errorCode( + client, + "select app_public.save_reminder_preferences(30, 'email')" + ) + ).toBeNull() + }) + ) + + it("accepts the Telegram channel once the flag is on", () => + withRootDb(async (client) => { + const { event } = await setup(client) + await setFeatureFlag(client, "registration_reminders", "on") + await setFeatureFlag(client, "telegram_reminders", "on") + const [sql] = enableReminder() + expect(await errorCode(client, sql, [event.id, "both"])).toBeNull() + })) + + it("refuses a link code and still allows disconnecting", () => + withRootDb(async (client) => { + const { user } = await setup(client) + expect( + await errorCode(client, "select app_public.request_telegram_link()") + ).toBe("FTOFF") + await client.query("select app_public.disconnect_telegram()") + const { rows } = await asRoot(client, (c) => + c.query( + "select * from app_public.telegram_accounts where user_id = $1", + [user.id] + ) + ) + expect(rows).toEqual([]) + })) +}) 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..dde03301b --- /dev/null +++ b/@app/db/__tests__/app_public/functions/reminder_preferences.test.ts @@ -0,0 +1,295 @@ +import { + asRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withRootDb, +} from "../../helpers" + +// The features under test are on; their gates are tested in reminder_feature_flags.test.ts. +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await setFeatureFlag(pool, "registration_reminders", "on") + await setFeatureFlag(pool, "telegram_reminders", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +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..a8b967724 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/set_event_registration_reminder.test.ts @@ -0,0 +1,429 @@ +import { PoolClient } from "pg" + +import { sendRegistrationReminderEmail as reminderTask } from "../../../../worker/src/tasks/reminder__send_registration" +import sendEmail from "../../../../worker/src/tasks/send_email" +import { + asRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withRootDb, +} from "../../helpers" + +// The features under test are on; their gates are tested in reminder_feature_flags.test.ts. +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await setFeatureFlag(pool, "registration_reminders", "on") + await setFeatureFlag(pool, "telegram_reminders", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +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/set_feature_flag.test.ts b/@app/db/__tests__/app_public/functions/set_feature_flag.test.ts new file mode 100644 index 000000000..6bbcb1b33 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/set_feature_flag.test.ts @@ -0,0 +1,166 @@ +import { PoolClient } from "pg" + +import { + asRoot, + upsertFeatureFlag, + withAdminUserDb, + withAnonymousDb, + withDeveloperUserDb, + withUserDb, +} from "../../helpers" + +const setFeatureFlag = (client: PoolClient, key: string, state: string) => + client.query("select * from app_public.set_feature_flag($1, $2)", [ + key, + state, + ]) + +const auditRows = (client: PoolClient, key: string) => + asRoot(client, async () => { + const { rows } = await client.query( + `select key, old_state, new_state, actor + from app_private.feature_flag_events + where key = $1 + order by created_at`, + [key] + ) + return rows + }) + +describe("app_public.set_feature_flag", () => { + it("is denied for anonymous users", () => + withAnonymousDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "off") + await expect( + setFeatureFlag(client, "test_flag", "on") + ).rejects.toMatchObject({ code: "DNIED" }) + })) + + it("is denied for regular users", () => + withUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "off") + await expect( + setFeatureFlag(client, "test_flag", "on") + ).rejects.toMatchObject({ code: "DNIED" }) + })) + + it("is denied for admins who are not developers", () => + withAdminUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "off") + await expect( + setFeatureFlag(client, "test_flag", "on") + ).rejects.toMatchObject({ code: "DNIED" }) + })) + + it("lets a developer change the state and records who did it", () => + withDeveloperUserDb(async (client, user) => { + await upsertFeatureFlag(client, "test_flag", "off") + + const { + rows: [flag], + } = await setFeatureFlag(client, "test_flag", "admins_only") + expect(flag.key).toBe("test_flag") + expect(flag.state).toBe("admins_only") + expect(flag.updated_by).toBe(user.id) + + await setFeatureFlag(client, "test_flag", "on") + + const { + rows: [stored], + } = await client.query( + "select state, updated_by from app_public.feature_flags where key = $1", + ["test_flag"] + ) + expect(stored).toEqual({ state: "on", updated_by: user.id }) + + expect(await auditRows(client, "test_flag")).toEqual([ + { + key: "test_flag", + old_state: "off", + new_state: "admins_only", + actor: user.id, + }, + { + key: "test_flag", + old_state: "admins_only", + new_state: "on", + actor: user.id, + }, + ]) + })) + + it("does not record an audit row when the state does not change", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + await setFeatureFlag(client, "test_flag", "on") + expect(await auditRows(client, "test_flag")).toEqual([]) + })) + + it("rejects an unknown key", () => + withDeveloperUserDb(async (client) => { + await expect( + setFeatureFlag(client, "test_does_not_exist", "on") + ).rejects.toMatchObject({ code: "NTFND" }) + })) + + it("refuses to enable an unavailable flag", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "off", { available: false }) + await expect( + setFeatureFlag(client, "test_flag", "admins_only") + ).rejects.toMatchObject({ code: "FTUNA" }) + })) + + it("still lets a developer switch an unavailable flag off", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on", { available: false }) + const { + rows: [flag], + } = await setFeatureFlag(client, "test_flag", "off") + expect(flag.state).toBe("off") + })) + + it("refuses to change a retired flag", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on", { retired: true }) + await expect( + setFeatureFlag(client, "test_flag", "off") + ).rejects.toMatchObject({ code: "DNIED" }) + })) +}) + +describe("app_public.feature_flag_events", () => { + it("returns the audit log, newest first, to developers", () => + withDeveloperUserDb(async (client, user) => { + await upsertFeatureFlag(client, "test_flag", "off") + await upsertFeatureFlag(client, "test_other", "off") + await setFeatureFlag(client, "test_flag", "on") + await setFeatureFlag(client, "test_other", "on") + + const { rows } = await client.query( + "select key, old_state, new_state, actor_id, actor_username from app_public.feature_flag_events($1)", + ["test_flag"] + ) + expect(rows).toEqual([ + { + key: "test_flag", + old_state: "off", + new_state: "on", + actor_id: user.id, + actor_username: user.username, + }, + ]) + + const { rows: all } = await client.query( + "select key from app_public.feature_flag_events() where key like 'test_%'" + ) + expect(all.map((r) => r.key).sort()).toEqual(["test_flag", "test_other"]) + })) + + it("is denied for admins who are not developers", () => + withAdminUserDb(async (client) => { + await expect( + client.query("select * from app_public.feature_flag_events()") + ).rejects.toMatchObject({ code: "DNIED" }) + })) +}) 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..a4d0b6c08 --- /dev/null +++ b/@app/db/__tests__/app_public/functions/telegram.test.ts @@ -0,0 +1,377 @@ +import { PoolClient } from "pg" + +import { processTelegramUpdate } from "../../../../server/src/telegram" +import { + asRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withRootDb, +} from "../../helpers" + +// The features under test are on; their gates are tested in reminder_feature_flags.test.ts. +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await setFeatureFlag(pool, "registration_reminders", "on") + await setFeatureFlag(pool, "telegram_reminders", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +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..548a1350f --- /dev/null +++ b/@app/db/__tests__/app_public/functions/telegram_language.test.ts @@ -0,0 +1,248 @@ +import { telegramRequest } from "@app/lib/dist/cjs/telegram" + +import { + processTelegramUpdate, + TelegramUpdate, +} from "../../../../server/src/telegram" +import { sendRegistrationReminderTelegram as telegramReminder } from "../../../../worker/src/tasks/reminder__send_telegram" +import { + asRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withRootDb, +} from "../../helpers" + +// The features under test are on; their gates are tested in reminder_feature_flags.test.ts. +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await setFeatureFlag(pool, "registration_reminders", "on") + await setFeatureFlag(pool, "telegram_reminders", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +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/__tests__/app_public/functions/update_event_questions.test.ts b/@app/db/__tests__/app_public/functions/update_event_questions.test.ts index 343306706..91c6e9ae8 100644 --- a/@app/db/__tests__/app_public/functions/update_event_questions.test.ts +++ b/@app/db/__tests__/app_public/functions/update_event_questions.test.ts @@ -36,8 +36,8 @@ describe("Test app_public.update_event_questions function", () => { `select app_public.update_event_questions( $1, array[ - row($2::uuid, 0::smallint, 'TEXT'::app_public.question_type, $3::app_public.translated_field, false, null), - row(null, 1::smallint, 'TEXT'::app_public.question_type, $4::app_public.translated_field, false, null) + row($2::uuid, 0::smallint, 'TEXT'::app_public.question_type, $3::app_public.translated_field, false, null, null), + row(null, 1::smallint, 'TEXT'::app_public.question_type, $4::app_public.translated_field, false, null, null) ]::app_public.update_event_questions[] )`, [ @@ -58,4 +58,89 @@ describe("Test app_public.update_event_questions function", () => { expect(questionIds).toContain(keptQuestion.id) expect(questionIds).not.toContain(removedQuestion.id) })) + + it("keeps an omitted prefill and clears it with NONE or a non-TEXT type", () => + withAdminUserDb(async (client) => { + const [organization] = await createOrganizations(client, 1) + const [eventCategory] = await createEventCategories( + client, + 1, + organization.id + ) + const [event] = await createEvents( + client, + 1, + organization.id, + eventCategory.id + ) + const label = { fi: "Telegram", en: "Telegram" } + const option = { fi: "A", en: "A" } + + // Each call sends the given questions, in order, and returns their + // stored prefills + const update = async ( + questions: Array<{ + id: string | null + type: string + prefill: string | null + }> + ) => { + const { rows } = await client.query( + `select q.id, q.prefill + from unnest(app_public.update_event_questions( + $1, + array( + select row( + (x->>'id')::uuid, + (ord - 1)::smallint, + (x->>'type')::app_public.question_type, + $2::app_public.translated_field, + false, + case when x->>'type' = 'TEXT' then null else array[$3::app_public.translated_field] end, + (x->>'prefill')::app_public.question_prefill + )::app_public.update_event_questions + from jsonb_array_elements($4::jsonb) with ordinality as t(x, ord) + order by ord + ) + )) as q`, + [event.id, label, option, JSON.stringify(questions)] + ) + return rows as Array<{ id: string; prefill: string | null }> + } + + const created = await update([ + { id: null, type: "TEXT", prefill: "TELEGRAM" }, + { id: null, type: "TEXT", prefill: "NONE" }, + { id: null, type: "TEXT", prefill: "TELEGRAM" }, + ]) + expect(created.map((q) => q.prefill)).toEqual([ + "TELEGRAM", + null, + "TELEGRAM", + ]) + const [a, b, c] = created.map((q) => q.id) + + // Omitted (null) keeps; NONE clears; a non-TEXT type clears + const omitted = await update([ + { id: a, type: "TEXT", prefill: null }, + { id: b, type: "TEXT", prefill: "DIETARY_RESTRICTIONS" }, + { id: c, type: "TEXT", prefill: null }, + ]) + expect(omitted.map((q) => q.prefill)).toEqual([ + "TELEGRAM", + "DIETARY_RESTRICTIONS", + "TELEGRAM", + ]) + + const cleared = await update([ + { id: a, type: "TEXT", prefill: "NONE" }, + { id: b, type: "TEXT", prefill: null }, + { id: c, type: "RADIO", prefill: null }, + ]) + expect(cleared.map((q) => q.prefill)).toEqual([ + null, + "DIETARY_RESTRICTIONS", + null, + ]) + })) }) diff --git a/@app/db/__tests__/app_public/functions/update_event_quotas.test.ts b/@app/db/__tests__/app_public/functions/update_event_quotas.test.ts index ca0a3967d..ee9a9aa44 100644 --- a/@app/db/__tests__/app_public/functions/update_event_quotas.test.ts +++ b/@app/db/__tests__/app_public/functions/update_event_quotas.test.ts @@ -29,8 +29,8 @@ describe("Test app_public.update_event_quotas function", () => { `select app_public.update_event_quotas( $1, array[ - row($2::uuid, 0::smallint, $3::jsonb, 5::smallint), - row(null, 1::smallint, $4::jsonb, 10::smallint) + row($2::uuid, 0::smallint, $3::jsonb, 5::smallint, 0), + row(null, 1::smallint, $4::jsonb, 10::smallint, 0) ]::app_public.update_event_quotas[] )`, [ diff --git a/@app/db/__tests__/app_public/tables/feature_flags.test.ts b/@app/db/__tests__/app_public/tables/feature_flags.test.ts new file mode 100644 index 000000000..835e8a8d2 --- /dev/null +++ b/@app/db/__tests__/app_public/tables/feature_flags.test.ts @@ -0,0 +1,104 @@ +import { PoolClient } from "pg" + +import { + asRoot, + upsertFeatureFlag, + withAdminUserDb, + withAnonymousDb, + withDeveloperUserDb, + withUserDb, +} from "../../helpers" + +const selectTestFlags = async (client: PoolClient) => { + const { rows } = await client.query( + "select key from app_public.feature_flags where key = 'test_flag'" + ) + return rows +} + +describe("app_public.feature_flags", () => { + it("is readable by developers", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + expect(await selectTestFlags(client)).toEqual([{ key: "test_flag" }]) + })) + + it("is not readable by admins who are not developers", () => + withAdminUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + expect(await selectTestFlags(client)).toEqual([]) + })) + + it("is not readable by regular users", () => + withUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + expect(await selectTestFlags(client)).toEqual([]) + })) + + it("is not readable by anonymous users", () => + withAnonymousDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "on") + expect(await selectTestFlags(client)).toEqual([]) + })) + + it("cannot be updated directly, even by developers", () => + withDeveloperUserDb(async (client) => { + await upsertFeatureFlag(client, "test_flag", "off") + await expect( + client.query( + "update app_public.feature_flags set state = 'on' where key = 'test_flag'" + ) + ).rejects.toThrow("permission denied") + })) + + it("cannot be inserted into directly, even by developers", () => + withDeveloperUserDb(async (client) => { + await expect( + client.query( + "insert into app_public.feature_flags (key, description) values ('test_new', 'x')" + ) + ).rejects.toThrow("permission denied") + })) +}) + +describe("app_public.users.is_developer", () => { + it("cannot be set by a user on themselves", () => + withAdminUserDb(async (client, user) => { + await expect( + client.query( + "update app_public.users set is_developer = true where id = $1", + [user.id] + ) + ).rejects.toThrow("permission denied") + })) + + it("is readable and defaults to false", () => + withUserDb(async (client, user) => { + const { + rows: [row], + } = await client.query( + "select is_developer from app_public.users where id = $1", + [user.id] + ) + expect(row.is_developer).toBe(false) + })) + + it("makes current_user_is_developer true only together with is_admin", () => + withDeveloperUserDb(async (client, user) => { + const isDeveloper = async () => + ( + await client.query( + "select app_public.current_user_is_developer() as v" + ) + ).rows[0].v + expect(await isDeveloper()).toBe(true) + + await asRoot(client, () => + client.query( + "update app_public.users set is_admin = false where id = $1", + [user.id] + ) + ) + expect(await isDeveloper()).toBe(false) + })) +}) diff --git a/@app/db/__tests__/app_public/tables/feature_flags_registry.test.ts b/@app/db/__tests__/app_public/tables/feature_flags_registry.test.ts new file mode 100644 index 000000000..06e8ab3ac --- /dev/null +++ b/@app/db/__tests__/app_public/tables/feature_flags_registry.test.ts @@ -0,0 +1,109 @@ +import { featureKeys } from "@app/lib" +import { PoolClient } from "pg" + +import { poolFromUrl, TEST_DATABASE_URL, withRootDb } from "../../helpers" + +/* + * The registry in @app/lib/src/featureFlags.ts and the rows in + * app_public.feature_flags must name the same features: the migration that + * adds a feature inserts its row, and removing a flag deletes the registry + * entry while the row stays, retired, until a later migration deletes it. + */ + +const registryKeys = () => [...featureKeys()].sort() as string[] + +/* + * Keys passed as literals to feature_enabled() in function bodies and row + * level security policies that are neither in the registry nor retired. SQL + * gates are invisible to the compiler, so this is what catches a gate left + * behind when a key is removed from the registry. + */ +const findUnregisteredSqlGates = async (client: PoolClient) => { + const { rows } = await client.query<{ source: string; key: string }>( + `with sources as ( + select p.oid::regprocedure::text as source, p.prosrc as body + from pg_proc as p + join pg_namespace as n on n.oid = p.pronamespace + where n.nspname not in ('pg_catalog', 'information_schema') + union all + select format('policy %s on %s', pol.polname, pol.polrelid::regclass), + concat_ws(' ', + pg_get_expr(pol.polqual, pol.polrelid), + pg_get_expr(pol.polwithcheck, pol.polrelid)) + from pg_policy as pol + ) + select distinct s.source, m[1] as key + from sources as s, + regexp_matches(s.body, 'feature_enabled\\s*\\(\\s*''([^'']*)''', 'g') as m + where not exists ( + select 1 from app_public.feature_flags as f + where f.key = m[1] and f.retired_at is not null + ) + order by 1, 2` + ) + const registered = new Set(registryKeys()) + return rows.filter((row) => !registered.has(row.key)) +} + +describe("feature flag registry", () => { + it("has a row for every key, and every non-retired row has a key", async () => { + const { rows } = await poolFromUrl(TEST_DATABASE_URL).query<{ + key: string + }>( + "select key from app_public.feature_flags where retired_at is null order by key" + ) + expect(rows.map((row) => row.key)).toEqual(registryKeys()) + }) + + it("has no SQL gate for a key outside the registry", () => + withRootDb(async (client) => { + expect(await findUnregisteredSqlGates(client)).toEqual([]) + })) + + describe("the SQL gate scan", () => { + it("reports a function that gates on an unknown key", () => + withRootDb(async (client) => { + await client.query( + `create function app_public.registry_test_gate() returns boolean as $$ + select app_public.feature_enabled( 'registry_test_unknown' ) + $$ language sql stable` + ) + expect(await findUnregisteredSqlGates(client)).toEqual([ + { + source: "app_public.registry_test_gate()", + key: "registry_test_unknown", + }, + ]) + })) + + it("reports a policy that gates on an unknown key", () => + withRootDb(async (client) => { + await client.query( + `create table app_public.registry_test_table (id int); + create policy registry_test_policy on app_public.registry_test_table + for select using (app_public.feature_enabled('registry_test_policy_key'))` + ) + expect(await findUnregisteredSqlGates(client)).toEqual([ + { + source: + "policy registry_test_policy on app_public.registry_test_table", + key: "registry_test_policy_key", + }, + ]) + })) + + it("allows a gate whose flag is retired", () => + withRootDb(async (client) => { + await client.query( + `insert into app_public.feature_flags (key, description, retired_at) + values ('registry_test_retired', 'Test flag', now())` + ) + await client.query( + `create function app_public.registry_test_gate() returns boolean as $$ + select app_public.feature_enabled('registry_test_retired') + $$ language sql stable` + ) + expect(await findUnregisteredSqlGates(client)).toEqual([]) + })) + }) +}) diff --git a/@app/db/__tests__/app_public/tables/payments.test.ts b/@app/db/__tests__/app_public/tables/payments.test.ts new file mode 100644 index 000000000..19a750c1b --- /dev/null +++ b/@app/db/__tests__/app_public/tables/payments.test.ts @@ -0,0 +1,166 @@ +import { PoolClient } from "pg" + +import { + becomeUser, + createUsers, + poolFromUrl, + resetFeatureFlags, + setFeatureFlag, + TEST_DATABASE_URL, + withAdminUserDb, + withRootDb, +} from "../../helpers" +import { + createOrganizationMember, + createPaidEventData, + insertPayment, + register, +} from "../../payments" + +// The payments flag is on (and available) for this file; what the database +// refuses while it is off is tested in payments_flag_off.test.ts +beforeAll(async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + await resetFeatureFlags(pool) + await setFeatureFlag(pool, "payments", "on") +}) +afterAll(() => resetFeatureFlags(poolFromUrl(TEST_DATABASE_URL))) + +describe("app_public.payments", () => { + describe("row level security", () => { + /** Makes the user the test then views as, returning their id (null: anonymous). */ + type Viewer = ( + client: PoolClient, + organizationId: string + ) => Promise + + const anonymous: Viewer = async () => null + const aUserWithoutEventPermissions: Viewer = async (client) => { + const [user] = await createUsers(client, 1) + return user.id + } + const aMember: Viewer = async (client, organizationId) => { + const member = await createOrganizationMember(client, organizationId) + return member.id + } + const anAdmin: Viewer = async (client) => { + const [admin] = await createUsers(client, 1, true, true) + return admin.id + } + + const nothing = () => [] + const thePayment = (payment: { id: string }) => [{ id: payment.id }] + + it.each([ + ["hides payments from anonymous users", anonymous, nothing], + [ + "hides payments from logged in users without event permissions", + aUserWithoutEventPermissions, + nothing, + ], + [ + "shows payments to members of the event's organization", + aMember, + thePayment, + ], + ["shows payments to admins", anAdmin, thePayment], + ])("%s", (_case, viewer, visiblePayments) => + withRootDb(async (client) => { + const { organization, event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + const payment = await insertPayment(client, registration) + + await becomeUser(client, await viewer(client, organization.id)) + const { rows } = await client.query( + "select id from app_public.payments where event_id = $1", + [event.id] + ) + expect(rows).toEqual(visiblePayments(payment)) + }) + ) + + it("does not let visitors write payments directly", () => + withAdminUserDb(async (client, admin) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + const payment = await insertPayment(client, registration) + await becomeUser(client, admin.id) + + await client.query("savepoint s") + await expect( + client.query( + `insert into app_public.payments(event_name, quota_title, method, ticket_amount_cents) + values ('{}', '{}', 'MANUAL', 100)` + ) + ).rejects.toThrow("permission denied") + await client.query("rollback to savepoint s") + + await expect( + client.query( + "update app_public.payments set status = 'EXPIRED' where id = $1", + [payment.id] + ) + ).rejects.toThrow("permission denied") + await client.query("rollback to savepoint s") + + await expect( + client.query("delete from app_public.payments where id = $1", [ + payment.id, + ]) + ).rejects.toThrow("permission denied") + await client.query("rollback to savepoint s") + })) + }) + + describe("one paid payment per registration", () => { + it("allows any number of non-paid rows next to a paid one, but rejects a second PAID row", () => + withRootDb(async (client) => { + const { event, quota } = await createPaidEventData(client) + const { registration } = await register(client, event.id, quota.id) + await insertPayment(client, registration, { status: "PAID" }) + await insertPayment(client, registration, { status: "EXPIRED" }) + await insertPayment(client, registration, { status: "PENDING" }) + + const { rows } = await client.query( + "select count(*)::int as count from app_public.payments where registration_id = $1", + [registration.id] + ) + expect(rows[0].count).toBe(3) + + await expect( + insertPayment(client, registration, { status: "PAID" }) + ).rejects.toThrow("payments_one_paid_per_registration_idx") + })) + }) +}) + +describe("payment check constraints", () => { + it.each([1, 24, -25, 1000001, 2147483647])( + "rejects a quota price of %i cents", + (price) => + withRootDb(async (client) => { + const { quota } = await createPaidEventData(client) + await expect( + client.query( + "update app_public.quotas set price_cents = $2 where id = $1", + [quota.id, price] + ) + ).rejects.toThrow( + 'violates check constraint "quotas_price_cents_check"' + ) + }) + ) + + it.each([0, 25, 1800, 1000000])( + "accepts a quota price of %i cents", + (price) => + withRootDb(async (client) => { + const { quota } = await createPaidEventData(client) + const { rows } = await client.query( + "update app_public.quotas set price_cents = $2 where id = $1 returning price_cents", + [quota.id, price] + ) + expect(rows[0].price_cents).toBe(price) + }) + ) +}) diff --git a/@app/db/__tests__/app_public/tables/registration_profiles.test.ts b/@app/db/__tests__/app_public/tables/registration_profiles.test.ts new file mode 100644 index 000000000..18a93e7e5 --- /dev/null +++ b/@app/db/__tests__/app_public/tables/registration_profiles.test.ts @@ -0,0 +1,294 @@ +import { PoolClient } from "pg" + +import { + becomeRoot, + becomeUser, + createEventCategories, + createEvents, + createOrganizations, + createQuestions, + createQuotas, + createUsers, + FeatureState, + upsertFeatureFlag, + withAnonymousDb, + withRootDb, + withUserDb, +} from "../../helpers" + +async function setRegistrationProfile( + client: PoolClient, + telegram: string | null, + dietaryRestrictions: string | null +) { + const { + rows: [profile], + } = await client.query( + `select * from app_public.set_registration_profile($1, $2)`, + [telegram, dietaryRestrictions] + ) + return profile +} + +async function deleteRegistrationProfile(client: PoolClient) { + const { + rows: [{ deleted }], + } = await client.query( + `select app_public.delete_registration_profile() as deleted` + ) + return deleted +} + +const setPrefillAnswers = (client: PoolClient, state: FeatureState) => + upsertFeatureFlag(client, "prefill_answers", state) + +/** + * Creates an open event whose two TEXT questions are marked to be prefilled + * with the telegram handle and dietary restrictions, and an unfinished + * registration to it, the way claim_registration_token leaves one. + */ +async function setupRegistration(client: PoolClient, email: string) { + await becomeRoot(client) + const [organization] = await createOrganizations(client, 1) + const [eventCategory] = await createEventCategories( + client, + 1, + organization.id + ) + const [event] = await createEvents( + client, + 1, + organization.id, + eventCategory.id + ) + const [quota] = await createQuotas(client, 1, event.id) + const [telegramQuestion, dietaryQuestion] = await createQuestions( + client, + 2, + event.id, + false, + "TEXT" as any + ) + await client.query( + `update app_public.event_questions set prefill = 'TELEGRAM' where id = $1`, + [telegramQuestion.id] + ) + await client.query( + `update app_public.event_questions set prefill = 'DIETARY_RESTRICTIONS' where id = $1`, + [dietaryQuestion.id] + ) + const { + rows: [registration], + } = await client.query( + `insert into app_public.registrations(event_id, quota_id, first_name, last_name, email) + values ($1, $2, 'Testi', 'Testaaja', $3) + returning *`, + [event.id, quota.id, email] + ) + return { registration, telegramQuestion, dietaryQuestion } +} + +// The registration is finished by create_registration, a security definer +// function, so the update runs as root with the user's session still set. +async function finishRegistration( + client: PoolClient, + registrationId: string, + answers: Record +) { + await becomeRoot(client) + await client.query( + `update app_public.registrations set answers = $2, is_finished = true where id = $1`, + [registrationId, answers] + ) +} + +async function getProfile(client: PoolClient, userId: string) { + await becomeRoot(client) + const { + rows: [profile], + } = await client.query( + `select * from app_public.registration_profiles where user_id = $1`, + [userId] + ) + return profile +} + +describe("app_public.registration_profiles", () => { + describe("with prefill_answers on", () => { + it("can set and update own registration profile", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + const created = await setRegistrationProfile( + client, + "@testi", + "Vegaani" + ) + expect(created).toMatchObject({ + user_id: user.id, + telegram: "@testi", + dietary_restrictions: "Vegaani", + }) + + // Empty values clear the saved value + const updated = await setRegistrationProfile(client, " @uusi ", "") + expect(updated).toMatchObject({ + user_id: user.id, + telegram: "@uusi", + dietary_restrictions: null, + }) + })) + + it("keeps the saved value of a null argument", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@vanha", "Vegaani") + + expect( + await setRegistrationProfile(client, "@uusi", null) + ).toMatchObject({ telegram: "@uusi", dietary_restrictions: "Vegaani" }) + expect( + await setRegistrationProfile(client, null, "Gluteeniton") + ).toMatchObject({ + telegram: "@uusi", + dietary_restrictions: "Gluteeniton", + }) + })) + + it("refuses an over-length value and keeps the saved profile", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@testi", "Vegaani") + + await client.query("savepoint too_long") + await expect( + setRegistrationProfile(client, "@" + "a".repeat(64), null) + ).rejects.toMatchObject({ code: "23514" }) + await client.query("rollback to savepoint too_long") + + expect(await getProfile(client, user.id)).toMatchObject({ + telegram: "@testi", + dietary_restrictions: "Vegaani", + }) + })) + + it("cannot see another user's registration profile", () => + withRootDb(async (client) => { + await setPrefillAnswers(client, "on") + const [user, otherUser] = await createUsers(client, 2) + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@testi", "Gluteeniton") + + await becomeUser(client, otherUser.id) + const { rows } = await client.query( + `select * from app_public.registration_profiles` + ) + expect(rows).toHaveLength(0) + })) + + it("cannot set a registration profile when logged out", () => + withAnonymousDb(async (client) => { + await setPrefillAnswers(client, "on") + const promise = setRegistrationProfile(client, "@testi", "Vegaani") + await expect(promise).rejects.toMatchObject({ code: "LOGIN" }) + })) + + it("can delete own registration profile", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@testi", "Vegaani") + + expect(await deleteRegistrationProfile(client)).toBe(true) + expect(await deleteRegistrationProfile(client)).toBe(false) + expect(await getProfile(client, user.id)).toBeUndefined() + })) + + it("does not save answers when the user finishes a registration", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + const { registration, telegramQuestion, dietaryQuestion } = + await setupRegistration(client, user._email) + + await becomeUser(client, user.id) + await finishRegistration(client, registration.id, { + [telegramQuestion.id]: "@testi", + [dietaryQuestion.id]: "Laktoositon", + }) + + expect(await getProfile(client, user.id)).toBeUndefined() + })) + + it("finishes a registration whose prefill answer is over-length", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@vanha", "Vegaani") + const { registration, telegramQuestion } = await setupRegistration( + client, + user._email + ) + + await becomeUser(client, user.id) + await finishRegistration(client, registration.id, { + [telegramQuestion.id]: "@" + "a".repeat(200), + }) + + await becomeRoot(client) + const { + rows: [finished], + } = await client.query( + `select is_finished from app_public.registrations where id = $1`, + [registration.id] + ) + expect(finished.is_finished).toBe(true) + expect(await getProfile(client, user.id)).toMatchObject({ + telegram: "@vanha", + dietary_restrictions: "Vegaani", + }) + })) + }) + + describe("with prefill_answers off", () => { + it("refuses to save a registration profile", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "off") + await becomeUser(client, user.id) + const promise = setRegistrationProfile(client, "@testi", "Vegaani") + await expect(promise).rejects.toMatchObject({ code: "FTOFF" }) + })) + + it("still reads and deletes own registration profile", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "on") + await becomeUser(client, user.id) + await setRegistrationProfile(client, "@testi", "Vegaani") + await setPrefillAnswers(client, "off") + await becomeUser(client, user.id) + + const { rows } = await client.query( + `select telegram from app_public.registration_profiles` + ) + expect(rows).toEqual([{ telegram: "@testi" }]) + expect(await deleteRegistrationProfile(client)).toBe(true) + expect(await getProfile(client, user.id)).toBeUndefined() + })) + + it("does not save answers when the user finishes a registration", () => + withUserDb(async (client, user) => { + await setPrefillAnswers(client, "off") + const { registration, telegramQuestion, dietaryQuestion } = + await setupRegistration(client, user._email) + + await becomeUser(client, user.id) + await finishRegistration(client, registration.id, { + [telegramQuestion.id]: "@testi", + [dietaryQuestion.id]: "Laktoositon", + }) + + expect(await getProfile(client, user.id)).toBeUndefined() + })) + }) +}) diff --git a/@app/db/__tests__/app_public/views/registrations_status_and_position.test.ts b/@app/db/__tests__/app_public/views/registrations_status_and_position.test.ts index f8e33311f..7b0e4f52f 100644 --- a/@app/db/__tests__/app_public/views/registrations_status_and_position.test.ts +++ b/@app/db/__tests__/app_public/views/registrations_status_and_position.test.ts @@ -2,15 +2,74 @@ import { PoolClient } from "pg" import { becomeRoot, + becomeUser, createEventCategories, createEvents, createOrganizations, createQuotas, createRegistrations, + createUsers, deleteTestData, + getJobs, + poolFromUrl, + TEST_DATABASE_URL, withUserDb, } from "../../helpers" +/* + * The statuses and positions of every registration, as defined by the + * materialized view of migration 000002. The maintained table must always + * hold exactly these rows. + */ +const REFERENCE_POSITIONS_QUERY = ` + with cte1 as ( + select + r.id, + size, + e.id as event_id, + q.id as quota_id, + e.open_quota_size, + r.created_at, + row_number() over (partition by r.quota_id order by r.created_at asc) as tmp_pos_quota + from app_public.registrations r + left join app_public.quotas q + on r.quota_id = q.id + left join app_public.events e + on r.event_id = e.id + ), cte2 as ( + select + tmp.*, + row_number() over (partition by event_id, tmp_status order by created_at asc) as tmp_pos_status + from ( + select + *, + case + when tmp_pos_quota <= size then 'IN_QUOTA'::text + else 'OPEN_OR_QUEUE'::text + end as tmp_status + from cte1 + ) as tmp + ), cte3 as ( + select + *, + case + when tmp_status = 'OPEN_OR_QUEUE'::text and tmp_pos_status <= open_quota_size then 'IN_OPEN_QUOTA'::app_public.registration_status + when tmp_status = 'OPEN_OR_QUEUE'::text then 'IN_QUEUE'::app_public.registration_status + else 'IN_QUOTA'::app_public.registration_status + end as status + from cte2 + ) select + id, + event_id, + quota_id, + status, + case + when status = 'IN_QUOTA'::app_public.registration_status then cast(row_number() over (partition by quota_id, status order by created_at asc) as integer) + else cast(row_number() over (partition by event_id, status order by created_at asc) as integer) + end as position + from cte3 +` + async function setupData(client: PoolClient, opts) { const { openQuotaSize, numQuotas, quotaSize } = opts const [organization] = await createOrganizations(client, 1) @@ -166,4 +225,643 @@ describe("registrations_status_and_position", () => { expect(sorted[8].position).toEqual(2) expect(sorted[9].position).toEqual(4) })) + + describe("maintained per event", () => { + afterAll(deleteTestData) + + // Registers `count` people one transaction at a time so that each + // registration gets a distinct created_at. + async function registerInOrder( + client: PoolClient, + count: number, + eventId: string, + quotaId: string + ) { + const registrations = [] + for (let i = 0; i < count; i++) { + const [reg] = await createRegistrations(client, 1, eventId, quotaId, []) + await client.query("commit") + registrations.push(reg) + } + return registrations + } + + async function positionsOf(client: PoolClient, ids: string[]) { + const { rows } = await client.query( + `select id, status, position + from app_hidden.registrations_status_and_position + where id = any($1::uuid[])`, + [ids] + ) + return ids.map((id) => { + const row = rows.find((r) => r.id === id) + return row ? { status: row.status, position: row.position } : null + }) + } + + it("is current right after each registration is inserted", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 2, + }) + const registrations = await registerInOrder( + client, + 3, + event.id, + quotas[0].id + ) + + expect( + await positionsOf( + client, + registrations.map((r) => r.id) + ) + ).toEqual([ + { status: "IN_QUOTA", position: 1 }, + { status: "IN_QUOTA", position: 2 }, + { status: "IN_QUEUE", position: 1 }, + ]) + })) + + it("leaves other events' rows untouched", () => + withUserDb(async (client) => { + const a = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const b = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + await registerInOrder(client, 2, a.event.id, a.quotas[0].id) + + const rowsOfA = async () => + ( + await client.query( + `select id, status, position, xmin::text as xmin + from app_hidden.registrations_status_and_position + where event_id = $1 + order by id`, + [a.event.id] + ) + ).rows + const before = await rowsOfA() + expect(before).toHaveLength(2) + + await registerInOrder(client, 2, b.event.id, b.quotas[0].id) + + expect(await rowsOfA()).toEqual(before) + })) + + it("recomputes positions when a quota grows", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 2, + }) + const registrations = await registerInOrder( + client, + 3, + event.id, + quotas[0].id + ) + + await client.query( + "update app_public.quotas set size = 3 where id = $1", + [quotas[0].id] + ) + + expect(await positionsOf(client, [registrations[2].id])).toEqual([ + { status: "IN_QUOTA", position: 3 }, + ]) + })) + + it("recomputes positions when the open quota size changes", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const registrations = await registerInOrder( + client, + 2, + event.id, + quotas[0].id + ) + + await client.query( + "update app_public.events set open_quota_size = 1 where id = $1", + [event.id] + ) + + expect(await positionsOf(client, [registrations[1].id])).toEqual([ + { status: "IN_OPEN_QUOTA", position: 1 }, + ]) + })) + + it("enqueues the first queued person when a full quota loses a registration", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 2, + }) + const registrations = await registerInOrder( + client, + 3, + event.id, + quotas[0].id + ) + + await client.query( + "delete from app_public.registrations where id = $1", + [registrations[1].id] + ) + + const jobs = await getJobs(client, "registration__process_queue") + expect(jobs).toHaveLength(1) + expect(jobs[0].payload).toMatchObject({ + receivedSpot: { + id: registrations[2].id, + event_id: event.id, + quota_id: quotas[0].id, + status: "IN_QUOTA", + position: 2, + }, + }) + expect( + await positionsOf(client, [registrations[0].id, registrations[2].id]) + ).toEqual([ + { status: "IN_QUOTA", position: 1 }, + { status: "IN_QUOTA", position: 2 }, + ]) + })) + + it("enqueues the earliest queued person of the quota when the queue head belongs to another quota", () => + withUserDb(async (client) => { + const { + event, + quotas: [quotaA, quotaB], + } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 2, + quotaSize: 1, + }) + const [inQuotaA] = await registerInOrder(client, 1, event.id, quotaA.id) + await registerInOrder(client, 2, event.id, quotaB.id) + const [queuedA] = await registerInOrder(client, 1, event.id, quotaA.id) + + await client.query( + "delete from app_public.registrations where id = $1", + [inQuotaA.id] + ) + + const jobs = await getJobs(client, "registration__process_queue") + expect(jobs).toHaveLength(1) + expect(jobs[0].payload).toMatchObject({ + receivedSpot: { + id: queuedA.id, + event_id: event.id, + quota_id: quotaA.id, + status: "IN_QUOTA", + position: 1, + }, + }) + })) + + async function queueJobIds(client: PoolClient) { + const jobs = await getJobs(client, "registration__process_queue") + return jobs.map((job) => job.payload.receivedSpot.id) + } + + it("emails the event's queue head when a quota spot is refilled from the open quota", () => + withUserDb(async (client) => { + const { + event, + quotas: [quotaX, quotaY], + } = await setupData(client, { + openQuotaSize: 1, + numQuotas: 2, + quotaSize: 1, + }) + // X1 is in quota X, X2 overflows into the open quota, Y1 is in quota + // Y and Y2 heads the event's queue. + const [x1] = await registerInOrder(client, 1, event.id, quotaX.id) + await registerInOrder(client, 1, event.id, quotaX.id) + await registerInOrder(client, 1, event.id, quotaY.id) + const [y2] = await registerInOrder(client, 1, event.id, quotaY.id) + + await client.query( + "delete from app_public.registrations where id = $1", + [x1.id] + ) + + expect(await queueJobIds(client)).toEqual([y2.id]) + expect(await positionsOf(client, [y2.id])).toEqual([ + { status: "IN_OPEN_QUOTA", position: 1 }, + ]) + })) + + it("emails queued people who get a spot when a quota grows", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const registrations = await registerInOrder( + client, + 3, + event.id, + quotas[0].id + ) + + await client.query( + "update app_public.quotas set size = 3 where id = $1", + [quotas[0].id] + ) + + expect((await queueJobIds(client)).sort()).toEqual( + [registrations[1].id, registrations[2].id].sort() + ) + })) + + it("emails queued people who get a spot when the open quota grows", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const registrations = await registerInOrder( + client, + 2, + event.id, + quotas[0].id + ) + + await client.query( + "update app_public.events set open_quota_size = 1 where id = $1", + [event.id] + ) + + expect(await queueJobIds(client)).toEqual([registrations[1].id]) + })) + + it("does not email unfinished registrations that leave the queue", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const [first] = await registerInOrder(client, 1, event.id, quotas[0].id) + await client.query( + "select * from app_public.claim_registration_token($1, $2)", + [event.id, quotas[0].id] + ) + + await client.query( + "delete from app_public.registrations where id = $1", + [first.id] + ) + + expect(await queueJobIds(client)).toEqual([]) + })) + + it("emails nobody when a queued registration is deleted", () => + withUserDb(async (client) => { + const { event, quotas } = await setupData(client, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + }) + const registrations = await registerInOrder( + client, + 3, + event.id, + quotas[0].id + ) + + await client.query( + "delete from app_public.registrations where id = $1", + [registrations[1].id] + ) + + expect(await queueJobIds(client)).toEqual([]) + })) + + it("keeps both of two concurrent claims with correct positions", async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + const setupClient = await pool.connect() + let event, quota + try { + await setupClient.query("begin") + const [user] = await createUsers(setupClient, 1) + await becomeUser(setupClient, user.id) + ;({ + event, + quotas: [quota], + } = await setupData(setupClient, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 5, + })) + await setupClient.query("commit") + } finally { + await setupClient.query("rollback") + setupClient.release() + } + + const client1 = await pool.connect() + const client2 = await pool.connect() + try { + await client1.query("begin") + await client1.query( + "select * from app_public.claim_registration_token($1, $2)", + [event.id, quota.id] + ) + + await client2.query("begin") + let claim2Done = false + const claim2 = client2 + .query("select * from app_public.claim_registration_token($1, $2)", [ + event.id, + quota.id, + ]) + .then((result) => { + claim2Done = true + return result + }) + + // Give the second claim time to reach the per-event lock. + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(claim2Done).toBe(false) + + await client1.query("commit") + await claim2 + await client2.query("commit") + } finally { + await client1.query("rollback").catch(() => {}) + await client2.query("rollback").catch(() => {}) + client1.release() + client2.release() + } + + const { rows } = await pool.query( + `select status, position + from app_hidden.registrations_status_and_position + where event_id = $1 + order by position`, + [event.id] + ) + expect(rows).toEqual([ + { status: "IN_QUOTA", position: 1 }, + { status: "IN_QUOTA", position: 2 }, + ]) + }) + + it("emails a registration made concurrently with the deletion of a quota spot", async () => { + const pool = poolFromUrl(TEST_DATABASE_URL) + const setupClient = await pool.connect() + let event, quota, firstRegistration + try { + await setupClient.query("begin") + const [user] = await createUsers(setupClient, 1) + await becomeUser(setupClient, user.id) + ;({ + event, + quotas: [quota], + } = await setupData(setupClient, { + openQuotaSize: 0, + numQuotas: 1, + quotaSize: 1, + })) + ;[firstRegistration] = await createRegistrations( + setupClient, + 1, + event.id, + quota.id, + [] + ) + await setupClient.query("commit") + } finally { + await setupClient.query("rollback") + setupClient.release() + } + + const client1 = await pool.connect() + const client2 = await pool.connect() + let claimedId: string + try { + await client1.query("begin") + ;[{ id: claimedId }] = await createRegistrations( + client1, + 1, + event.id, + quota.id, + [] + ) + + await client2.query("begin") + let deleteDone = false + const deletion = client2 + .query("delete from app_public.registrations where id = $1", [ + firstRegistration.id, + ]) + .then((result) => { + deleteDone = true + return result + }) + + // Give the deletion time to reach the per-event lock. + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(deleteDone).toBe(false) + + await client1.query("commit") + await deletion + await client2.query("commit") + } finally { + await client1.query("rollback").catch(() => {}) + await client2.query("rollback").catch(() => {}) + client1.release() + client2.release() + } + + const jobsClient = await pool.connect() + try { + const jobs = await getJobs(jobsClient, "registration__process_queue") + expect(jobs).toHaveLength(1) + expect(jobs[0].payload).toMatchObject({ + receivedSpot: { + id: claimedId, + event_id: event.id, + quota_id: quota.id, + status: "IN_QUOTA", + position: 1, + }, + }) + } finally { + jobsClient.release() + } + }) + }) + + describe("matches the reference definition", () => { + afterAll(deleteTestData) + + // Rows of the given events that are in the maintained table but not in + // the reference, and the other way round. + async function differences(client: PoolClient, eventIds: string[]) { + const query = (left: string, right: string) => + client.query( + `with reference as (${REFERENCE_POSITIONS_QUERY}), + maintained as ( + select id, event_id, quota_id, status, position + from app_hidden.registrations_status_and_position + ) + select * from ${left} where event_id = any($1::uuid[]) + except + select * from ${right} where event_id = any($1::uuid[])`, + [eventIds] + ) + const [{ rows: onlyMaintained }, { rows: onlyReference }] = + await Promise.all([ + query("maintained", "reference"), + query("reference", "maintained"), + ]) + return { onlyMaintained, onlyReference } + } + + it("after inserts, deletes and quota and event changes", () => + withUserDb(async (client) => { + const [organization] = await createOrganizations(client, 1) + const [eventCategory] = await createEventCategories( + client, + 1, + organization.id + ) + const createEvent = async (openQuotaSize: number, sizes: number[]) => { + const [event] = await createEvents( + client, + 1, + organization.id, + eventCategory.id, + true, + false, + openQuotaSize + ) + const quotas = [] + for (const [position, size] of sizes.entries()) { + const { + rows: [quota], + } = await client.query( + `insert into app_public.quotas(event_id, position, title, size) + values ($1, $2, $3, $4) + returning *`, + [event.id, position, { fi: "Kiintiö", en: "Quota" }, size] + ) + quotas.push(quota) + } + return { event, quotas } + } + const first = await createEvent(2, [1, 3, 2]) + const second = await createEvent(1, [2, 1]) + await becomeRoot(client) + const eventIds = [first.event.id, second.event.id] + + const expectMatch = async () => + expect(await differences(client, eventIds)).toEqual({ + onlyMaintained: [], + onlyReference: [], + }) + + // Interleave registrations across events and quotas, one transaction + // each so that every registration gets a distinct created_at. + const order = [ + first.quotas[0], + second.quotas[0], + first.quotas[1], + first.quotas[0], + second.quotas[1], + first.quotas[2], + second.quotas[1], + first.quotas[0], + second.quotas[0], + first.quotas[1], + second.quotas[1], + first.quotas[0], + second.quotas[0], + first.quotas[2], + first.quotas[2], + second.quotas[1], + ] + const registrations = [] + for (const quota of order) { + const [registration] = await createRegistrations( + client, + 1, + quota.event_id, + quota.id, + [] + ) + await client.query("commit") + registrations.push(registration) + await expectMatch() + } + + const deleteRegistration = async (index: number) => { + await client.query( + "delete from app_public.registrations where id = $1", + [registrations[index].id] + ) + await expectMatch() + } + await deleteRegistration(0) + await deleteRegistration(3) + await deleteRegistration(11) + await deleteRegistration(6) + + const setQuotaSize = async (quotaId: string, size: number) => { + await client.query( + "update app_public.quotas set size = $2 where id = $1", + [quotaId, size] + ) + await expectMatch() + } + await setQuotaSize(first.quotas[1].id, 1) + await setQuotaSize(second.quotas[1].id, 4) + await setQuotaSize(first.quotas[0].id, 5) + + const setOpenQuotaSize = async (eventId: string, size: number) => { + await client.query( + "update app_public.events set open_quota_size = $2 where id = $1", + [eventId, size] + ) + await expectMatch() + } + await setOpenQuotaSize(first.event.id, 0) + await setOpenQuotaSize(second.event.id, 3) + + await client.query("delete from app_public.events where id = $1", [ + second.event.id, + ]) + await expectMatch() + const { + rows: [{ count }], + } = await client.query( + `select count(*)::int as count + from app_hidden.registrations_status_and_position + where event_id = $1`, + [second.event.id] + ) + expect(count).toEqual(0) + })) + }) }) diff --git a/@app/db/__tests__/helpers.ts b/@app/db/__tests__/helpers.ts index 594ab0b84..d202912b6 100644 --- a/@app/db/__tests__/helpers.ts +++ b/@app/db/__tests__/helpers.ts @@ -108,6 +108,15 @@ export const withAdminUserDb = ( await fn(client, user) }) +export const withDeveloperUserDb = ( + fn: (client: PoolClient, user: User) => Promise +) => + withRootDb(async (client) => { + const [user] = await createUsers(client, 1, true, true, true) + await becomeUser(client, user.id) + await fn(client, user) + }) + export const withAnonymousDb = (fn: (client: PoolClient) => Promise) => withRootDb(async (client) => { await becomeUser(client, null) @@ -133,6 +142,33 @@ export const becomeUser = async ( ) } +export type FeatureState = "off" | "admins_only" | "on" + +/* + * Inserts a feature flag row, or overwrites an existing one, as root. The + * surrounding test transaction is rolled back, so nothing needs cleaning up. + */ +export const upsertFeatureFlag = ( + client: PoolClient, + key: string, + state: FeatureState, + { + available = true, + retired = false, + }: { available?: boolean; retired?: boolean } = {} +) => + asRoot(client, () => + client.query( + `insert into app_public.feature_flags (key, state, available, description, retired_at) + values ($1, $2, $3, 'Test flag', case when $4::boolean then now() end) + on conflict (key) do update + set state = excluded.state, + available = excluded.available, + retired_at = excluded.retired_at`, + [key, state, available, retired] + ) + ) + export const getSessions = async (client: PoolClient, userId: string) => { const { rows } = await asRoot(client, () => client.query( diff --git a/@app/db/__tests__/migrations/000008_blank_names.test.ts b/@app/db/__tests__/migrations/000008_blank_names.test.ts new file mode 100644 index 000000000..ffb11530f --- /dev/null +++ b/@app/db/__tests__/migrations/000008_blank_names.test.ts @@ -0,0 +1,197 @@ +import { promises as fs } from "fs" +import { tmpdir } from "os" +import { join } from "path" + +import { migrate, reset, Settings } from "graphile-migrate" +import { Client } from "pg" + +/* + * committed/000008.sql replaces the `constrained_name` check, which accepted + * an empty string, with one that requires a non-whitespace character. A + * database that stores a blank registration name must still migrate: the + * migration turns those names into null before it adds the check. + * + * This test builds a scratch database from the committed migrations up to + * 000007, stores registrations with blank names there, and then applies the + * remaining migrations the way a deploy does (`graphile-migrate migrate`). + */ + +const MIGRATIONS = join(__dirname, "../../migrations") +const BEFORE = "000008" +const { + ROOT_DATABASE_URL, + DATABASE_HOST, + DATABASE_NAME, + DATABASE_OWNER, + DATABASE_OWNER_PASSWORD, + DATABASE_AUTHENTICATOR, + DATABASE_VISITOR, + AZURE_DB_OWNER, +} = process.env +const SCRATCH_DATABASE = `${DATABASE_NAME}_migration_check` + +let folder: string +let settings: Settings + +async function withScratchDb(callback: (client: Client) => Promise) { + const url = new URL(ROOT_DATABASE_URL!) + url.pathname = `/${SCRATCH_DATABASE}` + const client = new Client({ connectionString: url.toString() }) + await client.connect() + try { + return await callback(client) + } finally { + await client.end() + } +} + +/** Copies the committed migrations that `include` selects into `folder`. */ +async function copyCommitted(include: (filename: string) => boolean) { + const files = await fs.readdir(join(MIGRATIONS, "committed")) + for (const file of files.filter((f) => f.endsWith(".sql") && include(f))) { + await fs.copyFile( + join(MIGRATIONS, "committed", file), + join(folder, "committed", file) + ) + } +} + +beforeAll(async () => { + folder = await fs.mkdtemp(join(tmpdir(), "ilmo-migrations-")) + await fs.mkdir(join(folder, "committed")) + await fs.writeFile(join(folder, "current.sql"), "") + await fs.copyFile( + join(MIGRATIONS, "afterReset.sql"), + join(folder, "afterReset.sql") + ) + settings = { + connectionString: `postgres://${DATABASE_OWNER}:${DATABASE_OWNER_PASSWORD}@${DATABASE_HOST}/${SCRATCH_DATABASE}`, + rootConnectionString: ROOT_DATABASE_URL, + migrationsFolder: folder, + pgSettings: { search_path: "app_public,app_private,app_hidden,public" }, + placeholders: { + ":DATABASE_AUTHENTICATOR": DATABASE_AUTHENTICATOR!, + ":DATABASE_VISITOR": DATABASE_VISITOR!, + ":AZURE_DB_OWNER": AZURE_DB_OWNER || DATABASE_OWNER!, + }, + // As in @app/db/.gmrc + afterReset: [ + "!afterReset.sql", + { + _: "command", + command: + 'cross-env DATABASE_URL="$GM_DBURL" pnpm --filter @app/worker run install-db-schema', + }, + ], + } + // graphile-migrate logs every migration it runs + jest.spyOn(console, "info").mockImplementation(() => {}) +}) + +afterAll(async () => { + const client = new Client({ connectionString: ROOT_DATABASE_URL }) + await client.connect() + await client.query(`drop database if exists ${SCRATCH_DATABASE}`) + await client.end() + await fs.rm(folder, { recursive: true, force: true }) +}) + +it("turns blank registration names into null before checking them", async () => { + await copyCommitted((file) => file < BEFORE) + await reset(settings) + await migrate(settings) + + const ids = await withScratchDb(async (client) => { + // Stored as is, without the triggers (registration validity, emails) + await client.query("begin") + await client.query("set local session_replication_role = replica") + const { + rows: [{ id: organizationId }], + } = await client.query( + `insert into app_public.organizations (slug, name) + values ('blank-names', 'Blank names') returning id` + ) + const { + rows: [{ id: categoryId }], + } = await client.query( + `insert into app_public.event_categories (name, description, owner_organization_id) + values ('{"fi": "K", "en": "C"}', '{"fi": "K", "en": "C"}', $1) returning id`, + [organizationId] + ) + const { + rows: [{ id: eventId }], + } = await client.query( + `insert into app_public.events ( + slug, name, description, location, event_start_time, event_end_time, + registration_start_time, registration_end_time, open_quota_size, + owner_organization_id, category_id + ) values ( + 'blank-names', '{"fi": "T", "en": "E"}', '{"fi": "T", "en": "E"}', 'Here', + now() + interval '3 days', now() + interval '4 days', + now() - interval '1 day', now() + interval '1 day', 0, $1, $2 + ) returning id`, + [organizationId, categoryId] + ) + const { + rows: [{ id: quotaId }], + } = await client.query( + `insert into app_public.quotas (event_id, position, title, size) + values ($1, 0, '{"fi": "K", "en": "Q"}', 10) returning id`, + [eventId] + ) + const { rows } = await client.query( + `insert into app_public.registrations + (event_id, quota_id, first_name, last_name, is_finished, updated_at) + values + ($1, $2, '', 'Wright', true, '2030-01-01T00:00:00Z'), + ($1, $2, 'Anna', '', true, '2030-01-01T00:00:00Z'), + ($1, $2, '', '', true, '2030-01-01T00:00:00Z'), + ($1, $2, 'Kept', 'Name', true, '2030-01-01T00:00:00Z'), + ($1, $2, null, null, false, '2030-01-01T00:00:00Z') + returning id`, + [eventId, quotaId] + ) + await client.query("commit") + return rows.map((r) => r.id) + }) + + await copyCommitted((file) => file >= BEFORE) + await migrate(settings) + + await withScratchDb(async (client) => { + const { rows } = await client.query( + `select first_name, last_name, updated_at + from app_public.registrations + where id = any($1::uuid[]) + order by array_position($1::uuid[], id)`, + [ids] + ) + expect(rows.map((r) => [r.first_name, r.last_name])).toEqual([ + [null, "Wright"], + ["Anna", null], + [null, null], + ["Kept", "Name"], + [null, null], + ]) + // The cleanup ran without the table's triggers + for (const row of rows) { + expect(row.updated_at.toISOString()).toBe("2030-01-01T00:00:00.000Z") + } + + const { + rows: [{ triggers_disabled }], + } = await client.query( + `select count(*)::int as triggers_disabled from pg_catalog.pg_trigger + where tgrelid = 'app_public.registrations'::regclass + and not tgisinternal and tgenabled = 'D'` + ) + expect(triggers_disabled).toBe(0) + + await expect( + client.query( + `update app_public.registrations set first_name = ' ' where id = $1`, + [ids[3]] + ) + ).rejects.toThrow(/constrained_name_check/) + }) +}, 120000) diff --git a/@app/db/__tests__/payments.ts b/@app/db/__tests__/payments.ts new file mode 100644 index 000000000..906a92035 --- /dev/null +++ b/@app/db/__tests__/payments.ts @@ -0,0 +1,174 @@ +import { PoolClient } from "pg" + +import { + asRoot, + createEventCategories, + createEvents, + createQuotas, + createUsers, +} from "./helpers" + +/* + * Shared setup for the payments tests. Everything runs as root inside the + * caller's transaction (which the with*Db helpers roll back). + */ + +interface PaidEventOptions { + priceCents?: number + quotaSize?: number + openQuotaSize?: number +} + +/** + * Creates an organization (the current session's user, if any, becomes its + * owner member), a category, an event with an open signup and one quota, and sets + * the quota's price. + */ +export async function createPaidEventData( + client: PoolClient, + { + priceCents = 1800, + quotaSize = 10, + openQuotaSize = 0, + }: PaidEventOptions = {} +) { + return asRoot(client, async () => { + // Like createOrganizations, but also works without a logged in user + const { + rows: [organization], + } = await client.query( + `insert into app_public.organizations(slug, name, color) + values ('payments-org-' || gen_random_uuid(), 'Payments org', '#002e7d') + returning *` + ) + await client.query( + `insert into app_public.organization_memberships(organization_id, user_id, is_owner) + select $1, app_public.current_user_id(), true + where app_public.current_user_id() is not null`, + [organization.id] + ) + const [eventCategory] = await createEventCategories( + client, + 1, + organization.id + ) + const [createdEvent] = await createEvents( + client, + 1, + organization.id, + eventCategory.id, + true, + false, + openQuotaSize + ) + const [createdQuota] = await createQuotas( + client, + 1, + createdEvent.id, + quotaSize + ) + const { + rows: [quota], + } = await client.query( + `update app_public.quotas set price_cents = $2 where id = $1 returning *`, + [createdQuota.id, priceCents] + ) + return { organization, eventCategory, event: createdEvent, quota } + }) +} + +let registrationCounter = 0 + +/** + * Registers through the real flow: claim_registration_token followed by + * create_registration. + */ +export async function register( + client: PoolClient, + eventId: string, + quotaId: string +) { + return asRoot(client, async () => { + const { + rows: [tokens], + } = await client.query( + `select * from app_public.claim_registration_token($1, $2)`, + [eventId, quotaId] + ) + registrationCounter++ + const { + rows: [registration], + } = await client.query( + `select * from app_public.create_registration($1, $2, $3, $4, $5, $6)`, + [ + tokens.registration_token, + eventId, + quotaId, + "Testi", + "Henkilö", + `payer${registrationCounter}@example.com`, + ] + ) + return { registration, updateToken: tokens.update_token as string } + }) +} + +interface PaymentOptions { + method?: "STRIPE" | "MANUAL" + status?: "PENDING" | "PAID" | "EXPIRED" + ticketAmountCents?: number + serviceFeeCents?: number +} + +/** Inserts a payment row for a registration, as the server or worker would. */ +export async function insertPayment( + client: PoolClient, + registration: { id: string; event_id: string; quota_id: string }, + { + method = "STRIPE", + status = "PAID", + ticketAmountCents = 1800, + serviceFeeCents = method === "STRIPE" ? 25 : 0, + }: PaymentOptions = {} +) { + return asRoot(client, async () => { + const { + rows: [payment], + } = await client.query( + `insert into app_public.payments( + registration_id, event_id, quota_id, event_name, quota_title, + method, status, ticket_amount_cents, service_fee_cents, paid_at + ) + values ($1, $2, $3, '{"fi": "Tapahtuma", "en": "Event"}', '{"fi": "Kiintiö", "en": "Quota"}', + $4::app_public.payment_method, $5::app_public.payment_status, $6, $7, + case when $5::app_public.payment_status = 'PAID' then now() end) + returning *`, + [ + registration.id, + registration.event_id, + registration.quota_id, + method, + status, + ticketAmountCents, + serviceFeeCents, + ] + ) + return payment + }) +} + +/** Creates a non-admin user who is a member of the organization. */ +export async function createOrganizationMember( + client: PoolClient, + organizationId: string +) { + return asRoot(client, async () => { + const [user] = await createUsers(client, 1) + await client.query( + `insert into app_public.organization_memberships(organization_id, user_id) + values ($1, $2)`, + [organizationId, user.id] + ) + return user + }) +} diff --git a/@app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql b/@app/db/migrations/committed/000005.sql similarity index 81% rename from @app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql rename to @app/db/migrations/committed/000005.sql index 220ed34d7..a13e041a4 100644 --- a/@app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql +++ b/@app/db/migrations/committed/000005.sql @@ -1,3 +1,25 @@ +--! Previous: sha1:eafce160dd3a8ec859a47bc11b5c9117cc07fd8e +--! Hash: sha1:43ae0b3e314d8775763bfdb7015fb858183d247d + +--! split: 1-current.sql +/* + * Admins manage every organization, the same way `manage_admin` on + * `app_public.events` and `app_public.registrations` already lets them manage + * every event. Without this, `update_owner` is the only route to updating an + * organization, so changing one's settings requires an `is_owner` row in + * `organization_memberships` — which admins have no reason to hold, and which + * nobody holds for an organization they did not create. + * + * Membership keeps its own meaning: the way a non-admin is given rights over a + * single organization's events. + */ + +drop policy if exists manage_admin on app_public.organizations; + +create policy manage_admin on app_public.organizations + for all using (app_public.current_user_is_admin()); + +--! split: 2-delete-omitted-quotas-and-questions.sql /* * The admin UI sends an event's kept quotas with their ids and newly added * quotas with a null id. Deletion of omitted quotas is detected with diff --git a/@app/db/migrations/committed/000006.sql b/@app/db/migrations/committed/000006.sql new file mode 100644 index 000000000..1bb6d1aa8 --- /dev/null +++ b/@app/db/migrations/committed/000006.sql @@ -0,0 +1,260 @@ +--! Previous: sha1:43ae0b3e314d8775763bfdb7015fb858183d247d +--! Hash: sha1:14afad22610b41b44aa9252558421a99ebb91c56 + +--! split: 1-feature-flags.sql +/* + * Feature flags and the developer permission. + * + * A flag is a row in `app_public.feature_flags`, inserted by the migration + * that adds the gated feature. `app_public.feature_enabled(key)` is the + * authoritative gate; a key without a row reads as off. Only developers (users + * who are both admins and developers) can read the table or switch a flag, and + * every switch is recorded in `app_private.feature_flag_events`. + */ + +drop function if exists app_public.feature_flag_events(text); +drop function if exists app_private.set_feature_available(text, boolean); +drop function if exists app_public.set_feature_flag(text, app_public.feature_state); +drop function if exists app_public.enabled_features(); +drop function if exists app_public.feature_enabled(text); +drop table if exists app_private.feature_flag_events; +drop table if exists app_public.feature_flags; +drop type if exists app_public.feature_state; +drop procedure if exists app_public.check_is_developer(); +drop function if exists app_public.current_user_is_developer(); +alter table app_public.users drop column if exists is_developer; + +/* + * Developer permission. Mirrors `is_admin`: readable like the rest of the + * user row, never writable through the visitor role (the column is not in the + * `grant update` column list of `app_public.users`). + */ + +alter table app_public.users add column is_developer boolean not null default false; + +comment on column app_public.users.is_developer is + E'If true and the user is also an admin, the user can manage feature flags.'; + +create function app_public.current_user_is_developer() returns boolean as $$ + select exists ( + select 1 + from app_public.users + where + id = app_public.current_user_id() + and is_admin = true + and is_developer = true) +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.current_user_is_developer() is + E'Returns true if the current user is both an admin and a developer, false otherwise.'; + +create procedure app_public.check_is_developer() as $$ +begin + if not app_public.current_user_is_developer() then + raise exception 'Access denied. Only developers are allowed to use this mutation.' using errcode = 'DNIED'; + end if; +end; +$$ language plpgsql; + +/* + * Flags. + */ + +create type app_public.feature_state as enum ('off', 'admins_only', 'on'); + +comment on type app_public.feature_state is + E'State of a feature flag: off for everyone, on for signed-in admins only, or on for everyone.'; + +create table app_public.feature_flags ( + key text primary key check (key ~ '^[a-z][a-z0-9_]*$'), + state app_public.feature_state not null default 'off', + available boolean not null default true, + description text not null, + updated_at timestamptz not null default now(), + updated_by uuid references app_public.users on delete set null, + retired_at timestamptz +); +alter table app_public.feature_flags enable row level security; + +create index on app_public.feature_flags(updated_by); + +create policy select_developer on app_public.feature_flags + for select using (app_public.current_user_is_developer()); +grant select on app_public.feature_flags to :DATABASE_VISITOR; +-- NOTE: `insert`, `update` and `delete` are not granted. Rows are inserted by +-- migrations and changed through `set_feature_flag` and `set_feature_available`. + +comment on table app_public.feature_flags is + E'A feature that can be switched on or off at runtime. Rows are created by migrations.'; +comment on column app_public.feature_flags.key is + E'Identifier of the feature, as used in code.'; +comment on column app_public.feature_flags.state is + E'Who the feature is enabled for.'; +comment on column app_public.feature_flags.available is + E'False when the server lacks the configuration the feature needs; the feature then reads as off whatever its state.'; +comment on column app_public.feature_flags.description is + E'What the flag gates.'; +comment on column app_public.feature_flags.updated_at is + E'When the state was last changed.'; +comment on column app_public.feature_flags.updated_by is + E'Who last changed the state.'; +comment on column app_public.feature_flags.retired_at is + E'Set when the gates have been removed from code. A retired flag reads as on.'; +comment on constraint feature_flags_updated_by_fkey on app_public.feature_flags is + E'@omit many'; + +/* + * Audit log of state changes. The key is not a foreign key so that the history + * stays when a retired flag row is deleted. + */ + +create table app_private.feature_flag_events ( + id uuid primary key default gen_random_uuid(), + key text not null, + old_state app_public.feature_state not null, + new_state app_public.feature_state not null, + actor uuid references app_public.users on delete set null, + created_at timestamptz not null default now() +); +alter table app_private.feature_flag_events enable row level security; + +create index on app_private.feature_flag_events(key, created_at); +create index on app_private.feature_flag_events(actor); + +comment on table app_private.feature_flag_events is + E'One row per feature flag state change.'; + +/* + * Gates. + */ + +create function app_public.feature_enabled(key text) returns boolean as $$ + select exists ( + select 1 + from app_public.feature_flags as f + where + f.key = feature_enabled.key + and ( + f.retired_at is not null + or ( + f.available + and ( + f.state = 'on' + or (f.state = 'admins_only' and app_public.current_user_is_admin()) + ) + ) + )) +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.feature_enabled(key text) is + E'@omit\nTrue when the feature is enabled for the current user. Unknown keys read as off.'; + +create function app_public.enabled_features() returns setof text as $$ + select f.key + from app_public.feature_flags as f + where app_public.feature_enabled(f.key) + order by f.key; +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.enabled_features() is + E'@simpleCollections only\nKeys of the features enabled for the current user.'; + +/* + * Switching. + */ + +create function app_public.set_feature_flag(key text, state app_public.feature_state) +returns app_public.feature_flags as $$ +#variable_conflict use_variable +declare + v_flag app_public.feature_flags; + v_old_state app_public.feature_state; +begin + call app_public.check_is_developer(); + + select * into v_flag + from app_public.feature_flags as f + where f.key = key + for update; + + if v_flag.key is null then + raise exception 'Unknown feature flag "%".', key using errcode = 'NTFND'; + end if; + + if v_flag.retired_at is not null then + raise exception 'Feature flag "%" is retired and cannot be changed.', key using errcode = 'DNIED'; + end if; + + if state <> 'off' and not v_flag.available then + raise exception 'Feature flag "%" is not available: the server lacks the configuration it needs.', key using errcode = 'FTUNA'; + end if; + + if v_flag.state = state then + return v_flag; + end if; + + v_old_state = v_flag.state; + + update app_public.feature_flags as f + set + state = state, + updated_at = now(), + updated_by = app_public.current_user_id() + where f.key = key + returning * into v_flag; + + insert into app_private.feature_flag_events (key, old_state, new_state, actor) + values (key, v_old_state, state, app_public.current_user_id()); + + return v_flag; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.set_feature_flag(key text, state app_public.feature_state) is + E'Changes the state of an existing feature flag. Only accessible to developers.'; + +create function app_private.set_feature_available(key text, available boolean) returns boolean as $$ + with updated as ( + update app_public.feature_flags as f + set available = set_feature_available.available + where f.key = set_feature_available.key + returning 1 + ) + select exists (select 1 from updated); +$$ language sql volatile security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_private.set_feature_available(key text, available boolean) is + E'Records whether the server has the configuration a feature needs. Returns false for an unknown key. Does not change `updated_at`, which tracks state changes.'; + +/* + * Audit log for the admin page. + */ + +create function app_public.feature_flag_events(flag_key text default null) +returns table ( + id uuid, + key text, + old_state app_public.feature_state, + new_state app_public.feature_state, + actor_id uuid, + actor_username text, + actor_name text, + created_at timestamptz +) as $$ +begin + -- Cannot use call app_public.check_is_developer(); in a non volatile function + if not app_public.current_user_is_developer() then + raise exception 'Access denied. Only developers are allowed to use this query.' using errcode = 'DNIED'; + end if; + + return query + select e.id, e.key, e.old_state, e.new_state, e.actor, u.username::text, u.name, e.created_at + from app_private.feature_flag_events as e + left join app_public.users as u on u.id = e.actor + where flag_key is null or e.key = flag_key + order by e.created_at desc, e.id; +end; +$$ language plpgsql stable security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.feature_flag_events(flag_key text) is + E'@simpleCollections only\nFeature flag state changes, newest first, optionally for one key. Only accessible to developers.'; diff --git a/@app/db/migrations/committed/000007.sql b/@app/db/migrations/committed/000007.sql new file mode 100644 index 000000000..1b866763c --- /dev/null +++ b/@app/db/migrations/committed/000007.sql @@ -0,0 +1,25 @@ +--! Previous: sha1:14afad22610b41b44aa9252558421a99ebb91c56 +--! Hash: sha1:afc6149bc215d6e6cf1bcabba9005f9b07e231e0 + +--! split: 1-admin-preview-features.sql +/* + * Lets the client tell a feature that is on for everyone from one that an + * admin sees only because it is in `admins_only`, so that such UI can carry a + * preview marker. Non-admins always get an empty list. + */ + +drop function if exists app_public.admin_preview_features(); + +create function app_public.admin_preview_features() returns setof text as $$ + select f.key + from app_public.feature_flags as f + where + app_public.current_user_is_admin() + and f.retired_at is null + and f.available + and f.state = 'admins_only' + order by f.key; +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; + +comment on function app_public.admin_preview_features() is + E'@simpleCollections only\nKeys of the features enabled for the current user only because they are in admins_only. Empty unless the current user is an admin.'; diff --git a/@app/db/migrations/committed/000008.sql b/@app/db/migrations/committed/000008.sql new file mode 100644 index 000000000..32f3d50a2 --- /dev/null +++ b/@app/db/migrations/committed/000008.sql @@ -0,0 +1,133 @@ +--! Previous: sha1:afc6149bc215d6e6cf1bcabba9005f9b07e231e0 +--! Hash: sha1:587c7c362b23a8020f9802cae49b6487968c3e39 + +--! split: 2-block-registration-update-after-close.sql +/* + * A registration is editable through its update token only while event signup + * is open, matching `delete_registration`. Admins edit registrations through + * the same function (after fetching the token with + * `admin_update_registration`), so they are exempt and can correct + * registrations after signup has closed. + */ + +create or replace function app_public.update_registration( + "updateToken" text, + "firstName" text, + "lastName" text, + answers jsonb default null +) +returns app_public.registrations as $$ +declare + v_registration_secret app_private.registration_secrets; + v_registration app_public.registrations; + v_event app_public.events; + v_required_question_ids uuid[]; +begin + select * into v_registration_secret + from app_private.registration_secrets + where update_token = "updateToken"; + + if v_registration_secret is null then + raise exception 'Registration matching token was not found.' using errcode = 'NTFND'; + end if; + + select * into v_event from app_public.events where id = v_registration_secret.event_id; + + if not app_public.current_user_is_admin() + and ((v_event is null) or not (select app_public.events_signup_open(v_event))) then + raise exception 'Updating a registration after event signup has closed is not allowed. Please contact the event organizers.' using errcode = 'DNIED'; + end if; + + -- If the registration doesn't provide answers to all of the required questions it is invalid. + -- This is double validated in the _200_registration_is_valid trigger. + v_required_question_ids := array(select id from app_public.event_questions where event_id = v_registration_secret.event_id and is_required = True); + perform app_public.validate_registration_answers(v_registration_secret.event_id, v_required_question_ids, answers); + + update app_public.registrations + set first_name = "firstName", last_name = "lastName", answers = update_registration.answers + where id = v_registration_secret.registration_id + returning + * into v_registration; + + return v_registration; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; + +--! split: 3-allow-spaces-in-names.sql +/* + * `constrained_name` used to reject any whitespace, which made multi-part + * first and last names (e.g. "Anna Maria" or "von Wright") impossible to + * register with. The intent was only to stop registrations whose name is + * nothing but spaces, so require at least one non-whitespace character + * instead. Null is still allowed because claimRegistrationToken creates a + * registration before the names are known. + * + * The old check accepted an empty string, so stored names may be '' (or, for + * any value that bypassed it, only whitespace), which the new check rejects. + * `registrations.first_name` and `last_name` are the only columns of this + * type. Both are nullable, and null already means "no name given" (see + * claimRegistrationToken above, and registrations_full_name, which gives null + * then), so blank names become null before the check is added. The update + * runs with the table's user triggers disabled: it only normalises how a + * missing name is stored, so it must not queue confirmation emails + * (_500_send_registration_email) or overwrite updated_at and updated_by. + */ + +do $$ +begin + if exists ( + select 1 from app_public.registrations + where first_name !~ '\S' or last_name !~ '\S' + ) then + alter table app_public.registrations disable trigger user; + + update app_public.registrations + set + first_name = case when first_name ~ '\S' then first_name end, + last_name = case when last_name ~ '\S' then last_name end + where first_name !~ '\S' or last_name !~ '\S'; + + alter table app_public.registrations enable trigger user; + end if; +end +$$; + +alter domain app_public.constrained_name + drop constraint if exists constrained_name_check; + +alter domain app_public.constrained_name + add constraint constrained_name_check check (value ~ '\S'); + +comment on domain app_public.constrained_name is + E'A name field which must not be empty or contain only whitespace'; + +--! split: 4-user-first-and-last-name.sql +/* + * Users only had a single `name`, so the registration form had to guess where + * the first name ends ("Anna Maria von Wright"). Keycloak already knows the + * split (the standard `given_name` and `family_name` claims), so keep it on + * the user and prefill registrations from it. The columns are written by the + * Keycloak login callback on every login (the member registry is the source + * of truth), which is why users get no update grant on them. They stay null + * for accounts that have never logged in through Keycloak. + */ + +alter table app_public.users add column if not exists first_name text; +alter table app_public.users add column if not exists last_name text; + +comment on column app_public.users.first_name is + E'The user''s first name(s), from the Keycloak `given_name` claim. Null for users that have not logged in with Keycloak.'; +comment on column app_public.users.last_name is + E'The user''s last name, from the Keycloak `family_name` claim. Null for users that have not logged in with Keycloak.'; + +/* + * The registration form prefers these names over splitting the display name + * only while `keycloak_names` is on. The login callback stores them whatever + * the flag's state. + */ +insert into app_public.feature_flags (key, description) + values ( + 'keycloak_names', + 'Prefill the registration form with the first and last name from Keycloak instead of splitting the display name.' + ) + on conflict (key) do nothing; diff --git a/@app/db/migrations/committed/000009.sql b/@app/db/migrations/committed/000009.sql new file mode 100644 index 000000000..5646720cd --- /dev/null +++ b/@app/db/migrations/committed/000009.sql @@ -0,0 +1,208 @@ +--! Previous: sha1:587c7c362b23a8020f9802cae49b6487968c3e39 +--! Hash: sha1:e6e9f29d163b6c919d2114541679abba74355693 + +--! split: 2-registration-positions-table.sql +/* + * Registration statuses and positions are kept in a table that is maintained + * per event. Every change to an event's registrations, quota sizes or open + * quota size recomputes the positions of that event only, inside the same + * transaction, so readers always see current positions and a change to one + * event never touches the rows of another. + */ + +drop trigger if exists _700_refresh_mat_view on app_public.registrations; +drop trigger if exists _300_refresh_mat_view on app_public.events; +drop trigger if exists _300_refresh_mat_view on app_public.quotas; +drop function if exists app_private.tg__refresh_materialized_view(); +drop trigger if exists _800_process_registration_queue on app_public.registrations; +drop function if exists app_private.tg__process_queue(); + +drop trigger if exists _700_refresh_registration_positions on app_public.registrations; +drop trigger if exists _701_refresh_registration_positions on app_public.registrations; +drop trigger if exists _300_refresh_registration_positions on app_public.events; +drop trigger if exists _301_refresh_registration_positions on app_public.events; +drop trigger if exists _300_refresh_registration_positions on app_public.quotas; +drop trigger if exists _301_refresh_registration_positions on app_public.quotas; +drop function if exists app_private.tg__refresh_registration_positions(); +drop function if exists app_private.refresh_registration_positions(uuid); + +do $$ +begin + if exists ( + select 1 from pg_matviews + where schemaname = 'app_hidden' and matviewname = 'registrations_status_and_position' + ) then + drop materialized view app_hidden.registrations_status_and_position; + end if; +end +$$; +drop table if exists app_hidden.registrations_status_and_position; + +create table app_hidden.registrations_status_and_position ( + id uuid primary key, + event_id uuid, + quota_id uuid, + status app_public.registration_status, + position integer +); +create index on app_hidden.registrations_status_and_position(event_id); +create index on app_hidden.registrations_status_and_position(quota_id); +alter table app_hidden.registrations_status_and_position enable row level security; + +create policy select_all on app_hidden.registrations_status_and_position + for select using (true); +grant select on app_hidden.registrations_status_and_position to :DATABASE_VISITOR; + +comment on table app_hidden.registrations_status_and_position is + E'Rank and position of registrations, maintained per event by app_private.refresh_registration_positions.'; + +/* + * Recomputes the statuses and positions of one event's registrations and + * emails every finished registration that leaves the queue. + * + * The advisory lock serializes recomputes of the same event until the end of + * the transaction. In READ COMMITTED each following statement takes a fresh + * snapshot, so a recompute that waited for the lock sees every registration + * committed by the transaction that held it, and compares against the + * statuses that transaction left behind. + */ +create function app_private.refresh_registration_positions(p_event_id uuid) +returns void as $$ +declare + v_queued uuid[]; +begin + perform pg_advisory_xact_lock(hashtext('registration_positions:' || p_event_id::text)); + + select coalesce(array_agg(id), '{}') + into v_queued + from app_hidden.registrations_status_and_position + where event_id = p_event_id and status = 'IN_QUEUE'::app_public.registration_status; + + delete from app_hidden.registrations_status_and_position + where event_id = p_event_id; + + insert into app_hidden.registrations_status_and_position(id, event_id, quota_id, status, position) + with cte1 as ( + select + r.id, + size, + r.event_id, + r.quota_id, + e.open_quota_size, + r.created_at, + row_number() over (partition by r.quota_id order by r.created_at asc) as tmp_pos_quota + from app_public.registrations r + left join app_public.quotas q + on r.quota_id = q.id + left join app_public.events e + on r.event_id = e.id + where r.event_id = p_event_id + ), cte2 as ( + select + tmp.*, + row_number() over (partition by event_id, tmp_status order by created_at asc) as tmp_pos_status + from ( + select + *, + case + when tmp_pos_quota <= size then 'IN_QUOTA'::text + else 'OPEN_OR_QUEUE'::text + end as tmp_status + from cte1 + ) as tmp + ), cte3 as ( + select + *, + case + when tmp_status = 'OPEN_OR_QUEUE'::text and tmp_pos_status <= open_quota_size then 'IN_OPEN_QUOTA'::app_public.registration_status + when tmp_status = 'OPEN_OR_QUEUE'::text then 'IN_QUEUE'::app_public.registration_status + else 'IN_QUOTA'::app_public.registration_status + end as status + from cte2 + ) select + id, + event_id, + quota_id, + status, + case + -- row_number() returns bigint but we cast it to integer to avoid + -- introducing another type to our GraphQL API. Besides, we are not + -- expecting to have that many registrations in the system. + when status = 'IN_QUOTA'::app_public.registration_status then cast(row_number() over (partition by quota_id, status order by created_at asc) as integer) + else cast(row_number() over (partition by event_id, status order by created_at asc) as integer) + end as position + from cte3; + + perform graphile_worker.add_job( + 'registration__process_queue', + json_build_object('receivedSpot', received_spot) + ) + from app_hidden.registrations_status_and_position received_spot + join app_public.registrations r on r.id = received_spot.id + where + received_spot.event_id = p_event_id and + received_spot.id = any(v_queued) and + received_spot.status <> 'IN_QUEUE'::app_public.registration_status and + r.is_finished; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; +revoke all on function app_private.refresh_registration_positions(uuid) from public; +comment on function app_private.refresh_registration_positions(uuid) is + E'Recomputes app_hidden.registrations_status_and_position for the registrations of one event.'; + +/* + * Recomputes positions for the event(s) a row of app_public.[registrations, + * quotas,events] belongs to before and after the change. + */ +create function app_private.tg__refresh_registration_positions() + returns trigger as $$ +begin + if TG_TABLE_NAME = 'events' then + perform app_private.refresh_registration_positions(coalesce(NEW.id, OLD.id)); + return null; + end if; + + if TG_OP in ('UPDATE', 'DELETE') then + perform app_private.refresh_registration_positions(OLD.event_id); + end if; + if TG_OP = 'INSERT' or (TG_OP = 'UPDATE' and NEW.event_id is distinct from OLD.event_id) then + perform app_private.refresh_registration_positions(NEW.event_id); + end if; + return null; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; +revoke all on function app_private.tg__refresh_registration_positions() from public; + +-- Updates recompute only when a rank input changes. +create trigger _700_refresh_registration_positions + after insert or delete on app_public.registrations for each row + execute procedure app_private.tg__refresh_registration_positions(); +create trigger _701_refresh_registration_positions + after update on app_public.registrations for each row + when ( + OLD.created_at is distinct from NEW.created_at or + OLD.quota_id is distinct from NEW.quota_id or + OLD.event_id is distinct from NEW.event_id + ) + execute procedure app_private.tg__refresh_registration_positions(); + +create trigger _300_refresh_registration_positions + after insert or delete on app_public.quotas for each row + execute procedure app_private.tg__refresh_registration_positions(); +create trigger _301_refresh_registration_positions + after update on app_public.quotas for each row + when ( + OLD.size is distinct from NEW.size or + OLD.event_id is distinct from NEW.event_id + ) + execute procedure app_private.tg__refresh_registration_positions(); + +create trigger _300_refresh_registration_positions + after insert or delete on app_public.events for each row + execute procedure app_private.tg__refresh_registration_positions(); +create trigger _301_refresh_registration_positions + after update on app_public.events for each row + when (OLD.open_quota_size is distinct from NEW.open_quota_size) + execute procedure app_private.tg__refresh_registration_positions(); + +select app_private.refresh_registration_positions(id) from app_public.events; diff --git a/@app/db/migrations/committed/000010-add-ribbon-text-to-events.sql b/@app/db/migrations/committed/000010-add-ribbon-text-to-events.sql new file mode 100644 index 000000000..28abcac57 --- /dev/null +++ b/@app/db/migrations/committed/000010-add-ribbon-text-to-events.sql @@ -0,0 +1,144 @@ +--! Previous: sha1:e6e9f29d163b6c919d2114541679abba74355693 +--! Hash: sha1:db141b611cd614d76926a295bf8e0432d3b99aba +--! Message: add ribbon text to events + +--! split: 30-event-ribbon-text.sql +/* + * Highlighted events carry a ribbon on the event card. Its text used to be a + * fixed translation ("Nätti tapahtuma!"); `highlight_text` lets the event + * creator write their own, per language. A null value, or a missing language, + * falls back to the default translation in the client. + * + * The client shows the text input and the custom ribbon only while the + * `ribbon_text` flag is enabled. The database does not gate it: a stored text + * is kept while the flag is off. + */ + +insert into app_public.feature_flags (key, description) + values ('ribbon_text', E'Custom ribbon text for highlighted events.') + on conflict (key) do nothing; + +alter table app_public.events add column if not exists highlight_text translated_field; + +comment on column app_public.events.highlight_text is + E'Text shown on the ribbon of a highlighted event.'; + +grant + insert (highlight_text), + update (highlight_text) +on app_public.events to :DATABASE_VISITOR; + +alter type app_public.event_input drop attribute if exists highlight_text; +alter type app_public.event_input add attribute highlight_text translated_field; + +create or replace function app_public.create_event( + event app_public.event_input, + quotas app_public.create_event_quotas[], + questions app_public.create_event_questions[] default null +) +returns app_public.events as $$ +#variable_conflict use_variable +declare + v_event app_public.events; +begin + -- Check permissions + call app_public.check_is_admin(); + + -- Create the event + insert into app_public.events( + slug, + name, + description, + location, + event_start_time, + event_end_time, + registration_start_time, + registration_end_time, + is_highlighted, + highlight_text, + is_draft, + header_image_file, + open_quota_size, + owner_organization_id, + category_id + ) + values ( + event.slug, + event.name, + event.description, + event.location, + event.event_start_time, + event.event_end_time, + event.registration_start_time, + event.registration_end_time, + event.is_highlighted, + event.highlight_text, + event.is_draft, + event.header_image_file, + event.open_quota_size, + event.owner_organization_id, + event.category_id + ) + returning * into v_event; + + -- Create quotas and questions + perform * from app_public.create_event_quotas(v_event.id, quotas); + perform * from app_public.create_event_questions(v_event.id, questions); + + return v_event; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +/* + * `highlight_text` is not coalesced like the other fields: a null must be able + * to clear a previously written text. It is instead updated together with + * `is_highlighted`, so partial updates that leave both out keep the old text. + */ +create or replace function app_public.update_event( + id uuid, + event app_public.event_input, + quotas app_public.update_event_quotas[], + questions app_public.update_event_questions[] default null +) +returns app_public.events as $$ +#variable_conflict use_column +declare + v_event app_public.events; +begin + -- Check permissions + call app_public.check_is_admin(); + + -- Create the event + update app_public.events + set + slug = coalesce(event.slug, slug), + name = coalesce(event.name, name), + description = coalesce(event.description, description), + location = coalesce(event.location, location), + event_start_time = coalesce(event.event_start_time, event_start_time), + event_end_time = coalesce(event.event_end_time, event_end_time), + registration_start_time = coalesce(event.registration_start_time, registration_start_time), + registration_end_time = coalesce(event.registration_end_time, registration_end_time), + is_highlighted = coalesce(event.is_highlighted, is_highlighted), + highlight_text = case + when event.is_highlighted is null then highlight_text + else event.highlight_text + end, + is_draft = coalesce(event.is_draft, is_draft), + header_image_file = coalesce(event.header_image_file, header_image_file), + open_quota_size = coalesce(event.open_quota_size, open_quota_size), + owner_organization_id = coalesce(event.owner_organization_id, owner_organization_id), + category_id = coalesce(event.category_id, category_id) + where id = update_event.id + returning * into v_event; + + -- Update quotas and questions + perform * from app_public.update_event_quotas(id, quotas); + perform * from app_public.update_event_questions(id, questions); + + return v_event; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +comment on function app_public.update_event(id uuid, event app_public.event_input, quotas app_public.update_event_quotas[], questions app_public.update_event_questions[]) is + E'Updates an event as well as any related quotas and questions with one mutation. An omitted event attribute keeps its value, except `highlightText`, which is replaced (null clears it) whenever `isHighlighted` is given.'; diff --git a/@app/db/migrations/committed/000011-add-flags-for-client-only-features.sql b/@app/db/migrations/committed/000011-add-flags-for-client-only-features.sql new file mode 100644 index 000000000..fd4c83f35 --- /dev/null +++ b/@app/db/migrations/committed/000011-add-flags-for-client-only-features.sql @@ -0,0 +1,18 @@ +--! Previous: sha1:db141b611cd614d76926a295bf8e0432d3b99aba +--! Hash: sha1:5be9acbd207f7b3514e90e1ecd7b6db2951c5dd9 +--! Message: add flags for client-only features + +--! split: 40-client-feature-flags.sql +/* + * Flags of features that only the client gates: the typed time boxes, event + * templates and the registration form preview in the event form, and the + * confetti after creating an event or a registration. They have no other + * database objects. + */ +insert into app_public.feature_flags (key, description) + values + ('typed_time_input', E'Typed hour, minute and second boxes for the event and registration times in the event form, and default times when a day is clicked.'), + ('event_templates', E'Event templates in the event form: template selectors and ready-made quotas and questions.'), + ('form_preview', E'Registration form preview tab in the event form.'), + ('confetti', E'Confetti after an event or a registration has been created.') + on conflict (key) do nothing; diff --git a/@app/db/migrations/committed/000012-add-calendar-invites.sql b/@app/db/migrations/committed/000012-add-calendar-invites.sql new file mode 100644 index 000000000..9e840988f --- /dev/null +++ b/@app/db/migrations/committed/000012-add-calendar-invites.sql @@ -0,0 +1,14 @@ +--! Previous: sha1:5be9acbd207f7b3514e90e1ecd7b6db2951c5dd9 +--! Hash: sha1:51c8483bf2ba1cedaf50a8530c75ba90e66d6a06 +--! Message: add calendar invites + +--! split: 50-calendar-invites.sql +/* + * Calendar invitations: registration emails carry an iCalendar invitation + * and the event page offers calendar links after signing up. Stores no data; + * the worker contributor and the client check the `calendar_invites` flag. + */ + +insert into app_public.feature_flags (key, description) + values ('calendar_invites', E'Calendar invitation in registration emails and calendar links after signing up.') + on conflict (key) do nothing; diff --git a/@app/db/migrations/committed/000013-add-registration-reminders.sql b/@app/db/migrations/committed/000013-add-registration-reminders.sql new file mode 100644 index 000000000..25a9bc012 --- /dev/null +++ b/@app/db/migrations/committed/000013-add-registration-reminders.sql @@ -0,0 +1,274 @@ +--! Previous: sha1:51c8483bf2ba1cedaf50a8530c75ba90e66d6a06 +--! Hash: sha1:e75a7381038ac7c4847cf9b0c0d13f3d4b3847f5 +--! Message: add registration reminders + +--! split: 51-registration-reminders.sql +/* + * Registration reminders: a signed-in user asks to be reminded a chosen time + * before an event's registration opens, by email, Telegram or both. + * + * Each reminder schedules one graphile-worker job per channel with a job key + * (`registration-reminder:` and `...:telegram`), rescheduled whenever the + * reminder or the event's opening time changes. The tasks re-validate the + * reminder when they run and record a sent marker per channel. + * + * `reminder_preferences` holds the defaults a user saves once; saving them + * also updates the user's upcoming unsent reminders. + * + * The Telegram tables and functions used here are in + * 52-telegram-reminders.sql. + * + * Gated by the `registration_reminders` flag: enabling a reminder and saving + * preferences raise FTOFF while it is off, and the worker tasks do nothing. + * Cancelling a reminder stays possible. Choosing the Telegram channel also + * needs `telegram_reminders`. + */ + +insert into app_public.feature_flags (key, description) + values ('registration_reminders', E'Reminders before registration opens: the reminder button, reminder settings and reminder emails.') + on conflict (key) do nothing; + +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) +); +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(); + +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 not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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 app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; + +/* + * Reminder preferences. 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\nDelivery and timing preferences for upcoming registration reminders.'; +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 not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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 app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; + +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; + if not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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; diff --git a/@app/db/migrations/committed/000014-add-telegram-reminders.sql b/@app/db/migrations/committed/000014-add-telegram-reminders.sql new file mode 100644 index 000000000..af8e31756 --- /dev/null +++ b/@app/db/migrations/committed/000014-add-telegram-reminders.sql @@ -0,0 +1,140 @@ +--! Previous: sha1:e75a7381038ac7c4847cf9b0c0d13f3d4b3847f5 +--! Hash: sha1:86191a97641e77baa1b163178f5f23cfcad7ed04 +--! Message: add Telegram reminders + +--! split: 52-telegram-reminders.sql +/* + * Telegram reminders: a user links a Telegram chat to their account through + * the bot, and registration reminders (51-registration-reminders.sql) can + * then be delivered there. + * + * Linking: `request_telegram_link()` returns a one-time code (stored hashed, + * valid 15 minutes) that the user sends to the bot with /start; the server's + * bot update processing consumes it with `app_private.connect_telegram`. + * Chat identifiers are only exposed to the server, never in GraphQL. + * + * Gated by the `telegram_reminders` flag (which the server marks unavailable + * without TELEGRAM_BOT_TOKEN): requesting a link code raises FTOFF while it is + * off, the bot webhook answers 404, polling pauses and the Telegram worker + * tasks do nothing. Disconnecting stays possible. + */ + +insert into app_public.feature_flags (key, description) + values ('telegram_reminders', E'Registration reminders through the Telegram bot, and linking a Telegram account.') + on conflict (key) do nothing; + +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; + if not app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; + +-- Unlinking cancels Telegram-only reminders and keeps 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; + +-- Bot preferences belong to a private Telegram chat, including before linking. +-- Keep 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/000015-add-mcp-sessions.sql b/@app/db/migrations/committed/000015-add-mcp-sessions.sql new file mode 100644 index 000000000..240cd53de --- /dev/null +++ b/@app/db/migrations/committed/000015-add-mcp-sessions.sql @@ -0,0 +1,51 @@ +--! Previous: sha1:86191a97641e77baa1b163178f5f23cfcad7ed04 +--! Hash: sha1:a82534fccfc43de4a5611c2911fbf0d72b9b9c05 +--! Message: add MCP sessions + +--! split: 60-mcp-sessions.sql +/* + * MCP server: the `mcp_server` flag, and Keycloak-token sessions. + * + * The flag gates every MCP route (they answer 404 while it is off). The + * server marks it unavailable at boot unless KEYCLOAK_ISSUER is set. + */ + +insert into app_public.feature_flags (key, description) + values ('mcp_server', E'MCP server at /mcp for AI assistants: browse events, register, and let admins create draft events.') + on conflict (key) do nothing; + +/* + * MCP requests authenticate with a Keycloak access token instead of a session + * cookie. The server turns each verified token into an ordinary + * app_private.sessions row so that current_user_id(), RLS and the ownership + * triggers work unchanged, and so that the database keeps identifying users by + * an unguessable session id rather than by a raw user id (see the comment on + * current_user_id). + * + * One MCP session exists per Keycloak session (`oauth_sid`, the token's `sid` + * claim): token refreshes reuse it. The rows are derived state — the server + * recreates one on the next request if it is gone — so inactive MCP sessions + * can be deleted aggressively by the sessions__delete_inactive_mcp_sessions + * task. + */ + +alter table app_private.sessions + add column if not exists kind text not null default 'web', + add column if not exists oauth_sid text; + +alter table app_private.sessions drop constraint if exists sessions_kind_check; +alter table app_private.sessions + add constraint sessions_kind_check check (kind in ('web', 'mcp')); + +alter table app_private.sessions drop constraint if exists sessions_oauth_sid_check; +alter table app_private.sessions + add constraint sessions_oauth_sid_check check ((kind = 'mcp') = (oauth_sid is not null)); + +drop index if exists app_private.sessions_mcp_oauth_sid_key; +create unique index sessions_mcp_oauth_sid_key + on app_private.sessions (oauth_sid) where kind = 'mcp'; + +comment on column app_private.sessions.kind is + E'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; +comment on column app_private.sessions.oauth_sid is + E'Keycloak session id (the access token sid claim) of an mcp session.'; diff --git a/@app/db/migrations/committed/000016-add-stripe-payments.sql b/@app/db/migrations/committed/000016-add-stripe-payments.sql new file mode 100644 index 000000000..78aa7fab3 --- /dev/null +++ b/@app/db/migrations/committed/000016-add-stripe-payments.sql @@ -0,0 +1,638 @@ +--! Previous: sha1:a82534fccfc43de4a5611c2911fbf0d72b9b9c05 +--! Hash: sha1:ee27fe2667031e53f857909f275a6687335676cd +--! Message: add Stripe payments + +--! split: 70-payments.sql +/* + * Stripe payments: schema and database functions. + * + * Everything here is additive: new types, new tables and new columns with + * defaults. An event is paid when one of its quotas has a price above 0; a + * quota price of 0 (the default) behaves exactly as before. + * + * Two rules shape everything below: + * - A registrant pays only after the event's registration has closed (the + * server enforces this when Checkout starts; the worker emails the payment + * link at the close). + * - Ilmo never refunds. Deleting a registration, a quota or an event leaves + * its payments in place (detached, see app_public.payments); organizers + * refund by hand in Stripe. + * + * Gated by the `payments` feature flag. While it is off, nobody can start a + * payment: create_event_quotas and update_event_quotas refuse a non-zero + * price, the organizer payment actions refuse to run (errcode FTOFF), and the + * server and worker refuse Checkout and payment emails. Payments already in + * flight still settle: the computed payment status is never gated. The flag + * reads as off unless the server has both Stripe secrets (`available`). + * + * Money is always integer cents. + * + * This file is idempotent: the first block removes everything it creates so + * that `graphile-migrate watch` can re-run it. + */ + +insert into app_public.feature_flags (key, description) + values ('payments', E'Stripe payments for paid quotas: prices, the pay page, Checkout, organizer payment tools and payment emails.') + on conflict (key) do nothing; + +/******************************************************************************/ +-- Teardown (idempotency) + +drop function if exists app_public.admin_send_payment_reminders(uuid); +drop function if exists app_public.admin_unmark_registration_paid(uuid); +drop function if exists app_public.admin_mark_registration_paid(uuid); +drop function if exists app_public.events_payment_summary(app_public.events); +drop function if exists app_public.registrations_payment_status(app_public.registrations); +drop function if exists app_private.registration_payment_status(app_public.registrations); +drop function if exists app_private.current_user_can_manage_event_payments(uuid); +drop trigger if exists _250_reset_unpaid_close_email on app_public.events; +drop function if exists app_private.tg_events__reset_unpaid_close_email(); + +drop table if exists app_private.stripe_events; +drop table if exists app_public.payments; + +alter table app_public.events drop column if exists unpaid_close_email_sent_at; +alter table app_public.events drop column if exists last_payment_reminder_sent_at; +alter table app_public.quotas drop column if exists price_cents; + +alter type app_public.create_event_quotas drop attribute if exists price_cents; +alter type app_public.update_event_quotas drop attribute if exists price_cents; + +drop type if exists app_public.event_payment_summary; +drop type if exists app_public.registration_payment_status; +drop type if exists app_public.payment_status; +drop type if exists app_public.payment_method; + +/******************************************************************************/ +-- Types + +create type app_public.payment_method as enum ( + 'STRIPE', + 'MANUAL' +); +comment on type app_public.payment_method is + E'How a payment was made: by card through Stripe Checkout, or marked paid by an organizer (cash, bank transfer).'; + +create type app_public.payment_status as enum ( + 'PENDING', + 'PAID', + 'EXPIRED' +); +comment on type app_public.payment_status is + E'State of a single payment attempt.'; + +create type app_public.registration_payment_status as enum ( + 'NOT_REQUIRED', + 'UNPAID', + 'PAID', + 'PAID_MANUALLY' +); +comment on type app_public.registration_payment_status is + E'Payment state of a registration as shown to organizers.'; + +create type app_public.event_payment_summary as ( + paid_count integer, + unpaid_count integer, + due_count integer, + tickets_paid_cents integer, + guild_receives_cents integer, + unlinked_card_payment_count integer +); +comment on type app_public.event_payment_summary is + E'Payment totals for an event, for organizers.'; + +alter type app_public.create_event_quotas + add attribute price_cents integer; +alter type app_public.update_event_quotas + add attribute price_cents integer; + +/******************************************************************************/ +-- Columns + +alter table app_public.events + add column unpaid_close_email_sent_at timestamptz, + add column last_payment_reminder_sent_at timestamptz; + +comment on column app_public.events.unpaid_close_email_sent_at is + E'When the close-of-registration payment email was sent. Set by the worker; cleared when registration_end_time moves later, so that the email goes out again at the new close.'; +comment on column app_public.events.last_payment_reminder_sent_at is + E'When an organizer last sent payment reminders to all unpaid participants.'; + +alter table app_public.quotas + add column price_cents integer not null default 0 + constraint quotas_price_cents_check check (price_cents = 0 or price_cents between 25 and 1000000); + +comment on column app_public.quotas.price_cents is + E'Ticket price in cents. 0 means the quota is free; a paid price is at least 25 cents so that the total charge with the service fee reaches Stripe''s minimum, and at most 1 000 000 cents (10 000 €). Registrants pay the price in effect when they pay.'; + +grant + insert(price_cents), + update(price_cents) +on app_public.quotas to :DATABASE_VISITOR; + +/* + * Reopening or extending registration after the close email went out: the + * email is sent again at the new close, so that registrations made in the + * meantime get their payment link. Registrants who already paid get nothing + * (the email goes to unpaid registrations only). + */ +create function app_private.tg_events__reset_unpaid_close_email() returns trigger as $$ +begin + NEW.unpaid_close_email_sent_at := null; + return NEW; +end; +$$ language plpgsql volatile set search_path to pg_catalog, public, pg_temp; +comment on function app_private.tg_events__reset_unpaid_close_email() is + E'Clears events.unpaid_close_email_sent_at when registration_end_time moves later.'; + +create trigger _250_reset_unpaid_close_email + before update of registration_end_time on app_public.events + for each row + when (NEW.registration_end_time > OLD.registration_end_time) + execute procedure app_private.tg_events__reset_unpaid_close_email(); + +/******************************************************************************/ +-- Payments + +create table app_public.payments ( + id uuid primary key default gen_random_uuid(), + registration_id uuid references app_public.registrations(id) on delete set null, + event_id uuid references app_public.events(id) on delete set null, + quota_id uuid references app_public.quotas(id) on delete set null, + event_name jsonb not null, + quota_title jsonb not null, + method app_public.payment_method not null, + status app_public.payment_status not null default 'PENDING', + ticket_amount_cents integer not null check (ticket_amount_cents >= 0), + service_fee_cents integer not null default 0 check (service_fee_cents >= 0), + currency text not null default 'eur', + stripe_checkout_session_id text unique, + stripe_payment_intent_id text, + paid_at timestamptz, + created_by uuid references app_public.users(id) on delete set null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +comment on table app_public.payments is + E'@omit create,update,delete\nPayments for registrations. Rows outlive their registration (and event and quota) so they can be reconciled with Stripe payouts; they hold no personal data. Ilmo never refunds: a card payment without a registration is refunded by hand in Stripe, if at all.'; +comment on column app_public.payments.registration_id is + E'The registration paid for. Null once the registration has been deleted, and for a card payment that could not be applied to it (a second payment, or an amount that did not match).'; +comment on column app_public.payments.event_id is + E'The event paid for. Null once the event has been deleted.'; +comment on column app_public.payments.quota_id is + E'The quota paid for. Null once the quota has been deleted.'; +comment on column app_public.payments.event_name is + E'Snapshot of the event name when the payment was created.'; +comment on column app_public.payments.quota_title is + E'Snapshot of the quota title when the payment was created.'; +comment on column app_public.payments.ticket_amount_cents is + E'Ticket price paid, in cents: the quota price when the payment was started.'; +comment on column app_public.payments.service_fee_cents is + E'Service fee paid on top of the ticket, in cents. 0 for manual payments.'; +comment on column app_public.payments.created_by is + E'The organizer who recorded a manual payment.'; + +create index payments_registration_id_idx on app_public.payments(registration_id); +create index payments_event_id_idx on app_public.payments(event_id); +create index payments_quota_id_idx on app_public.payments(quota_id); +create index payments_created_by_idx on app_public.payments(created_by); +create index payments_stripe_payment_intent_id_idx on app_public.payments(stripe_payment_intent_id); + +-- A registration can be paid only once. A second card payment is kept as a +-- separate PAID row detached from the registration. +create unique index payments_one_paid_per_registration_idx + on app_public.payments(registration_id) + where status = 'PAID' and registration_id is not null; + +create trigger _100_timestamps + before insert or update on app_public.payments + for each row + execute procedure app_private.tg__timestamps(); + +/* + * Payment data is for organizers only. Organizers are admins (who manage + * every event, like everywhere else in the admin UI) and members of the + * event's owner organization. + */ +create function app_private.current_user_can_manage_event_payments(event_id uuid) +returns boolean as $$ + select app_public.current_user_is_admin() + or app_public.current_user_has_event_permissions(event_id); +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_private.current_user_can_manage_event_payments(event_id uuid) is + E'True if the current user may see and manage payments of the event: admins and members of the event''s owner organization.'; + +alter table app_public.payments enable row level security; + +-- No insert/update/delete grants: writes go through security definer +-- functions below or through the server/worker root pool. +create policy select_event_permissions on app_public.payments + for select using ( + app_public.current_user_is_admin() + or app_public.current_user_has_event_permissions(event_id) + ); + +grant select on app_public.payments to :DATABASE_VISITOR; + +/* + * Stripe webhook events that have been processed, for idempotency. + */ +create table app_private.stripe_events ( + id text primary key, + type text not null, + processed_at timestamptz not null default now() +); +alter table app_private.stripe_events enable row level security; +comment on table app_private.stripe_events is + E'Ids of Stripe webhook events already handled, so that redelivered events are ignored.'; + +/******************************************************************************/ +-- Quota functions + +create or replace function app_public.create_event_quotas( + event_id uuid, + quotas app_public.create_event_quotas[] +) +returns app_public.quotas[] as $$ +declare + v_input app_public.create_event_quotas; + v_quota app_public.quotas; + v_ret app_public.quotas[] default '{}'; +begin + -- Check permissions + call app_public.check_is_admin(); + + -- Must specify at least one quota + if (select array_length(quotas, 1)) is null then + raise exception 'You must specify at least one quota' using errcode = 'DNIED'; + end if; + + -- A price can be set only while payments are on + if not app_public.feature_enabled('payments') + and exists(select 1 from unnest(quotas) as q where coalesce(q.price_cents, 0) <> 0) + then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + -- Create quotas + foreach v_input in array quotas loop + insert into app_public.quotas(event_id, position, title, size, price_cents) + values (event_id, v_input.position, v_input.title, v_input.size, coalesce(v_input.price_cents, 0)) + returning * into v_quota; + + v_ret := array_append(v_ret, v_quota); + end loop; + + return v_ret; +end; +$$ language plpgsql volatile security invoker set search_path to pg_catalog, public, pg_temp; + +/* + * Built on committed/000005.sql (null-id fix). A null price_cents keeps an + * existing quota's price (and makes a new quota free), so callers that don't + * know about prices leave them untouched. A non-zero price_cents is refused + * while payments are off; a null or 0 is accepted. Changing a price is always + * allowed: payments already made keep their amount and stay paid. + */ +create or replace function app_public.update_event_quotas( + event_id uuid, + quotas app_public.update_event_quotas[] +) +returns app_public.quotas[] as $$ +#variable_conflict use_variable +declare + v_quota_ids_to_delete uuid[]; + v_input app_public.update_event_quotas; + v_quota app_public.quotas; + v_ret app_public.quotas[] default '{}'; +begin + -- Check permissions + call app_public.check_is_admin(); + + -- Must specify at least one quota + if (select array_length(quotas, 1)) is null then + raise exception 'You must specify at least one quota' using errcode = 'DNIED'; + end if; + + -- A price can be set only while payments are on + if not app_public.feature_enabled('payments') + and exists(select 1 from unnest(quotas) as q where coalesce(q.price_cents, 0) <> 0) + then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + select array( + select id from app_public.quotas as q + where q.event_id = event_id + and q.id not in (select id from unnest(quotas) where id is not null) + ) + into v_quota_ids_to_delete; + + -- Delete existing event quotas that were not supplied + -- as input to this function + delete from app_public.quotas as q + where q.id = any(v_quota_ids_to_delete); + + foreach v_input in array quotas loop + if exists(select 1 from app_public.quotas where id = v_input.id) then + -- Update existing event quotas by id + update app_public.quotas as q + set + position = v_input.position, + title = v_input.title, + size = v_input.size, + price_cents = coalesce(v_input.price_cents, q.price_cents) + where q.id = v_input.id + returning * into v_quota; + else + -- Create new quotas that didn't exist before + insert into app_public.quotas(event_id, position, title, size, price_cents) + values (event_id, v_input.position, v_input.title, v_input.size, coalesce(v_input.price_cents, 0)) + returning * into v_quota; + end if; + + v_ret := array_append(v_ret, v_quota); + end loop; + + return v_ret; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +/******************************************************************************/ +-- Computed columns for organizers + +/* + * The payment state of a registration, without any permission check. Used by + * the guarded computed column below and by the server (the /pay page and + * Checkout) and the worker, which look registrations up without a user. + * + * A PAID payment makes the registration paid whatever its quota costs now: + * changing a price never undoes a payment. Otherwise a finished registration + * in a quota with a price above 0 is unpaid. + */ +create function app_private.registration_payment_status(registration app_public.registrations) +returns app_public.registration_payment_status as $$ + select + case + when exists( + select 1 from app_public.payments as p + where p.registration_id = registration.id and p.status = 'PAID' and p.method = 'MANUAL' + ) + then 'PAID_MANUALLY'::app_public.registration_payment_status + when exists( + select 1 from app_public.payments as p + where p.registration_id = registration.id and p.status = 'PAID' + ) + then 'PAID'::app_public.registration_payment_status + when registration.is_finished is true and exists( + select 1 from app_public.quotas as q + where q.id = registration.quota_id and q.price_cents > 0 + ) + then 'UNPAID'::app_public.registration_payment_status + else 'NOT_REQUIRED'::app_public.registration_payment_status + end; +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_private.registration_payment_status(registration app_public.registrations) is + E'Payment status of the registration, without a permission check.'; + +create function app_public.registrations_payment_status(registration app_public.registrations) +returns app_public.registration_payment_status as $$ + select + case + when not app_private.current_user_can_manage_event_payments(registration.event_id) + then null + else app_private.registration_payment_status(registration) + end; +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_public.registrations_payment_status(registration app_public.registrations) is + E'@sortable\n@filterable\nPayment status of the registration. Null unless the current user may manage the event''s payments, because registrations are publicly readable.'; + +create function app_public.events_payment_summary(e app_public.events) +returns app_public.event_payment_summary as $$ + with in_spot as ( + select + r.id, + app_public.registrations_payment_status(r) as payment_status + from app_public.registrations as r + join app_hidden.registrations_status_and_position as s on s.id = r.id + where + r.event_id = e.id + and r.is_finished is true + and s.status in ('IN_QUOTA', 'IN_OPEN_QUOTA') + ), + paid as ( + select p.method, p.ticket_amount_cents, p.registration_id + from app_public.payments as p + where p.event_id = e.id and p.status = 'PAID' + ) + select + case when not app_private.current_user_can_manage_event_payments(e.id) then null else + row( + (select count(*) from in_spot where payment_status in ('PAID', 'PAID_MANUALLY'))::integer, + (select count(*) from in_spot where payment_status = 'UNPAID')::integer, + (select count(*) from in_spot where payment_status in ('PAID', 'PAID_MANUALLY', 'UNPAID'))::integer, + (select coalesce(sum(ticket_amount_cents), 0) from paid)::integer, + -- Same formula as guildReceivesCents in @app/lib: Stripe keeps the + -- service fee and 1,5 % of the total, rounded to the cent (halves up). + -- Manual payments reach the guild in full. + (select coalesce(sum( + case + when method = 'MANUAL' or ticket_amount_cents = 0 then ticket_amount_cents + -- In numeric, so large amounts can't overflow integer maths + else floor((1000 * ticket_amount_cents::numeric - 15 * (ticket_amount_cents::numeric + 25)) / 1000 + 0.5) + end + ), 0) from paid)::integer, + (select count(*) from paid where method = 'STRIPE' and registration_id is null)::integer + )::app_public.event_payment_summary + end; +$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_public.events_payment_summary(e app_public.events) is + E'Payment totals for organizers: counts of registrations holding a spot (in quota or open quota) that are paid, unpaid and due, the ticket amount paid, the estimated amount the guild receives and the number of card payments not linked to a registration (deleted registrations, second payments), which organizers may refund by hand in Stripe. Null unless the current user may manage the event''s payments.'; + +/******************************************************************************/ +-- Organizer actions + +create function app_public.admin_mark_registration_paid(registration_id uuid) +returns app_public.payments as $$ +declare + v_registration app_public.registrations; + v_event app_public.events; + v_quota app_public.quotas; + v_payment app_public.payments; +begin + select * into v_registration + from app_public.registrations as r + where r.id = admin_mark_registration_paid.registration_id; + + if v_registration.id is null then + raise exception 'Registration was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(v_registration.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + select * into v_event from app_public.events where id = v_registration.event_id; + select * into v_quota from app_public.quotas where id = v_registration.quota_id; + + if v_registration.is_finished is not true or v_quota.price_cents = 0 then + raise exception 'This registration does not require payment.' using errcode = 'DNIED'; + end if; + + if exists( + select 1 from app_public.payments as p + where p.registration_id = v_registration.id and p.status = 'PAID' + ) then + raise exception 'This registration has already been paid.' using errcode = 'DNIED'; + end if; + + -- Queued registrations pay once they get a spot, like on the /pay page + if exists( + select 1 from app_hidden.registrations_status_and_position as s + where s.id = v_registration.id and s.status = 'IN_QUEUE' + ) then + raise exception 'This registration is in the queue.' using errcode = 'DNIED'; + end if; + + insert into app_public.payments ( + registration_id, + event_id, + quota_id, + event_name, + quota_title, + method, + status, + ticket_amount_cents, + service_fee_cents, + paid_at, + created_by + ) + values ( + v_registration.id, + v_registration.event_id, + v_registration.quota_id, + v_event.name, + v_quota.title, + 'MANUAL', + 'PAID', + v_quota.price_cents, + 0, + now(), + app_public.current_user_id() + ) + returning * into v_payment; + + perform graphile_worker.add_job( + 'payment__send_received_email', + json_build_object('paymentId', v_payment.id) + ); + + return v_payment; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_public.admin_mark_registration_paid(registration_id uuid) is + E'Records a manual payment (cash, bank transfer) of the current quota price for a registration and emails the participant a payment confirmation.'; + +create function app_public.admin_unmark_registration_paid(registration_id uuid) +returns boolean as $$ +declare + v_registration app_public.registrations; + v_deleted_count integer; +begin + select * into v_registration + from app_public.registrations as r + where r.id = admin_unmark_registration_paid.registration_id; + + if v_registration.id is null then + raise exception 'Registration was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(v_registration.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + delete from app_public.payments as p + where + p.registration_id = v_registration.id + and p.method = 'MANUAL' + and p.status = 'PAID'; + + get diagnostics v_deleted_count = row_count; + if v_deleted_count = 0 then + raise exception 'This registration has no manual payment.' using errcode = 'NTFND'; + end if; + + return true; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_public.admin_unmark_registration_paid(registration_id uuid) is + E'Removes a manual payment recorded with adminMarkRegistrationPaid. Card payments cannot be undone this way.'; + +create function app_public.admin_send_payment_reminders(event_id uuid) +returns integer as $$ +declare + v_registration_id uuid; + v_count integer := 0; + v_last_sent_at timestamptz; +begin + if not exists(select 1 from app_public.events as e where e.id = admin_send_payment_reminders.event_id) then + raise exception 'Event was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(admin_send_payment_reminders.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + -- A short cooldown, so a double click or a script can't email everyone + -- many times over. The event row lock makes concurrent calls wait here + -- and then see the first call's timestamp. + select e.last_payment_reminder_sent_at into v_last_sent_at + from app_public.events as e + where e.id = admin_send_payment_reminders.event_id + for update; + if v_last_sent_at > now() - interval '10 minutes' then + raise exception 'Payment reminders were sent less than 10 minutes ago. Try again later.' using errcode = 'DNIED'; + end if; + + for v_registration_id in + select r.id + from app_public.registrations as r + join app_hidden.registrations_status_and_position as s on s.id = r.id + where + r.event_id = admin_send_payment_reminders.event_id + and r.is_finished is true + and s.status in ('IN_QUOTA', 'IN_OPEN_QUOTA') + and app_public.registrations_payment_status(r) = 'UNPAID' + order by r.created_at, r.id + loop + perform graphile_worker.add_job( + 'payment__send_reminder', + json_build_object('registrationId', v_registration_id) + ); + v_count := v_count + 1; + end loop; + + if v_count > 0 then + update app_public.events as e + set last_payment_reminder_sent_at = now() + where e.id = admin_send_payment_reminders.event_id; + end if; + + return v_count; +end; +$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp; +comment on function app_public.admin_send_payment_reminders(event_id uuid) is + E'Emails a payment reminder to every finished, unpaid registration holding a spot in the event. Returns the number of reminders queued. Refused for 10 minutes after the last reminders were sent.'; diff --git a/@app/db/migrations/committed/000017-add-prefilled-registration-answers.sql b/@app/db/migrations/committed/000017-add-prefilled-registration-answers.sql new file mode 100644 index 000000000..a0ce3a3c8 --- /dev/null +++ b/@app/db/migrations/committed/000017-add-prefilled-registration-answers.sql @@ -0,0 +1,285 @@ +--! Previous: sha1:ee27fe2667031e53f857909f275a6687335676cd +--! Hash: sha1:9539962ddef96c2ce2693e6cfd004f2028048e1f +--! Message: add prefilled registration answers + +--! split: 80-registration-prefill.sql +/* + * Registration prefill. The registration form prefills the registrant's name + * and email from their account. Telegram handles and dietary restrictions are + * asked with ordinary event questions, so an admin marks which question asks + * which (`event_questions.prefill`), and the answer is prefilled from the + * user's registration profile. + */ + +do $$ +begin + create type app_public.question_prefill as enum ( + 'TELEGRAM', + 'DIETARY_RESTRICTIONS', + 'NONE' + ); +exception when duplicate_object then null; +end +$$; + +comment on type app_public.question_prefill is + E'Which registration profile field prefills the answer to a question. NONE is only an input value: it clears the prefill of a question in `updateEvent`, where an omitted prefill keeps the stored one.'; + +alter table app_public.event_questions + add column if not exists prefill app_public.question_prefill; + +-- The registration profile stores free text, which only fits a TEXT answer +alter table app_public.event_questions + drop constraint if exists _cnstr_prefill_text_only; +alter table app_public.event_questions + add constraint _cnstr_prefill_text_only check(prefill is null or type = 'TEXT'); + +-- 'NONE' only exists in the input types, see update_event_questions; a +-- question without a prefill stores null +alter table app_public.event_questions + drop constraint if exists _cnstr_prefill_not_none; +alter table app_public.event_questions + add constraint _cnstr_prefill_not_none check(prefill <> 'NONE'); + +comment on column app_public.event_questions.prefill is + E'Which registration profile field prefills the answer to this question, if any.'; + +grant + insert (prefill), + update (prefill) +on app_public.event_questions to :DATABASE_VISITOR; + +-- Input types for app_public.create_event_questions and +-- app_public.update_event_questions +do $$ +begin + alter type app_public.create_event_questions add attribute prefill app_public.question_prefill; +exception when duplicate_column then null; +end +$$; + +do $$ +begin + alter type app_public.update_event_questions add attribute prefill app_public.question_prefill; +exception when duplicate_column then null; +end +$$; + +create or replace function app_public.create_event_questions( + event_id uuid, + questions app_public.create_event_questions[] +) +returns app_public.event_questions[] as $$ +declare + v_input app_public.create_event_questions; + v_question app_public.event_questions; + v_ret app_public.event_questions[] default '{}'; +begin + -- Check permissions + call app_public.check_is_admin(); + + if questions is null then + return null; + end if; + + -- Create questions + foreach v_input in array questions loop + insert into app_public.event_questions(event_id, position, type, label, is_required, data, prefill) + values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data, nullif(v_input.prefill, 'NONE')) + returning * into v_question; + + v_ret := array_append(v_ret, v_question); + end loop; + + return v_ret; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +/* + * `prefill` follows the update rule of update_event: an omitted (null) + * prefill keeps the stored one, so callers that do not know about prefills + * leave them untouched. 'NONE' clears it, and so does a type other than + * TEXT, because only TEXT answers can be prefilled. + */ +create or replace function app_public.update_event_questions( + event_id uuid, + questions app_public.update_event_questions[] +) +returns app_public.event_questions[] as $$ +#variable_conflict use_variable +declare + v_question_ids_to_delete uuid[]; + v_input app_public.update_event_questions; + v_question app_public.event_questions; + v_ret app_public.event_questions[] default '{}'; +begin + -- Check permissions + call app_public.check_is_admin(); + + select array( + select id from app_public.event_questions as q + where q.event_id = event_id + and q.id not in (select id from unnest(questions) where id is not null) + ) + into v_question_ids_to_delete; + + -- Delete existing event questions that were not supplied + -- as input to this function + delete from app_public.event_questions as q + where q.id = any(v_question_ids_to_delete); + + foreach v_input in array questions loop + if exists(select 1 from app_public.event_questions where id = v_input.id) then + -- Update existing event questions by id + update app_public.event_questions + set position = v_input.position, type = v_input.type, label = v_input.label, is_required = v_input.is_required, data = v_input.data, + prefill = case + when v_input.type <> 'TEXT' or v_input.prefill = 'NONE' then null + else coalesce(v_input.prefill, prefill) + end + where id = v_input.id + returning * into v_question; + else + -- Create new questions that didn't exist before + insert into app_public.event_questions(event_id, position, type, label, is_required, data, prefill) + values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data, nullif(v_input.prefill, 'NONE')) + returning * into v_question; + end if; + + v_ret := array_append(v_ret, v_question); + end loop; + + return v_ret; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +/* + * The registration profile holds the values used to prefill registration + * answers. It is a table of its own rather than columns on app_public.users + * because users are publicly visible, and dietary restrictions are not + * anyone else's business. + */ +create table if not exists app_public.registration_profiles ( + user_id uuid primary key references app_public.users on delete cascade, + telegram text check(length(telegram) <= 64), + dietary_restrictions text check(length(dietary_restrictions) <= 1000), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +alter table app_public.registration_profiles enable row level security; + +drop trigger if exists _100_timestamps on app_public.registration_profiles; +create trigger _100_timestamps + before insert or update on app_public.registration_profiles for each row + execute procedure app_private.tg__timestamps(); + +comment on table app_public.registration_profiles is + E'Values used to prefill event registration answers. Only visible to the user themselves.'; +comment on column app_public.registration_profiles.user_id is + E'The user this registration profile belongs to.'; +comment on column app_public.registration_profiles.telegram is + E'Telegram handle.'; +comment on column app_public.registration_profiles.dietary_restrictions is + E'Dietary restrictions and allergies.'; + +drop policy if exists select_own on app_public.registration_profiles; +drop policy if exists insert_own on app_public.registration_profiles; +drop policy if exists update_own on app_public.registration_profiles; +drop policy if exists delete_own on app_public.registration_profiles; +create policy select_own on app_public.registration_profiles for select using (user_id = app_public.current_user_id()); +create policy insert_own on app_public.registration_profiles for insert with check (user_id = app_public.current_user_id()); +create policy update_own on app_public.registration_profiles for update using (user_id = app_public.current_user_id()); +create policy delete_own on app_public.registration_profiles for delete using (user_id = app_public.current_user_id()); + +grant + select, + insert (user_id, telegram, dietary_restrictions), + update (telegram, dietary_restrictions), + delete +on app_public.registration_profiles to :DATABASE_VISITOR; + +/* + * Answers are saved into the registration profile only when the user asks + * for it: on the settings page, or by ticking "remember these answers" in + * the registration form, which calls set_registration_profile after the + * registration succeeded. Nothing saves them inside the registration itself. + */ +drop trigger if exists _500_save_registration_profile on app_public.registrations; +drop function if exists app_private.tg_registrations__save_registration_profile(); + +/* + * Creates or updates the current user's registration profile. A null + * argument keeps the saved value and an empty one clears it, so the + * registration form can save only the fields its event asks for. Refused + * while `prefill_answers` is off; delete_registration_profile still works. + */ +create or replace function app_public.set_registration_profile( + telegram text default null, + dietary_restrictions text default null +) +returns app_public.registration_profiles as $$ +#variable_conflict use_variable +declare + v_user_id uuid := app_public.current_user_id(); + v_profile app_public.registration_profiles; +begin + if v_user_id is null then + raise exception 'You must log in to update your registration profile' using errcode = 'LOGIN'; + end if; + + if not app_public.feature_enabled('prefill_answers') then + raise exception 'Saving registration answers is not enabled' using errcode = 'FTOFF'; + end if; + + insert into app_public.registration_profiles(user_id, telegram, dietary_restrictions) + values (v_user_id, nullif(trim(telegram), ''), nullif(trim(dietary_restrictions), '')) + on conflict (user_id) do update + set + telegram = case + when telegram is null then registration_profiles.telegram + else excluded.telegram + end, + dietary_restrictions = case + when dietary_restrictions is null then registration_profiles.dietary_restrictions + else excluded.dietary_restrictions + end + returning * into v_profile; + + return v_profile; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; +comment on function app_public.set_registration_profile(telegram text, dietary_restrictions text) is + E'Set the values used to prefill your event registrations. A null value keeps the saved one and an empty value clears it.'; + +/* + * Deletes the current user's registration profile. Not gated: removing your + * own data keeps working while `prefill_answers` is off. + */ +create or replace function app_public.delete_registration_profile() +returns boolean as $$ +declare + v_user_id uuid := app_public.current_user_id(); +begin + if v_user_id is null then + raise exception 'You must log in to delete your registration profile' using errcode = 'LOGIN'; + end if; + + delete from app_public.registration_profiles where user_id = v_user_id; + return found; +end; +$$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; +comment on function app_public.delete_registration_profile() is + E'Delete the values saved to prefill your event registrations.'; + +/* + * The question type select offers prefill questions, the register page + * prefills their answers and the registration form and settings page save + * them only while `prefill_answers` is on. Questions keep their `prefill` + * marking whatever the flag's state. + */ +insert into app_public.feature_flags (key, description) + values ( + 'prefill_answers', + 'Prefill Telegram and dietary restriction answers from a registration profile the user saves on request.' + ) + on conflict (key) do nothing; diff --git a/@app/db/migrations/current/1-current.sql b/@app/db/migrations/current/1-current.sql index 67a36aa4f..8da533983 100644 --- a/@app/db/migrations/current/1-current.sql +++ b/@app/db/migrations/current/1-current.sql @@ -1,16 +1 @@ -/* - * Admins manage every organization, the same way `manage_admin` on - * `app_public.events` and `app_public.registrations` already lets them manage - * every event. Without this, `update_owner` is the only route to updating an - * organization, so changing one's settings requires an `is_owner` row in - * `organization_memberships` — which admins have no reason to hold, and which - * nobody holds for an organization they did not create. - * - * Membership keeps its own meaning: the way a non-admin is given rights over a - * single organization's events. - */ - -drop policy if exists manage_admin on app_public.organizations; - -create policy manage_admin on app_public.organizations - for all using (app_public.current_user_is_admin()); +-- Enter migration here diff --git a/@app/db/package.json b/@app/db/package.json index 90e80d42d..b7d26f03e 100644 --- a/@app/db/package.json +++ b/@app/db/package.json @@ -3,7 +3,7 @@ "private": true, "version": "0.0.0", "scripts": { - "gm": "NODE_OPTIONS=\"-r @app/config/env\" pnpm exec graphile-migrate", + "gm": "cross-env NODE_OPTIONS=\"-r @app/config/env\" pnpm exec graphile-migrate", "migrate": "pnpm gm migrate", "watch": "pnpm gm watch", "dev": "exit 0", @@ -13,15 +13,18 @@ "dump": "pnpm gm migrate && pnpm gm reset --shadow --erase && pnpm gm migrate --shadow --forceActions", "test": "NODE_ENV=test NODE_OPTIONS=\"-r @app/config/env.js\" pnpm exec jest", "create-fake-data": "ts-node -r @app/config/env.js scripts/create-fake-data.ts", + "create-demo-data": "ts-node -r @app/config/env.js scripts/create-demo-data.ts", "clean-fake-data": "ts-node -r @app/config/env.js scripts/clean-fake-data.ts", "depcheck": "depcheck --ignores=\"dayjs,@app/config\"" }, "dependencies": { + "cross-env": "^7.0.3", "graphile-migrate": "^1.4.0" }, "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/db/scripts/clean-fake-data.ts b/@app/db/scripts/clean-fake-data.ts index 46f91d8b1..57a654824 100644 --- a/@app/db/scripts/clean-fake-data.ts +++ b/@app/db/scripts/clean-fake-data.ts @@ -1,6 +1,9 @@ import { Pool, PoolClient } from "pg" -import { toggleRefreshMaterializedViewTrigger } from "./utils" +import { + refreshRegistrationPositions, + toggleRegistrationPositionTriggers, +} from "./utils" if (process.env.NODE_ENV !== "development") { console.error("This script should only be ran in development!") @@ -36,9 +39,10 @@ async function main() { const pgPool = new Pool({ connectionString }) const client = await pgPool.connect() try { - await toggleRefreshMaterializedViewTrigger(client, "disable") + await toggleRegistrationPositionTriggers(client, "disable") await cleanData(client) - await toggleRefreshMaterializedViewTrigger(client, "enable") + await toggleRegistrationPositionTriggers(client, "enable") + await refreshRegistrationPositions(client) } catch (e) { if (typeof e.code === "string" && e.code.match(/^[0-9A-Z]{5}$/)) { console.error([e.message, e.code, e.detail, e.hint, e.where].join("\n")) diff --git a/@app/db/scripts/create-demo-data.ts b/@app/db/scripts/create-demo-data.ts new file mode 100644 index 000000000..df04e4a68 --- /dev/null +++ b/@app/db/scripts/create-demo-data.ts @@ -0,0 +1,1041 @@ +/** + * Creates realistic-looking demo data for showing Ilmo off: guild events with + * real names, descriptions, quotas and questions, and registrations with + * plausible Finnish names and answers. Unlike create-fake-data it doesn't use + * random placeholder text, and it covers every state an event can be in: + * signup open (with full quotas, overflow spots and a queue), signup opening + * later, signup closed, and a draft. Dates are relative to today. + * + * Usage: pnpm db create-demo-data [admin username, default "testuser"] + * + * Safe to run again: organizations and categories are reused and events that + * already exist are skipped. Remove everything with pnpm db clean-fake-data. + */ +import { Pool, PoolClient } from "pg" + +import { + refreshRegistrationPositions, + toggleRegistrationPositionTriggers, +} from "./utils" + +if (process.env.NODE_ENV !== "development") { + console.error("This script should only be ran in development!") + process.exit(0) +} + +type Localized = { fi: string; en: string } +type Person = { firstName: string; lastName: string; email: string } +type Answer = string | string[] | undefined + +type QuestionDef = { + type: "TEXT" | "RADIO" | "CHECKBOX" + label: Localized + isRequired?: boolean + options?: Localized[] + // Answers are given by index into options for RADIO and CHECKBOX + answer: (person: Person, random: () => number) => Answer | number | number[] +} + +type QuotaDef = { title: Localized; size: number; registrations: number } + +type EventDef = { + name: Localized + description: Localized + location: string + organization: string + category: string + // [days from today, hour, minute] + registrationStart: [number, number, number?] + registrationEnd: [number, number, number?] + eventStart: [number, number, number?] + eventEnd: [number, number, number?] + quotas: QuotaDef[] + openQuotaSize?: number + questions?: QuestionDef[] + isHighlighted?: boolean + isDraft?: boolean +} + +/******************************************************************************/ +// Organizations and categories + +const organizations = [ + { slug: "prodeko", name: "Prodeko", color: "#002e7d" }, + { + slug: "prodeko-urheilukerho", + name: "Prodekon urheilukerho", + color: "#2e7d32", + }, + { + slug: "prodeko-kulttuurikerho", + name: "Prodekon kulttuurikerho", + color: "#8e24aa", + }, +] + +const categories: Record< + string, + { + organization: string + name: Localized + description: Localized + color: string + } +> = { + sitsit: { + organization: "prodeko", + name: { fi: "Sitsit", en: "Sitsit" }, + description: { + fi: "Laulua, ruokaa ja juomaa pitkien pöytien ääressä.", + en: "Singing, food and drinks at long tables.", + }, + color: "#c62828", + }, + juhlat: { + organization: "prodeko", + name: { fi: "Juhlat", en: "Parties" }, + description: { + fi: "Killan suuret juhlat ympäri vuoden.", + en: "The guild's big celebrations throughout the year.", + }, + color: "#f9a825", + }, + excursiot: { + organization: "prodeko", + name: { fi: "Excursiot", en: "Excursions" }, + description: { + fi: "Matkoja ja vierailuja Otaniemen ulkopuolelle.", + en: "Trips and visits outside Otaniemi.", + }, + color: "#00838f", + }, + yritys: { + organization: "prodeko", + name: { fi: "Yritysyhteistyö", en: "Corporate relations" }, + description: { + fi: "Yritysvierailuja, case-iltoja ja rekrytapahtumia.", + en: "Company visits, case evenings and recruiting events.", + }, + color: "#37474f", + }, + vapaaAika: { + organization: "prodeko", + name: { fi: "Vapaa-aika", en: "Free time" }, + description: { + fi: "Rentoa yhdessäoloa ilman sen kummempaa ohjelmaa.", + en: "Relaxed get-togethers without much of a programme.", + }, + color: "#6d4c41", + }, + urheilu: { + organization: "prodeko-urheilukerho", + name: { fi: "Urheilu", en: "Sports" }, + description: { + fi: "Turnauksia, vuorojen täyttöä ja hikeä.", + en: "Tournaments, weekly sports and sweat.", + }, + color: "#2e7d32", + }, + kulttuuri: { + organization: "prodeko-kulttuurikerho", + name: { fi: "Kulttuuri", en: "Culture" }, + description: { + fi: "Teatteria, museoita ja konsertteja porukalla.", + en: "Theatre, museums and concerts together.", + }, + color: "#8e24aa", + }, +} + +/******************************************************************************/ +// Questions + +const yes = { fi: "Kyllä", en: "Yes" } +const no = { fi: "Ei", en: "No" } + +// Picks an index, the first options being the most likely +const pickWeighted = (random: () => number, weights: number[]) => { + const total = weights.reduce((a, b) => a + b, 0) + let r = random() * total + for (let i = 0; i < weights.length; i++) { + r -= weights[i] + if (r < 0) return i + } + return weights.length - 1 +} + +const telegram: QuestionDef = { + type: "TEXT", + label: { fi: "Telegram", en: "Telegram" }, + isRequired: true, + answer: (p) => `@${ascii(p.firstName)}_${ascii(p.lastName).slice(0, 3)}`, +} + +const alcohol: QuestionDef = { + type: "RADIO", + label: { fi: "Alkoholivalinta", en: "Alcohol preference" }, + isRequired: true, + options: [ + { fi: "Holillinen", en: "Alcoholic" }, + { fi: "Holiton", en: "Non-alcoholic" }, + { fi: "Holittomat shotit", en: "Non-alcoholic shots" }, + ], + answer: (_, random) => pickWeighted(random, [7, 2, 1]), +} + +const specialDiet: QuestionDef = { + type: "CHECKBOX", + label: { fi: "Erityisruokavalio", en: "Special diet" }, + options: [ + { fi: "Kasvis", en: "Vegetarian" }, + { fi: "Laktoositon", en: "Lactose-free" }, + { fi: "Gluteeniton", en: "Gluten-free" }, + { fi: "Vegaani", en: "Vegan" }, + ], + answer: (_, random) => { + const r = random() + if (r < 0.65) return [] + if (r < 0.95) return [pickWeighted(random, [4, 3, 1, 2])] + return [1, 2] + }, +} + +const otherDiet: QuestionDef = { + type: "TEXT", + label: { + fi: "Muu erityisruokavalio tai allergia", + en: "Other special diet or allergy", + }, + answer: (_, random) => + random() < 0.12 + ? ["Pähkinäallergia", "Kalaton", "Ei sieniä", "Selleriallergia"][ + Math.floor(random() * 4) + ] + : undefined, +} + +const seating: QuestionDef = { + type: "TEXT", + label: { fi: "Paikkatoiveet", en: "Seating preferences" }, + answer: (_, random) => + random() < 0.3 + ? `${firstNames[Math.floor(random() * firstNames.length)]}n viereen, kiitos!` + : undefined, +} + +const avec: QuestionDef = { + type: "TEXT", + label: { fi: "Avec", en: "Avec" }, + answer: (_, random) => + random() < 0.35 + ? `${firstNames[Math.floor(random() * firstNames.length)]} ${ + lastNames[Math.floor(random() * lastNames.length)] + }` + : undefined, +} + +const bindingRegistration: QuestionDef = { + type: "CHECKBOX", + label: { fi: "Sitova ilmoittautuminen", en: "Binding registration" }, + isRequired: true, + options: [ + { + fi: "Ymmärrän, että osallistumismaksu muuttuu sitovaksi ilmoittautumisen päätyttyä", + en: "I understand that the participation fee becomes binding once registration closes", + }, + ], + answer: () => [0], +} + +const sitsitQuestions = [ + telegram, + alcohol, + specialDiet, + otherDiet, + seating, + bindingRegistration, +] + +/******************************************************************************/ +// Events + +const yearGroupQuotas = (sizes: number[], registrations: number[]) => + ["I", "II", "III", "IV", "N"].map((title, i) => ({ + title: { fi: title, en: title }, + size: sizes[i], + registrations: registrations[i], + })) + +const openQuota = (size: number, registrations: number): QuotaDef => ({ + title: { fi: "Avoin kiintiö", en: "Open quota" }, + size, + registrations, +}) + +const events: EventDef[] = [ + // Signup open now + { + name: { fi: "Fuksisitsit", en: "Freshman sitsit" }, + description: { + fi: "Syksyn perinteiset fuksisitsit! Luvassa kolmen ruokalajin illallinen, laulua laulukirjan kera ja tutoreiden yllätysohjelmaa. Pukukoodi: cocktail ja haalarit. Fuksit ovat etusijalla, vanhemmille opiskelijoille on oma kiintiönsä.", + en: "The traditional freshman sitsit! A three-course dinner, singing from the songbook and a surprise programme by the tutors. Dress code: cocktail and overalls. Freshmen come first, older students have their own quota.", + }, + location: "Dipoli, Otakaari 24", + organization: "prodeko", + category: "sitsit", + registrationStart: [-3, 12], + registrationEnd: [4, 23, 59], + eventStart: [8, 18], + eventEnd: [9, 2], + quotas: [ + { + title: { fi: "Fuksit (I)", en: "Freshmen (I)" }, + size: 60, + registrations: 47, + }, + { + title: { fi: "Vanhemmat (II–N)", en: "Older students (II–N)" }, + size: 20, + registrations: 28, + }, + ], + openQuotaSize: 6, + questions: sitsitQuestions, + }, + { + name: { fi: "Excursio Tallinnaan", en: "Excursion to Tallinn" }, + description: { + fi: "Kahden päivän excursio Tallinnaan: yritysvierailut Telliskivessä, yhteinen illallinen vanhassakaupungissa ja paluu seuraavana iltana. Hinta sisältää laivamatkat, hostellin ja illallisen.", + en: "A two-day excursion to Tallinn: company visits in Telliskivi, a dinner in the old town and the trip back the next evening. The price includes the ferries, a hostel and the dinner.", + }, + location: "Länsisatama, Terminaali 2, Helsinki", + organization: "prodeko", + category: "excursiot", + registrationStart: [-1, 12], + registrationEnd: [9, 23, 59], + eventStart: [20, 8], + eventEnd: [21, 20], + quotas: yearGroupQuotas([10, 10, 10, 10, 10], [6, 10, 4, 3, 2]), + questions: [ + specialDiet, + otherDiet, + { + type: "TEXT", + label: { fi: "Huonetoive", en: "Room preference" }, + answer: (_, random) => + random() < 0.4 + ? `Samaan huoneeseen ${ + firstNames[Math.floor(random() * firstNames.length)] + }n kanssa` + : undefined, + }, + bindingRegistration, + ], + }, + { + name: { fi: "Saunailta", en: "Sauna evening" }, + description: { + fi: "Rantasauna lämpiää ja grilli kuumenee. Ota mukaan pyyhe ja omat eväät, killan puolesta makkaraa ja limua.", + en: "The beach sauna is warming up and so is the grill. Bring a towel and your own snacks, the guild provides sausages and soft drinks.", + }, + location: "Rantasauna, Otaniemi", + organization: "prodeko", + category: "vapaaAika", + registrationStart: [-4, 12], + registrationEnd: [1, 23, 59], + eventStart: [3, 18], + eventEnd: [3, 23, 30], + quotas: [openQuota(40, 31)], + }, + { + name: { fi: "Salibandyturnaus", en: "Floorball tournament" }, + description: { + fi: "Vuosikurssien välinen salibandyturnaus. Joukkueet arvotaan ilmoittautuneiden kesken, mailoja saa lainaan.", + en: "A floorball tournament between the year groups. Teams are drawn among the registrants, sticks can be borrowed.", + }, + location: "Otahalli, Otaniementie 17", + organization: "prodeko-urheilukerho", + category: "urheilu", + registrationStart: [-6, 12], + registrationEnd: [2, 23, 59], + eventStart: [5, 10], + eventEnd: [5, 16], + quotas: [ + { + title: { fi: "Pelaajat", en: "Players" }, + size: 36, + registrations: 41, + }, + ], + questions: [ + { + type: "RADIO", + label: { fi: "Pelipaikka", en: "Position" }, + isRequired: true, + options: [ + { fi: "Kenttäpelaaja", en: "Field player" }, + { fi: "Maalivahti", en: "Goalkeeper" }, + ], + answer: (_, random) => pickWeighted(random, [9, 1]), + }, + { + type: "RADIO", + label: { fi: "Tarvitsetko mailan?", en: "Do you need a stick?" }, + isRequired: true, + options: [yes, no], + answer: (_, random) => pickWeighted(random, [1, 2]), + }, + ], + }, + { + name: { + fi: "Yritysvierailu: Kvartaali Consulting", + en: "Company visit: Kvartaali Consulting", + }, + description: { + fi: "Kvartaali Consulting esittelee konsultin arkea ja kesätyömahdollisuuksia. Vierailun jälkeen iltapala ja vapaata verkostoitumista.", + en: "Kvartaali Consulting presents the everyday life of a consultant and their summer jobs. Snacks and networking after the visit.", + }, + location: "Kvartaali Consulting, Mannerheimintie 12, Helsinki", + organization: "prodeko", + category: "yritys", + registrationStart: [-2, 12], + registrationEnd: [6, 23, 59], + eventStart: [12, 16], + eventEnd: [12, 19], + quotas: [ + { + title: { fi: "Kandivaihe (I–III)", en: "Bachelor's (I–III)" }, + size: 15, + registrations: 9, + }, + { + title: { fi: "Maisterivaihe (IV–N)", en: "Master's (IV–N)" }, + size: 15, + registrations: 19, + }, + ], + openQuotaSize: 3, + questions: [ + { + type: "RADIO", + label: { + fi: "Kiinnostaako kesätyö?", + en: "Are you interested in a summer job?", + }, + isRequired: true, + options: [yes, { fi: "Ehkä", en: "Maybe" }, no], + answer: (_, random) => pickWeighted(random, [5, 3, 2]), + }, + { + type: "TEXT", + label: { fi: "Pääaine", en: "Major" }, + answer: (_, random) => + random() < 0.7 + ? [ + "Tuotantotalous", + "Strategy and Venturing", + "Operations Management", + ][Math.floor(random() * 3)] + : undefined, + }, + ], + }, + + // Signup opens later + { + name: { fi: "Prodekon vuosijuhlat", en: "Prodeko's annual gala" }, + description: { + fi: "Killan vuoden juhlavin ilta: cocktailtilaisuus, kolmen ruokalajin illallinen, tanssit ja jatkot. Pukukoodi: frakki tai iltapuku. Avecit ovat tervetulleita omassa kiintiössään.", + en: "The guild's most festive evening of the year: cocktails, a three-course dinner, dancing and an after-party. Dress code: white tie. Avecs are welcome in their own quota.", + }, + location: "Vanha ylioppilastalo, Mannerheimintie 3, Helsinki", + organization: "prodeko", + category: "juhlat", + registrationStart: [6, 12], + registrationEnd: [20, 23, 59], + eventStart: [45, 18], + eventEnd: [46, 4], + quotas: [ + { + title: { fi: "Prodekolaiset", en: "Prodeko members" }, + size: 120, + registrations: 0, + }, + { + title: { fi: "Kutsuvieraat", en: "Invited guests" }, + size: 30, + registrations: 0, + }, + { title: { fi: "Avecit", en: "Avecs" }, size: 40, registrations: 0 }, + ], + openQuotaSize: 10, + questions: [ + avec, + alcohol, + specialDiet, + otherDiet, + seating, + bindingRegistration, + ], + isHighlighted: true, + }, + { + name: { fi: "Laskiaisrieha", en: "Shrovetide sledding" }, + description: { + fi: "Pulkkamäkeä, hernekeittoa ja laskiaispullia. Kisaamme myös perinteisessä pulkkaviestissä vuosikursseittain.", + en: "Sledding, pea soup and Shrovetide buns. We also race in the traditional sled relay between the year groups.", + }, + location: "Malminkartanonhuippu, Helsinki", + organization: "prodeko", + category: "vapaaAika", + registrationStart: [2, 12], + registrationEnd: [12, 23, 59], + eventStart: [16, 10], + eventEnd: [16, 18], + quotas: [openQuota(80, 0)], + questions: [ + { + type: "RADIO", + label: { fi: "Tuotko oman pulkan?", en: "Are you bringing a sled?" }, + isRequired: true, + options: [yes, no], + answer: () => 0, + }, + ], + }, + { + name: { fi: "Wappubrunssi", en: "Vappu brunch" }, + description: { + fi: "Kuohuvaa, simaa ja runsas brunssipöytä wapun kunniaksi. Ylioppilaslakki päähän!", + en: "Sparkling wine, sima and a generous brunch table for Vappu. Remember your student cap!", + }, + location: "Prodeko-kiltahuone, Otakaari 1", + organization: "prodeko", + category: "juhlat", + registrationStart: [9, 12], + registrationEnd: [18, 23, 59], + eventStart: [30, 11], + eventEnd: [30, 15], + quotas: yearGroupQuotas([12, 12, 12, 12, 12], [0, 0, 0, 0, 0]), + questions: [specialDiet, otherDiet], + }, + + // Signup closed + { + name: { fi: "Appro", en: "Appro pub crawl" }, + description: { + fi: "Perinteinen appro Helsingin keskustassa: kuusi rastia, haalarimerkki ja jatkot. Ilmoittaudu tiimisi kanssa!", + en: "The traditional appro in central Helsinki: six checkpoints, an overall patch and an after-party. Register with your team!", + }, + location: "Lähtö: Kansalaistori, Helsinki", + organization: "prodeko", + category: "juhlat", + registrationStart: [-25, 12], + registrationEnd: [-12, 23, 59], + eventStart: [-8, 17], + eventEnd: [-8, 23, 59], + quotas: [openQuota(100, 108)], + questions: [ + { + type: "TEXT", + label: { fi: "Tiimin nimi", en: "Team name" }, + isRequired: true, + answer: (_, random) => + [ + "Kvartaalikiitäjät", + "Excel-velhot", + "Pivot-pojat", + "Kassavirta", + "Tase ja tunteet", + ][Math.floor(random() * 5)], + }, + ], + }, + { + name: { fi: "Pikkujoulut", en: "Christmas party" }, + description: { + fi: "Jouluruokaa, glögiä ja joulupukki! Kiltahuone on koristeltu ja tonttulakit kaivettu esiin.", + en: "Christmas food, mulled wine and Santa Claus! The guild room is decorated and the elf hats are out.", + }, + location: "Prodeko-kiltahuone, Otakaari 1", + organization: "prodeko", + category: "juhlat", + registrationStart: [-35, 12], + registrationEnd: [-20, 23, 59], + eventStart: [-15, 18], + eventEnd: [-15, 23, 59], + quotas: yearGroupQuotas([20, 20, 20, 20, 20], [20, 17, 12, 9, 6]), + questions: [alcohol, specialDiet, otherDiet], + }, + { + name: { fi: "Teatteri-ilta", en: "Theatre evening" }, + description: { + fi: "Kulttuurikerho lähtee katsomaan syksyn puhutuinta komediaa. Liput kerhon piikkiin, väliajalla kuohuvaa.", + en: "The culture club goes to see the most talked-about comedy of the autumn. Tickets on the club, sparkling wine in the intermission.", + }, + location: "Kaupunginteatteri, Eläintarhantie 5, Helsinki", + organization: "prodeko-kulttuurikerho", + category: "kulttuuri", + registrationStart: [-14, 12], + registrationEnd: [-6, 23, 59], + eventStart: [-3, 19], + eventEnd: [-3, 22], + quotas: [openQuota(25, 25)], + }, + + // Draft, only visible to admins + { + name: { fi: "Kevätretki Nuuksioon", en: "Spring hike in Nuuksio" }, + description: { + fi: "Päiväretki Nuuksion kansallispuistoon: patikointia, nuotiolla paistettua makkaraa ja kevään ensimmäiset pulahdukset. Suunnitelma vielä kesken.", + en: "A day trip to Nuuksio national park: hiking, sausages over the campfire and the first dips of spring. The plan is still a work in progress.", + }, + location: "Haukkalammen pysäköintialue, Nuuksio", + organization: "prodeko", + category: "vapaaAika", + registrationStart: [25, 12], + registrationEnd: [32, 23, 59], + eventStart: [40, 9], + eventEnd: [40, 17], + quotas: [openQuota(30, 0)], + isDraft: true, + }, +] + +/******************************************************************************/ +// People + +const firstNames = [ + "Aino", + "Eetu", + "Emma", + "Elias", + "Helmi", + "Onni", + "Venla", + "Leevi", + "Aada", + "Väinö", + "Ella", + "Niilo", + "Siiri", + "Oliver", + "Iida", + "Eino", + "Sofia", + "Leo", + "Kerttu", + "Veeti", + "Pihla", + "Joona", + "Lumi", + "Otto", + "Isla", + "Aleksi", + "Enni", + "Juho", + "Linnea", + "Santeri", + "Lotta", + "Roope", + "Maija", + "Tuomas", + "Ronja", + "Matias", + "Ilona", + "Lauri", + "Vilma", + "Akseli", + "Maijuli Kielo", + "Anna-Liisa", + "Juha-Pekka", +] + +const lastNames = [ + "Korhonen", + "Virtanen", + "Mäkinen", + "Nieminen", + "Mäkelä", + "Hämäläinen", + "Laine", + "Heikkinen", + "Koskinen", + "Järvinen", + "Lehtonen", + "Lehtinen", + "Saarinen", + "Salminen", + "Heinonen", + "Niemi", + "Heikkilä", + "Kinnunen", + "Salonen", + "Turunen", + "Salo", + "Laitinen", + "Tuominen", + "Rantanen", + "Karjalainen", + "Jokinen", + "Mattila", + "Savolainen", + "Lahtinen", + "Ahonen", + "Juokko Tuoppo", + "von Bonsdorff", +] + +// Small deterministic random generator, so every run creates the same data +function seededRandom(seed: number) { + let state = seed + return () => { + state |= 0 + state = (state + 0x6d2b79f5) | 0 + let t = Math.imul(state ^ (state >>> 15), 1 | state) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function ascii(text: string) { + return text + .toLowerCase() + .replace(/[äå]/g, "a") + .replace(/ö/g, "o") + .replace(/[^a-z0-9]+/g, "") +} + +function slugify(text: string) { + return text + .toLowerCase() + .replace(/[äå]/g, "a") + .replace(/ö/g, "o") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") +} + +function makePerson(random: () => number, index: number): Person { + const firstName = firstNames[Math.floor(random() * firstNames.length)] + const lastName = lastNames[Math.floor(random() * lastNames.length)] + return { + firstName, + lastName, + // example.com is reserved for examples, so no email can reach anyone + email: `${ascii(firstName)}.${ascii(lastName)}${index}@example.com`, + } +} + +/******************************************************************************/ +// Database + +function at([days, hour, minute = 0]: [number, number, number?]) { + const date = new Date() + date.setDate(date.getDate() + days) + date.setHours(hour, minute, minute === 59 ? 59 : 0, 0) + return date +} + +const paragraphs = (text: string) => [ + { type: "paragraph", children: [{ text }] }, +] + +async function getOrCreateUser(client: PoolClient, username: string) { + const { + rows: [existing], + } = await client.query("select * from app_public.users where username = $1", [ + username, + ]) + if (existing) return existing + + const { + rows: [user], + } = await client.query( + `insert into app_public.users (username, name, is_admin) + values ($1, $1, true) returning *`, + [username] + ) + await client.query( + `insert into app_public.user_emails (user_id, email, is_verified, is_primary) + values ($1, $2, true, true)`, + [user.id, `${username}@example.com`] + ) + await client.query( + `update app_private.user_secrets + set password_hash = crypt('kananugetti', gen_salt('bf')) + where user_id = $1`, + [user.id] + ) + return user +} + +async function getOrCreateOrganization( + client: PoolClient, + org: (typeof organizations)[number], + userId: string +) { + const { + rows: [organization], + } = await client.query( + `insert into app_public.organizations (slug, name, color) + values ($1, $2, $3) + on conflict (slug) do update set name = excluded.name + returning *`, + [org.slug, org.name, org.color] + ) + await client.query( + `insert into app_public.organization_memberships (organization_id, user_id, is_owner) + values ($1, $2, true) + on conflict do nothing`, + [organization.id, userId] + ) + return organization +} + +async function getOrCreateCategory( + client: PoolClient, + key: string, + organizationId: string +) { + const category = categories[key] + const { + rows: [existing], + } = await client.query( + `select * from app_public.event_categories + where owner_organization_id = $1 and name->>'fi' = $2`, + [organizationId, category.name.fi] + ) + if (existing) return existing + + const { + rows: [created], + } = await client.query( + `insert into app_public.event_categories (name, description, color, owner_organization_id) + values ($1, $2, $3, $4) returning *`, + [category.name, category.description, category.color, organizationId] + ) + return created +} + +function toAnswer( + question: QuestionDef, + raw: ReturnType, + lang: "fi" | "en" +) { + if (raw === undefined) return undefined + if (question.type === "TEXT") return raw as string + const option = (index: number) => question.options![index][lang] + if (question.type === "RADIO") return option(raw as number) + return (raw as number[]).map(option) +} + +async function createEvent( + client: PoolClient, + def: EventDef, + organizationId: string, + categoryId: string, + random: () => number +) { + const eventStart = at(def.eventStart) + const day = `${eventStart.getFullYear()}-${eventStart.getMonth() + 1}-${eventStart.getDate()}` + const slug = `${day}-${slugify(def.name.fi)}` + + const { + rows: [existing], + } = await client.query("select id from app_public.events where slug = $1", [ + slug, + ]) + if (existing) { + console.log(` skipped "${def.name.fi}", it already exists`) + return + } + + const { + rows: [event], + } = await client.query( + `insert into app_public.events ( + name, slug, description, location, + event_start_time, event_end_time, + registration_start_time, registration_end_time, + is_highlighted, is_draft, open_quota_size, + owner_organization_id, category_id + ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) + returning *`, + [ + def.name, + slug, + { + fi: paragraphs(def.description.fi), + en: paragraphs(def.description.en), + }, + def.location, + eventStart, + at(def.eventEnd), + at(def.registrationStart), + at(def.registrationEnd), + def.isHighlighted ?? false, + def.isDraft ?? false, + def.openQuotaSize ?? 0, + organizationId, + categoryId, + ] + ) + + const questions = [] + const questionDefs = def.questions ?? [] + for (let position = 0; position < questionDefs.length; position++) { + const q = questionDefs[position] + const { + rows: [question], + } = await client.query( + `insert into app_public.event_questions (event_id, position, type, label, is_required, data) + values ($1, $2, $3, $4, $5, $6) returning id`, + [ + event.id, + position, + q.type, + q.label, + q.isRequired ?? false, + q.options ?? null, + ] + ) + questions.push({ id: question.id, def: q }) + } + + // Registrations arrive between signup opening and now (or signup closing) + const signupFrom = at(def.registrationStart).getTime() + const signupTo = Math.min(Date.now(), at(def.registrationEnd).getTime()) + let total = 0 + + for (let position = 0; position < def.quotas.length; position++) { + const quotaDef = def.quotas[position] + const { + rows: [quota], + } = await client.query( + `insert into app_public.quotas (event_id, position, title, size) + values ($1, $2, $3, $4) returning id`, + [event.id, position, quotaDef.title, quotaDef.size] + ) + + for (let i = 0; i < quotaDef.registrations; i++) { + const person = makePerson(random, total) + const lang = random() < 0.85 ? "fi" : "en" + const answers: Record = {} + for (const { id, def: q } of questions) { + const answer = toAnswer(q, q.answer(person, random), lang) + if (answer !== undefined) answers[id] = answer + } + // Earlier registrations come in quickly after signup opens + const createdAt = new Date( + signupFrom + Math.pow(random(), 2) * (signupTo - signupFrom) + ) + + const { + rows: [registration], + } = await client.query( + `insert into app_public.registrations + (event_id, quota_id, first_name, last_name, email, answers, is_finished, created_at, updated_at) + values ($1, $2, $3, $4, $5, $6, true, $7, $7) returning id`, + [ + event.id, + quota.id, + person.firstName, + person.lastName, + person.email, + answers, + createdAt, + ] + ) + await client.query( + `insert into app_private.registration_secrets (event_id, quota_id, registration_id) + values ($1, $2, $3)`, + [event.id, quota.id, registration.id] + ) + total++ + } + } + + console.log(` created "${def.name.fi}" with ${total} registrations`) +} + +// Triggers that would get in the way of inserting historical data: the +// timestamps trigger overwrites created_at, the validity trigger rejects +// registrations outside the signup window and registration positions would be +// recomputed after every single row. They are switched back on, and positions +// recomputed once, before commit. +const triggers = [ + ["app_public.registrations", "_100_timestamps"], + ["app_public.registrations", "_300_registration_is_valid"], +] as const + +async function setTriggers(client: PoolClient, mode: "enable" | "disable") { + for (const [table, trigger] of triggers) { + await client.query(`alter table ${table} ${mode} trigger ${trigger}`) + } + await toggleRegistrationPositionTriggers(client, mode) +} + +async function main() { + const connectionString = process.env.DATABASE_URL + if (!connectionString) { + throw new Error("DATABASE_URL not set!") + } + const username = process.argv[2] || "testuser" + const random = seededRandom(2026) + + const pgPool = new Pool({ connectionString }) + const client = await pgPool.connect() + try { + // Everything happens in one transaction, including switching the + // triggers off and on, so a failure leaves the database untouched + await client.query("begin") + await client.query("reset role") + await setTriggers(client, "disable") + + const user = await getOrCreateUser(client, username) + const orgIds: Record = {} + for (const org of organizations) { + orgIds[org.slug] = ( + await getOrCreateOrganization(client, org, user.id) + ).id + } + + console.log("Creating demo events:") + for (const def of events) { + const category = await getOrCreateCategory( + client, + def.category, + orgIds[def.organization] + ) + await createEvent( + client, + def, + orgIds[def.organization], + category.id, + random + ) + } + + await setTriggers(client, "enable") + await refreshRegistrationPositions(client) + await client.query("commit") + console.log( + `Done. Log in as "${username}" to see the drafts and admin views.` + ) + } catch (e) { + await client.query("rollback") + if (typeof e.code === "string" && e.code.match(/^[0-9A-Z]{5}$/)) { + console.error([e.message, e.code, e.detail, e.hint, e.where].join("\n")) + } + throw e + } finally { + client.release() + await pgPool.end() + } +} + +main().catch((e) => { + console.error(e) + process.exit(1) +}) diff --git a/@app/db/scripts/create-fake-data.ts b/@app/db/scripts/create-fake-data.ts index c90d4317e..9f2894d4e 100644 --- a/@app/db/scripts/create-fake-data.ts +++ b/@app/db/scripts/create-fake-data.ts @@ -14,7 +14,10 @@ import { User, } from "../../__tests__/data" -import { toggleRefreshMaterializedViewTrigger } from "./utils" +import { + refreshRegistrationPositions, + toggleRegistrationPositionTriggers, +} from "./utils" if (process.env.NODE_ENV !== "development") { console.error("This script should only be ran in development!") @@ -120,11 +123,12 @@ async function main() { const pgPool = new Pool({ connectionString }) const client = await pgPool.connect() try { - await toggleRefreshMaterializedViewTrigger(client, "disable") + await toggleRegistrationPositionTriggers(client, "disable") await client.query("begin") await generateData(client) await client.query("commit") - await toggleRefreshMaterializedViewTrigger(client, "enable") + await toggleRegistrationPositionTriggers(client, "enable") + await refreshRegistrationPositions(client) } catch (e) { if (typeof e.code === "string" && e.code.match(/^[0-9A-Z]{5}$/)) { console.error([e.message, e.code, e.detail, e.hint, e.where].join("\n")) diff --git a/@app/db/scripts/dump-db.js b/@app/db/scripts/dump-db.js index 310d44114..47a5541c1 100644 --- a/@app/db/scripts/dump-db.js +++ b/@app/db/scripts/dump-db.js @@ -25,18 +25,37 @@ const NOISE = const outPath = "../../data/schema.sql" const out = fs.createWriteStream(outPath) -const child = spawn( - process.env.PG_DUMP || "pg_dump", - [ - "--no-sync", - "--schema-only", - "--no-owner", - "--exclude-schema=graphile_migrate", - "--exclude-schema=graphile_worker", - connectionString, - ], - { stdio: ["ignore", "pipe", "inherit"] } -) +const pgDumpArgs = [ + "--no-sync", + "--schema-only", + "--no-owner", + "--exclude-schema=graphile_migrate", + "--exclude-schema=graphile_worker", +] + +// On Windows there's usually no local pg_dump, so run one in a throwaway +// Docker container instead. CI dumps with pg_dump 16+, whose output differs +// from the db container's pg_dump 14, so use a postgres:16 image and reach the +// host-mapped port through host.docker.internal. Set PG_DUMP to force a local +// binary, or PG_DUMP_DOCKER_IMAGE to pick another image. +const dockerImage = + process.env.PG_DUMP_DOCKER_IMAGE || + (process.platform === "win32" && !process.env.PG_DUMP ? "postgres:16" : "") + +let command, args +if (dockerImage) { + const url = new URL(connectionString) + if (["localhost", "127.0.0.1"].includes(url.hostname)) { + url.hostname = "host.docker.internal" + } + command = "docker" + args = ["run", "--rm", dockerImage, "pg_dump", ...pgDumpArgs, url.toString()] +} else { + command = process.env.PG_DUMP || "pg_dump" + args = [...pgDumpArgs, connectionString] +} + +const child = spawn(command, args, { stdio: ["ignore", "pipe", "inherit"] }) let pending = "" child.stdout.on("data", (chunk) => { diff --git a/@app/db/scripts/utils.ts b/@app/db/scripts/utils.ts index 3a88c8c34..fd6115991 100644 --- a/@app/db/scripts/utils.ts +++ b/@app/db/scripts/utils.ts @@ -1,12 +1,34 @@ import { PoolClient } from "pg" -export async function toggleRefreshMaterializedViewTrigger( +const REGISTRATION_POSITION_TRIGGERS = [ + ["app_public.registrations", "_700_refresh_registration_positions"], + ["app_public.registrations", "_701_refresh_registration_positions"], + ["app_public.events", "_300_refresh_registration_positions"], + ["app_public.events", "_301_refresh_registration_positions"], + ["app_public.quotas", "_300_refresh_registration_positions"], + ["app_public.quotas", "_301_refresh_registration_positions"], +] + +/* + * Bulk changes recompute registration positions once per changed row. Disable + * the triggers around a bulk change and call refreshRegistrationPositions + * afterwards to recompute every event once. + */ +export async function toggleRegistrationPositionTriggers( client: PoolClient, mode: "enable" | "disable" ) { await client.query( - `alter table app_public.registrations ${mode} trigger _700_refresh_mat_view; - alter table app_public.events ${mode} trigger _300_refresh_mat_view; - alter table app_public.quotas ${mode} trigger _300_refresh_mat_view;` + REGISTRATION_POSITION_TRIGGERS.map( + ([table, trigger]) => `alter table ${table} ${mode} trigger ${trigger};` + ).join("\n") + ) +} + +export async function refreshRegistrationPositions(client: PoolClient) { + await client.query( + `delete from app_hidden.registrations_status_and_position + where id not in (select id from app_public.registrations); + select app_private.refresh_registration_positions(id) from app_public.events;` ) } diff --git a/@app/e2e/cypress/e2e/admin_features.spec.ts b/@app/e2e/cypress/e2e/admin_features.spec.ts new file mode 100644 index 000000000..98c01a0cc --- /dev/null +++ b/@app/e2e/cypress/e2e/admin_features.spec.ts @@ -0,0 +1,108 @@ +/// + +const FLAG = "test_e2e_flag" +const FRESH_FLAG = "test_e2e_fresh" +const UNAVAILABLE_FLAG = "test_e2e_unconfigured" + +const segment = (key: string, state: "off" | "admins_only" | "on") => + cy.getCy(`feature-${key}-state-${state}`).closest(".ant-segmented-item") + +const shouldBeIn = (key: string, state: "off" | "admins_only" | "on") => + segment(key, state).should("have.class", "ant-segmented-item-selected") + +context("Features page", () => { + beforeEach(() => cy.serverCommand("clearTestUsers")) + beforeEach(() => cy.serverCommand("clearTestEventData")) + beforeEach(() => cy.serverCommand("deleteTestFeatureFlags")) + after(() => cy.serverCommand("deleteTestFeatureFlags")) + + it("lets a developer switch a flag through every state", () => { + cy.serverCommand("createTestFeatureFlag", { key: FLAG }) + cy.login({ isAdmin: true, isDeveloper: true, next: "admin/event/list" }) + + cy.getCy("admin-sider-features").click() + cy.url().should("equal", Cypress.env("ROOT_URL") + "/admin/features") + cy.getCy(`feature-row-${FLAG}`).should("contain", FLAG) + shouldBeIn(FLAG, "off") + + // Off -> Admins only saves at once. + cy.getCy(`feature-${FLAG}-state-admins_only`).click() + cy.get(".ant-message").should("contain", FLAG) + shouldBeIn(FLAG, "admins_only") + cy.getCy("feature-confirm-on-modal").should("not.exist") + + // Into On asks first; the flag has been previewed. + cy.getCy(`feature-${FLAG}-state-on`).click() + cy.getCy("feature-confirm-previewed").should("be.visible") + cy.getCy("feature-confirm-preview").should("not.exist") + cy.getCy("feature-confirm-cancel").filter(":visible").click() + shouldBeIn(FLAG, "admins_only") + + cy.getCy(`feature-${FLAG}-state-on`).click() + cy.getCy("feature-confirm-on").click() + shouldBeIn(FLAG, "on") + + // Out of On asks first, with what stops and what keeps working. + cy.getCy(`feature-${FLAG}-state-off`).click() + cy.getCy("feature-confirm-stops").should("be.visible") + cy.getCy("feature-confirm-keeps").should("be.visible") + cy.getCy("feature-confirm-leave-on").click() + shouldBeIn(FLAG, "off") + + // The history lists the three changes, newest first. + cy.getCy(`feature-${FLAG}-history`).click() + cy.getCy("feature-history-drawer") + .find("[data-cy=feature-history-event]") + .should("have.length", 3) + }) + + it("recommends a preview before turning on a flag never previewed", () => { + cy.serverCommand("createTestFeatureFlag", { key: FRESH_FLAG }) + cy.login({ isAdmin: true, isDeveloper: true, next: "admin/features" }) + + cy.getCy(`feature-${FRESH_FLAG}-state-on`).click() + cy.getCy("feature-confirm-never-previewed").should("be.visible") + cy.getCy("feature-confirm-preview").click() + shouldBeIn(FRESH_FLAG, "admins_only") + }) + + it("does not let a developer switch on an unavailable flag", () => { + cy.serverCommand("createTestFeatureFlag", { + key: UNAVAILABLE_FLAG, + available: false, + }) + cy.login({ isAdmin: true, isDeveloper: true, next: "admin/features" }) + + shouldBeIn(UNAVAILABLE_FLAG, "off") + segment(UNAVAILABLE_FLAG, "admins_only").should( + "have.class", + "ant-segmented-item-disabled" + ) + segment(UNAVAILABLE_FLAG, "on").should( + "have.class", + "ant-segmented-item-disabled" + ) + cy.getCy(`feature-${UNAVAILABLE_FLAG}-note`).should("be.visible") + }) + + it("hides the page from an admin without the developer role", () => { + cy.serverCommand("createTestFeatureFlag", { key: FLAG }) + cy.login({ isAdmin: true, next: "admin/event/list" }) + + cy.getCy("admin-sider-events").should("be.visible") + cy.getCy("admin-sider-features").should("not.exist") + + cy.visit(Cypress.env("ROOT_URL") + "/admin/features") + cy.url().should("equal", Cypress.env("ROOT_URL") + "/") + cy.get(".ant-message").should("contain", "Pääsy kielletty") + cy.getCy("features-page").should("not.exist") + }) + + it("redirects a user who is not an admin", () => { + cy.login({ next: "admin/features" }) + + cy.url().should("equal", Cypress.env("ROOT_URL") + "/") + cy.get(".ant-message").should("contain", "Pääsy kielletty") + cy.getCy("features-page").should("not.exist") + }) +}) diff --git a/@app/e2e/cypress/e2e/create_event_registration.spec.ts b/@app/e2e/cypress/e2e/create_event_registration.spec.ts index acd49bf7e..aa1a26088 100644 --- a/@app/e2e/cypress/e2e/create_event_registration.spec.ts +++ b/@app/e2e/cypress/e2e/create_event_registration.spec.ts @@ -1,11 +1,15 @@ /// +// 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")) beforeEach(() => cy.serverCommand("clearTestOrganizations")) it("can register to an event", () => { + cy.serverCommand("setFeatureFlags", { calendar_invites: "on" }) // Setup cy.serverCommand("createTestEventData").as("createEventDataResult") @@ -30,6 +34,62 @@ 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:") + // Long lines are folded at 75 octets (RFC 5545), so a long + // event URL can span two lines + const unfolded = calendar.replace(/\r\n[ \t]/g, "") + expect(unfolded).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/csrf.spec.ts b/@app/e2e/cypress/e2e/csrf.spec.ts index 48a5634b8..ff32fc464 100644 --- a/@app/e2e/cypress/e2e/csrf.spec.ts +++ b/@app/e2e/cypress/e2e/csrf.spec.ts @@ -23,21 +23,18 @@ context("CSRF protection", () => { .then((cookie) => { cy.setCookie("csrfToken", cookie!.value + "a") }) + // The event page loads the event with a request to /graphql, which + // now carries a wrong csrfToken cy.getCy("homepage-signup-open-events") .getCy(`eventcard-eventpage-link-${event.slug}`) .click() - // Triggers a request to /graphql with a wrong csrfToken - cy.get("[data-cy=eventpage-quotas-link-0]", { timeout: 5000 }).should( - "not.be.disabled" - ) - cy.getCy("eventpage-quotas-link-0").click() - // Assertions cy.get(".ant-result").should("contain", "Väärä CSRF-tunnus") // Can recover from csrf error cy.getCy("error-csrf-refresh").click() + cy.getCy("eventpage-quotas-link-0").should("not.be.disabled").click() cy.contains("h3", "Ilmoittaudu tapahtumaan").should("be.visible") }) }) diff --git a/@app/e2e/cypress/e2e/event_form_templates.spec.ts b/@app/e2e/cypress/e2e/event_form_templates.spec.ts new file mode 100644 index 000000000..34fe3044d --- /dev/null +++ b/@app/e2e/cypress/e2e/event_form_templates.spec.ts @@ -0,0 +1,114 @@ +/// + +import dayjs from "dayjs" + +const format = "YYYY-MM-DD HH:mm:ss" +const openDropdown = ".ant-picker-dropdown:not(.ant-picker-dropdown-hidden)" + +// Clicks a day of the month shown in the open picker's first calendar +const clickDay = (day: number) => + cy + .get(`${openDropdown} .ant-picker-date-panel`) + .first() + .contains(".ant-picker-cell-in-view", new RegExp(`^${day}$`)) + .click() + +context("Event form templates, preview and day click", () => { + beforeEach(() => cy.serverCommand("clearTestUsers")) + beforeEach(() => cy.serverCommand("clearTestEventData")) + beforeEach(() => cy.serverCommand("clearTestOrganizations")) + // After clearTestEventData, which switches every flag off + beforeEach(() => + cy.serverCommand("setFeatureFlags", { + event_templates: "on", + form_preview: "on", + typed_time_input: "on", + }) + ) + + it("admin can fill the event form from templates and preview it", () => { + cy.serverCommand("createTestEventData", { + eventSignupUpcoming: true, + userIsAdmin: true, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then(() => { + cy.login({ + username: "testuser", + password: "DOESNT MATTER", + existingUser: true, + }) + cy.visit(Cypress.env("ROOT_URL") + "/admin/event/create") + cy.get(".ant-tabs-tab").as("tabs") + + // A day click fills in the whole range and closes the calendar + const month = dayjs() + cy.getCy("eventform-input-event-time").eq(0).click() + clickDay(20) + cy.get(openDropdown).should("not.exist") + cy.getCy("eventform-input-event-time") + .eq(0) + .should( + "have.value", + month.date(20).hour(12).startOf("hour").format(format) + ) + cy.getCy("eventform-input-event-time") + .eq(1) + .should("have.value", month.date(20).endOf("day").format(format)) + + cy.getCy("eventform-input-registration-time").eq(0).click() + clickDay(10) + cy.get(openDropdown).should("not.exist") + cy.getCy("eventform-input-registration-time") + .eq(0) + .should( + "have.value", + month.date(10).hour(12).startOf("hour").format(format) + ) + cy.getCy("eventform-input-registration-time") + .eq(1) + .should( + "have.value", + month.date(10).add(7, "day").endOf("day").format(format) + ) + + // Quota template and a ready-made quota + cy.get("@tabs").eq(1).click() + cy.getCy("eventform-quotas-template-yearGroups").closest("label").click() + cy.getCy("eventform-input-quotas-title-fi-0").should("have.value", "I") + cy.getCy("eventform-input-quotas-title-fi-4").should("have.value", "N") + cy.getCy("eventform-quotas-presets") + .find("input[type=checkbox]") + .first() + .check() + cy.getCy("eventform-input-quotas-title-fi-5").should( + "have.value", + "Avoin kiintiö" + ) + // Dropping the template keeps the hand-picked quota + cy.getCy("eventform-quotas-template-none").closest("label").click() + cy.get(".ant-modal-confirm-btns .ant-btn-primary").click() + cy.getCy("eventform-input-quotas-title-fi-0").should( + "have.value", + "Avoin kiintiö" + ) + cy.getCy("eventform-input-quotas-title-fi-1").should("not.exist") + + // Event template with question presets + cy.get("@tabs").eq(2).click() + cy.getCy("eventform-questions-template-sitsit").closest("label").click() + cy.getCy("eventform-input-questions-0-fi-label").should( + "have.value", + "Telegram" + ) + cy.getCy("eventform-select-questions-type-5").should("exist") + cy.getCy("eventform-select-questions-type-6").should("not.exist") + + // The preview shows the registration form with those questions + cy.get("@tabs").eq(3).click() + cy.getCy("eventregistrationform-button-submit").should("be.visible") + cy.get(".ant-tabs-tabpane-active").should("contain", "Telegram") + cy.url().should("equal", Cypress.env("ROOT_URL") + "/admin/event/create") + }) + }) +}) diff --git a/@app/e2e/cypress/e2e/payments_admin.spec.ts b/@app/e2e/cypress/e2e/payments_admin.spec.ts new file mode 100644 index 000000000..08905d5b8 --- /dev/null +++ b/@app/e2e/cypress/e2e/payments_admin.spec.ts @@ -0,0 +1,184 @@ +/// + +// Stripe payments from the organizer's side: quota prices in the event form, and the payment tools of the registrations tab. Stripe is +// never contacted; card payments are completed with the +// completeStripeCheckout server command (a signed fake webhook event). +// +// Needs a server running with both Stripe secrets (dummy values are fine), so +// that the `payments` flag is available; the tests switch it on. + +function loginAndOpenEvent(eventId: string) { + cy.login({ + username: "testuser", + password: "DOESNT MATTER", + existingUser: true, + }) + cy.visit(Cypress.env("ROOT_URL") + `/admin/event/update/${eventId}`) +} + +function openRegistrationsTab() { + cy.get("[role=tab]").contains("Ilmoittautuneet").click() +} + +context("Payments: admin", () => { + beforeEach(() => cy.serverCommand("clearTestUsers")) + beforeEach(() => cy.serverCommand("clearTestEventData")) + beforeEach(() => cy.serverCommand("clearTestOrganizations")) + beforeEach(() => cy.serverCommand("setFeatureFlags", { payments: "on" })) + + it("sets quota prices", () => { + // Setup: a free event with one registration + cy.serverCommand("createTestEventData", { userIsAdmin: true }).as( + "createEventDataResult" + ) + + cy.get("@createEventDataResult").then(({ event }: any) => { + loginAndOpenEvent(event.id) + + // Action: a price makes the event paid; there is no separate setting + cy.get(".ant-tabs-tab").eq(1).click() + cy.getCy("eventform-quotas-price-changed-warning").should("not.exist") + cy.getCy("eventform-input-quotas-price-0").clear().type("12") + cy.getCy("eventform-quotas-guild-receives-0").should( + "contain", + "≈ 11,82 €" + ) + // The quota already has a registration, which pays the new price + cy.getCy("eventform-quotas-price-changed-warning").should("exist") + + cy.get(".ant-tabs-tab").eq(0).click() + cy.getCy("eventform-button-submit").click() + cy.url().should("equal", Cypress.env("ROOT_URL") + "/admin/event/list") + + // Assertion: the event page shows the price + cy.visit(`${Cypress.env("ROOT_URL")}/event/${event.slug}`) + cy.getCy("eventpage-quotas-price-0").should("contain", "12,00 €") + + // The existing registration now has to pay + loginAndOpenEvent(event.id) + openRegistrationsTab() + cy.getCy("registrations-payment-summary-unpaid").should("contain", "1") + cy.getCy("registrations-payment-status-UNPAID").should("have.length", 1) + }) + }) + + it("marks a registration as paid and undoes it", () => { + // Setup + cy.serverCommand("createTestEventData", { + userIsAdmin: true, + priceCents: 1500, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then(({ event }: any) => { + loginAndOpenEvent(event.id) + openRegistrationsTab() + cy.getCy("registrations-payment-status-UNPAID").should("have.length", 1) + + // Action: mark as paid + cy.getCy("admin-table-more-button").click() + cy.getCy("admin-table-mark-paid").click() + + // Assertion + cy.getCy("registrations-payment-status-PAID_MANUALLY").should( + "have.length", + 1 + ) + cy.getCy("registrations-payment-summary-paid").should("contain", "1") + cy.getCy("registrations-payment-summary-unpaid").should("contain", "0") + cy.getCy("registrations-payment-summary-ticketsPaid").should( + "contain", + "15,00 €" + ) + + // Action: undo the manual payment + cy.getCy("admin-table-more-button").click() + cy.getCy("admin-table-undo-manual-payment").click() + cy.get(".ant-popover .ant-btn-primary").filter(":visible").click() + + // Assertion + cy.getCy("registrations-payment-status-UNPAID").should("have.length", 1) + cy.getCy("registrations-payment-summary-unpaid").should("contain", "1") + }) + }) + + it("sends a payment reminder to unpaid registrations", () => { + // Setup: three unpaid registrations and one paid by card + cy.serverCommand("createTestEventData", { + userIsAdmin: true, + priceCents: 1500, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then( + ({ event, quota, registrationSecret }: any) => { + cy.serverCommand("createRegistrations", { + eventId: event.id, + quotaId: quota.id, + count: 3, + }) + cy.serverCommand("completeStripeCheckout", { + updateToken: registrationSecret.update_token, + }) + + loginAndOpenEvent(event.id) + openRegistrationsTab() + cy.getCy("registrations-payment-status-PAID").should("have.length", 1) + cy.getCy("registrations-payment-status-UNPAID").should("have.length", 3) + cy.getCy("registrations-last-reminder").should("not.exist") + + // Action + cy.getCy("registrations-button-send-reminders") + .should("contain", "3") + .click() + cy.get(".ant-modal-content") + .filter(":visible") + .within(() => { + cy.get(".ant-btn-primary").should("contain", "3").click() + }) + + // Assertion + cy.get(".ant-modal-content").should("not.exist") + cy.getCy("registrations-last-reminder").should("exist") + } + ) + }) + + it("warns that nothing is refunded when deleting a registration paid by card", () => { + // Setup + cy.serverCommand("createTestEventData", { + userIsAdmin: true, + priceCents: 1500, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then( + ({ event, registrationSecret }: any) => { + cy.serverCommand("completeStripeCheckout", { + updateToken: registrationSecret.update_token, + }) + + loginAndOpenEvent(event.id) + openRegistrationsTab() + cy.getCy("registrations-payment-status-PAID").should("have.length", 1) + + // Action + cy.getCy("admin-table-delete-button").click() + + // Assertion: the dialog warns, and deleting is still allowed + cy.getCy("registrations-payment-summary-unlinked").should("not.exist") + cy.get(".ant-modal-content") + .filter(":visible") + .within(() => { + cy.getCy("admin-table-delete-no-refund-warning").should("exist") + cy.get(".ant-btn-dangerous").click() + }) + cy.getCy("registrations-payment-status-PAID").should("not.exist") + cy.getCy("registrations-payment-summary-paid").should("contain", "0") + // The card payment is kept, no longer linked to a registration, with + // a hint to refund it in Stripe + cy.getCy("registrations-payment-summary-unlinked").should( + "contain", + "1" + ) + } + ) + }) +}) diff --git a/@app/e2e/cypress/e2e/payments_register.spec.ts b/@app/e2e/cypress/e2e/payments_register.spec.ts new file mode 100644 index 000000000..c90860694 --- /dev/null +++ b/@app/e2e/cypress/e2e/payments_register.spec.ts @@ -0,0 +1,234 @@ +/// + +// Stripe payments from the participant's side. Payment opens when +// registration closes. Stripe itself is never contacted: +// createCheckoutSession is stubbed, the Checkout page is replaced by a +// redirect straight back to Ilmo, and the payment is completed with the +// completeStripeCheckout server command, which posts a signed +// checkout.session.completed event to the real webhook route. +// +// Needs a server running with both Stripe secrets (dummy values are fine), so +// that the `payments` flag is available; the tests switch it on. + +const STRIPE_CHECKOUT_URL = "https://checkout.stripe.com/c/pay/cs_test_cypress" + +function fillRegistrationForm() { + cy.getCy("eventregistrationform-input-firstname") + .wait(0) + .focus() + .clear() + .type("Etunimi") + cy.getCy("eventregistrationform-input-lastname").type("Sukunimi") + cy.getCy("eventregistrationform-input-email").type( + "etunimi.sukunimi@prodeko.org" + ) +} + +context("Payments: registration", () => { + beforeEach(() => cy.serverCommand("clearTestUsers")) + beforeEach(() => cy.serverCommand("clearTestEventData")) + beforeEach(() => cy.serverCommand("clearTestOrganizations")) + beforeEach(() => cy.serverCommand("setFeatureFlags", { payments: "on" })) + + it("registers into a paid quota without paying yet", () => { + // Setup + cy.serverCommand("createTestEventData", { + priceCents: 1500, + }).as("createEventDataResult") + let checkoutRequested = false + cy.intercept("POST", "/graphql", (req) => { + if (req.body?.operationName === "CreateCheckoutSession") { + checkoutRequested = true + } + }) + + cy.get("@createEventDataResult").then(({ event, quota }: any) => { + // Event page shows the price + cy.visit(`${Cypress.env("ROOT_URL")}/event/${event.slug}`) + cy.getCy("eventpage-quotas-price-0").should("contain", "15,00 €") + + // Action + cy.visit( + Cypress.env("ROOT_URL") + `/event/${event.slug}/register/${quota.id}` + ) + // One notice: the price and that the link comes when registration + // closes + cy.getCy("eventregistrationform-payment-summary") + .should("contain", "15,00 €") + .and("contain", "0,25 €") + fillRegistrationForm() + cy.getCy("eventregistrationform-button-submit") + .should("not.contain", "€") + .click() + + // Assertion: the registration is saved and nothing is paid yet + cy.url().should("equal", Cypress.env("ROOT_URL") + `/event/${event.slug}`) + cy.getCy("eventpage-signups-quota-0-table").should("contain", "Etunimi") + cy.then(() => expect(checkoutRequested).to.equal(false)) + }) + }) + + it("opens /pay when registration closes and completes the payment", () => { + // Setup: an unpaid registration while registration is open + cy.serverCommand("createTestEventData", { + priceCents: 1500, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then( + ({ event, registrationSecret }: any) => { + const updateToken = registrationSecret.update_token + cy.intercept("POST", "/graphql", (req) => { + if (req.body?.operationName === "CreateCheckoutSession") { + req.alias = "createCheckoutSession" + req.reply({ + data: { + createCheckoutSession: { + __typename: "CreateCheckoutSessionPayload", + url: STRIPE_CHECKOUT_URL, + }, + }, + }) + } + }) + // Stand-in for Stripe's Checkout page: send the browser back to the + // success URL like Stripe does once the card has been charged + cy.intercept("GET", `${STRIPE_CHECKOUT_URL}*`, (req) => { + req.reply({ + statusCode: 303, + headers: { + location: `${Cypress.env( + "ROOT_URL" + )}/pay/${updateToken}?status=success`, + }, + }) + }).as("stripeCheckout") + + // While registration is open, payment has not opened yet + cy.visit(`${Cypress.env("ROOT_URL")}/pay/${updateToken}`) + cy.getCy("paypage-card").should("have.attr", "data-state", "opensLater") + cy.getCy("paypage-button-pay").should("not.exist") + + // Action: registration closes, then the participant pays + cy.serverCommand("closeEventRegistration", { eventId: event.id }) + cy.reload() + cy.getCy("paypage-card").should("have.attr", "data-state", "unpaid") + cy.getCy("paypage-button-pay").should("contain", "15,25 €").click() + + // Assertion: Checkout was requested and the browser came back to /pay + cy.wait("@createCheckoutSession") + cy.wait("@stripeCheckout") + cy.location("search").should("contain", "status=success") + cy.getCy("paypage-card").should("have.attr", "data-state", "confirming") + cy.getCy("paypage-confirming-notice").should("exist") + + // The webhook marks the payment paid and the polling page notices + cy.serverCommand("completeStripeCheckout", { updateToken }) + cy.getCy("paypage-card", { timeout: 20000 }).should( + "have.attr", + "data-state", + "paid" + ) + cy.getCy("paypage-confirming-notice").should("not.exist") + cy.getCy("paypage-button-pay").should("not.exist") + } + ) + }) + + it("shows an error on /pay if Checkout can't be started", () => { + // Setup: an unpaid registration after registration has closed + cy.serverCommand("createTestEventData", { + priceCents: 1500, + }).as("createEventDataResult") + cy.intercept("POST", "/graphql", (req) => { + if (req.body?.operationName === "CreateCheckoutSession") { + req.alias = "createCheckoutSession" + req.reply({ + data: { createCheckoutSession: null }, + errors: [ + { message: "Stripe is down", path: ["createCheckoutSession"] }, + ], + }) + } + }) + + cy.get("@createEventDataResult").then( + ({ event, registrationSecret }: any) => { + const updateToken = registrationSecret.update_token + cy.serverCommand("closeEventRegistration", { eventId: event.id }) + + // Action + cy.visit(`${Cypress.env("ROOT_URL")}/pay/${updateToken}`) + cy.getCy("paypage-button-pay").click() + + // Assertion: the page stays and says that it failed + cy.wait("@createCheckoutSession") + cy.getCy("paypage-checkout-failed").should("exist") + cy.getCy("paypage-card").should("have.attr", "data-state", "unpaid") + } + ) + }) + + it("/pay polls after returning from Checkout until the payment is paid", () => { + // Setup: an unpaid registration after registration has closed + cy.serverCommand("createTestEventData", { + priceCents: 1000, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then( + ({ event, registrationSecret }: any) => { + const updateToken = registrationSecret.update_token + cy.serverCommand("closeEventRegistration", { eventId: event.id }) + cy.visit(`${Cypress.env("ROOT_URL")}/pay/${updateToken}`) + cy.getCy("paypage-card").should("have.attr", "data-state", "unpaid") + cy.getCy("paypage-button-pay").should("contain", "10,25 €") + + // Action: come back from Checkout before the webhook has arrived + cy.visit(`${Cypress.env("ROOT_URL")}/pay/${updateToken}?status=success`) + cy.getCy("paypage-card").should("have.attr", "data-state", "confirming") + cy.getCy("paypage-confirming-notice").should("exist") + cy.serverCommand("completeStripeCheckout", { updateToken }) + + // Assertion + cy.getCy("paypage-card", { timeout: 20000 }).should( + "have.attr", + "data-state", + "paid" + ) + cy.getCy("paypage-status-tag").should("exist") + cy.getCy("paypage-button-pay").should("not.exist") + } + ) + }) + + it("warns that nothing is refunded when deleting a paid registration", () => { + // Setup: a registration paid by card while registration is open, as + // after registration has been reopened + cy.serverCommand("createTestEventData", { + priceCents: 1500, + }).as("createEventDataResult") + + cy.get("@createEventDataResult").then( + ({ event, registrationSecret }: any) => { + const updateToken = registrationSecret.update_token + cy.serverCommand("completeStripeCheckout", { updateToken }) + + // Action + cy.visit( + `${Cypress.env("ROOT_URL")}/update-registration/${updateToken}` + ) + cy.getCy("updateregistration-paid-banner").should("exist") + cy.getCy("eventregistrationform-button-delete-registration").click() + + // Assertion: the confirmation warns, and deleting is still allowed + cy.getCy("eventregistrationform-delete-no-refund-warning").should( + "be.visible" + ) + cy.get(".ant-popconfirm-buttons button").contains("Kyllä").click() + cy.url().should( + "equal", + Cypress.env("ROOT_URL") + `/event/${event.slug}` + ) + } + ) + }) +}) diff --git a/@app/e2e/cypress/e2e/reminders.spec.ts b/@app/e2e/cypress/e2e/reminders.spec.ts new file mode 100644 index 000000000..85aec9e9c --- /dev/null +++ b/@app/e2e/cypress/e2e/reminders.spec.ts @@ -0,0 +1,96 @@ +/// + +context("Registration reminder preferences", () => { + beforeEach(() => cy.serverCommand("clearTestUsers")) + beforeEach(() => cy.serverCommand("clearTestEventData")) + beforeEach(() => cy.serverCommand("clearTestOrganizations")) + beforeEach(() => + cy.serverCommand("setFeatureFlags", { registration_reminders: "on" }) + ) + + 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") + + // With reminders off, an existing reminder can still be removed + cy.serverCommand("setFeatureFlags", { registration_reminders: "off" }) + cy.reload() + cy.getCy("reminders-off-notice").should("exist") + cy.getCy("reminder-preferences-edit").should("not.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/e2e/cypress/e2e/update_event.spec.ts b/@app/e2e/cypress/e2e/update_event.spec.ts index 4ff31e5de..00d4ab330 100644 --- a/@app/e2e/cypress/e2e/update_event.spec.ts +++ b/@app/e2e/cypress/e2e/update_event.spec.ts @@ -7,6 +7,7 @@ context("Update event", () => { it("admin can update an existing event", () => { // Setup + cy.serverCommand("setFeatureFlags", { ribbon_text: "on" }) cy.serverCommand("createTestEventData", { userIsAdmin: true }).as( "createEventDataResult" ) @@ -97,6 +98,7 @@ context("Update event", () => { .clear() .type("Päivitetty testitapahtuma") cy.getCy("eventform-switch-highlight").click() + cy.getCy("eventform-input-highlight-text-fi").type("Pian täynnä") cy.getCy("eventform-header-image-upload").attachFile("kitten.jpg") cy.get(".img-crop-modal button").contains("OK").click() @@ -113,6 +115,7 @@ context("Update event", () => { "contain", "Päivitetty testitapahtuma" ) + cy.getCy("homepage-signup-open-events").should("contain", "Pian täynnä") } ) }) diff --git a/@app/e2e/cypress/support/commands.ts b/@app/e2e/cypress/support/commands.ts index d2eaaed8f..82b70186d 100644 --- a/@app/e2e/cypress/support/commands.ts +++ b/@app/e2e/cypress/support/commands.ts @@ -31,9 +31,13 @@ type User = { username: string name: string is_admin: boolean + is_developer: boolean is_verified: boolean } +/** States by flag key; the keys are those of @app/lib/src/featureFlags.ts. */ +type FeatureFlagStates = Record + function getCy(cyName: string): Chainable> { return cy.get(`[data-cy=${cyName}]`) } @@ -53,12 +57,49 @@ function serverCommand(command: "clearTestOrganizations"): Chainable<{ }> /** - * Deletes all event data generated for e2e tests. + * Deletes all event data generated for e2e tests and switches every feature + * flag off. */ function serverCommand(command: "clearTestEventData"): Chainable<{ success: true }> +/** + * Sets feature flag states, e.g. `{ payments: "on" }`. Every key must have a + * row in app_public.feature_flags. The server's flag cache is cleared, so the + * change applies to the next request. + */ +function serverCommand( + command: "setFeatureFlags", + payload: FeatureFlagStates +): Chainable<{ + success: true +}> + +/** + * Creates or resets a flag row that no feature uses, for tests of the + * Features page, and clears its change history. The key must start with + * `test_e2e_`. Defaults: state `off`, available. + */ +function serverCommand( + command: "createTestFeatureFlag", + payload: { + key: `test_e2e_${string}` + state?: "off" | "admins_only" | "on" + available?: boolean + description?: string + } +): Chainable<{ + success: true +}> + +/** + * Deletes every flag row created by createTestFeatureFlag, with its history. + */ +function serverCommand(command: "deleteTestFeatureFlags"): Chainable<{ + success: true +}> + /** * Generate event data for e2e tests. */ @@ -90,6 +131,8 @@ function serverCommand( * - verified: false * - name: `${username}` * - password: `TestUserPassword` + * - isAdmin: false + * - isDeveloper: false (feature flag management; needs isAdmin as well) * - next: `/` */ function serverCommand( @@ -100,6 +143,8 @@ function serverCommand( verified?: boolean name?: string password?: string + isAdmin?: boolean + isDeveloper?: boolean next?: string } ): Chainable<{ @@ -120,6 +165,29 @@ function serverCommand( verification_token: string | null }> +/** + * Ends the registration of the event a moment ago, as if it had closed. + */ +function serverCommand( + command: "closeEventRegistration", + payload: { eventId: string } +): Chainable<{ + success: true +}> + +/** + * Pays for the registration behind `updateToken` as if Stripe Checkout had + * completed: posts a signed `checkout.session.completed` event to the + * webhook. Requires Stripe to be configured. + */ +function serverCommand( + command: "completeStripeCheckout", + payload: { updateToken: string } +): Chainable<{ + paymentId: string + sessionId: string +}> + // The actual implementation of the 'serverCommand' function. function serverCommand(command: string, payload?: any): any { const url = `${Cypress.env( @@ -137,6 +205,8 @@ function login(payload?: { name?: string verified?: boolean isAdmin?: boolean + /** Feature flag management; needs isAdmin as well. */ + isDeveloper?: boolean password?: string orgs?: [[string, string] | [string, string, boolean]] existingUser?: true diff --git a/@app/e2e/keycloak/realm-ci.json b/@app/e2e/keycloak/realm-ci.json index 8f55df774..4fd0b6470 100644 --- a/@app/e2e/keycloak/realm-ci.json +++ b/@app/e2e/keycloak/realm-ci.json @@ -17,6 +17,10 @@ { "name": "ilmo-admin", "description": "Maps to app_public.users.is_admin; the name is ILMO_ADMIN_ROLE in @app/server/src/utils/keycloak.ts" + }, + { + "name": "ilmo-developer", + "description": "Maps to app_public.users.is_developer (feature flag management, together with ilmo-admin); the name is ILMO_DEVELOPER_ROLE in @app/server/src/utils/keycloak.ts" } ] }, @@ -109,6 +113,24 @@ "temporary": false } ] + }, + { + "username": "ci-developer", + "enabled": true, + "emailVerified": true, + "email": "ci-developer@example.com", + "firstName": "CI", + "lastName": "Developer", + "attributes": { "locale": ["en"] }, + "requiredActions": [], + "realmRoles": ["ilmo-admin", "ilmo-developer"], + "credentials": [ + { + "type": "password", + "value": "ci-developer-password", + "temporary": false + } + ] } ] } diff --git a/@app/graphql/.persisted_operations/049ad46a1304886067ad2325866baed2b66979a18cc09333740a2c49ac1d7744.graphql b/@app/graphql/.persisted_operations/049ad46a1304886067ad2325866baed2b66979a18cc09333740a2c49ac1d7744.graphql new file mode 100644 index 000000000..2f3cb0d79 --- /dev/null +++ b/@app/graphql/.persisted_operations/049ad46a1304886067ad2325866baed2b66979a18cc09333740a2c49ac1d7744.graphql @@ -0,0 +1,33 @@ +fragment AdminFeatures_FeatureFlag on FeatureFlag { + key + state + available + description + updatedAt + retiredAt + __typename +} +fragment AdminFeatures_FeatureFlagEvent on FeatureFlagEventsRecord { + id + key + oldState + newState + actorId + actorName + actorUsername + createdAt + __typename +} +query AdminFeatures { + featureFlags(orderBy: KEY_ASC) { + nodes { + ...AdminFeatures_FeatureFlag + __typename + } + __typename + } + featureFlagEventsList { + ...AdminFeatures_FeatureFlagEvent + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/994c6d2a2d085b6452233787ccd1502e270b193029b1793369e0d7503ef999b5.graphql b/@app/graphql/.persisted_operations/059752747adcbd9bc1dd51f36f20f6cce2ce65b5c66c57a66905471744a48e6f.graphql similarity index 95% rename from @app/graphql/.persisted_operations/994c6d2a2d085b6452233787ccd1502e270b193029b1793369e0d7503ef999b5.graphql rename to @app/graphql/.persisted_operations/059752747adcbd9bc1dd51f36f20f6cce2ce65b5c66c57a66905471744a48e6f.graphql index 57d6ae688..62b3dd94f 100644 --- a/@app/graphql/.persisted_operations/994c6d2a2d085b6452233787ccd1502e270b193029b1793369e0d7503ef999b5.graphql +++ b/@app/graphql/.persisted_operations/059752747adcbd9bc1dd51f36f20f6cce2ce65b5c66c57a66905471744a48e6f.graphql @@ -21,6 +21,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -29,6 +31,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { diff --git a/@app/graphql/.persisted_operations/a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739.graphql b/@app/graphql/.persisted_operations/11644b9a58d11149330a34204af8f15f758efccc09bcb64b231648f72877a357.graphql similarity index 97% rename from @app/graphql/.persisted_operations/a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739.graphql rename to @app/graphql/.persisted_operations/11644b9a58d11149330a34204af8f15f758efccc09bcb64b231648f72877a357.graphql index 12b2cfce9..6f8fadf1a 100644 --- a/@app/graphql/.persisted_operations/a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739.graphql +++ b/@app/graphql/.persisted_operations/11644b9a58d11149330a34204af8f15f758efccc09bcb64b231648f72877a357.graphql @@ -15,6 +15,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } mutation UpdateEventRegistration($input: UpdateRegistrationInput!) { 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/77885919f782dbb117e2759c4918f2445a633ed0a98d08fd5d1ab699ebce9391.graphql b/@app/graphql/.persisted_operations/1e004ee4f10fea6972a6c364a9d4955664248c4745f0948543200c9b8e47fdda.graphql similarity index 95% rename from @app/graphql/.persisted_operations/77885919f782dbb117e2759c4918f2445a633ed0a98d08fd5d1ab699ebce9391.graphql rename to @app/graphql/.persisted_operations/1e004ee4f10fea6972a6c364a9d4955664248c4745f0948543200c9b8e47fdda.graphql index 888aba7cc..552ca3438 100644 --- a/@app/graphql/.persisted_operations/77885919f782dbb117e2759c4918f2445a633ed0a98d08fd5d1ab699ebce9391.graphql +++ b/@app/graphql/.persisted_operations/1e004ee4f10fea6972a6c364a9d4955664248c4745f0948543200c9b8e47fdda.graphql @@ -23,6 +23,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -31,6 +33,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { diff --git a/@app/graphql/.persisted_operations/c80a1b7e4a79510cd8e544910e72dec734223574011e0a40bb00c78de8de310c.graphql b/@app/graphql/.persisted_operations/20fe542e08269ad0e1479f307ce17f1b04c59e48f2dd73139d36dbdeaef3e99a.graphql similarity index 88% rename from @app/graphql/.persisted_operations/c80a1b7e4a79510cd8e544910e72dec734223574011e0a40bb00c78de8de310c.graphql rename to @app/graphql/.persisted_operations/20fe542e08269ad0e1479f307ce17f1b04c59e48f2dd73139d36dbdeaef3e99a.graphql index 4f5141897..998082d3e 100644 --- a/@app/graphql/.persisted_operations/c80a1b7e4a79510cd8e544910e72dec734223574011e0a40bb00c78de8de310c.graphql +++ b/@app/graphql/.persisted_operations/20fe542e08269ad0e1479f307ce17f1b04c59e48f2dd73139d36dbdeaef3e99a.graphql @@ -1,5 +1,15 @@ fragment CreateEventRegistrationPage_Query on Query { ...SharedLayout_Query + currentUser { + id + firstName + lastName + registrationProfile { + ...RegistrationProfile + __typename + } + __typename + } eventBySlug(slug: $slug) { ...EventPage_Event __typename @@ -24,6 +34,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -32,6 +44,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { @@ -72,6 +85,12 @@ fragment SharedLayout_Organization on Organization { slug __typename } +fragment RegistrationProfile on RegistrationProfile { + userId + telegram + dietaryRestrictions + __typename +} fragment EventPage_Event on Event { ...EventFields category { @@ -116,6 +135,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -152,6 +172,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } fragment EventPage_Registration on Registration { @@ -173,6 +194,7 @@ fragment EventPage_Question on EventQuestion { label isRequired data + prefill __typename } query CreateEventRegistrationPage($slug: String!, $quotaId: UUID!) { diff --git a/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql b/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql new file mode 100644 index 000000000..b01e57dce --- /dev/null +++ b/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql @@ -0,0 +1,59 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + __typename + } + category { + name + __typename + } + __typename +} +query McpEvent($slug: String!) { + currentUser { + name + primaryEmail + __typename + } + eventBySlug(slug: $slug) { + ...McpEventSummary + description + isDraft + openQuotaSize + quotas(orderBy: POSITION_ASC) { + nodes { + id + title + size + registrations { + totalCount + __typename + } + __typename + } + __typename + } + eventQuestions(orderBy: POSITION_ASC) { + nodes { + id + type + label + isRequired + data + __typename + } + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/e97c6726ce1d78c512935a15f46e8315e8ab2e50b2776d4fa1c92a5e8a54c566.graphql b/@app/graphql/.persisted_operations/282c98619013fc7f0e852cec433d21a04a36d1d07350d011424ac32a60d772c7.graphql similarity index 97% rename from @app/graphql/.persisted_operations/e97c6726ce1d78c512935a15f46e8315e8ab2e50b2776d4fa1c92a5e8a54c566.graphql rename to @app/graphql/.persisted_operations/282c98619013fc7f0e852cec433d21a04a36d1d07350d011424ac32a60d772c7.graphql index 8e47db289..d5f3f4ca6 100644 --- a/@app/graphql/.persisted_operations/e97c6726ce1d78c512935a15f46e8315e8ab2e50b2776d4fa1c92a5e8a54c566.graphql +++ b/@app/graphql/.persisted_operations/282c98619013fc7f0e852cec433d21a04a36d1d07350d011424ac32a60d772c7.graphql @@ -15,6 +15,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } mutation CreateEventRegistration($input: CreateRegistrationInput!) { diff --git a/@app/graphql/.persisted_operations/37b4cd795c818a76ab63d56f5ba1009e6663d18bef8c95110a17f272b0bb94d4.graphql b/@app/graphql/.persisted_operations/37b4cd795c818a76ab63d56f5ba1009e6663d18bef8c95110a17f272b0bb94d4.graphql new file mode 100644 index 000000000..f438d1efa --- /dev/null +++ b/@app/graphql/.persisted_operations/37b4cd795c818a76ab63d56f5ba1009e6663d18bef8c95110a17f272b0bb94d4.graphql @@ -0,0 +1,32 @@ +fragment EventPaymentSummary_Event on Event { + id + lastPaymentReminderSentAt + quotas { + nodes { + id + priceCents + __typename + } + __typename + } + registrations { + totalCount + __typename + } + paymentSummary { + paidCount + unpaidCount + dueCount + ticketsPaidCents + guildReceivesCents + unlinkedCardPaymentCount + __typename + } + __typename +} +query EventPaymentSummary($id: UUID!) { + event(id: $id) { + ...EventPaymentSummary_Event + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/063ffe79e5b7bcf7d58cc1b0742a2526dfd993ebd5550a37cc5d326b8fd35d00.graphql b/@app/graphql/.persisted_operations/3b54a951d1aa12e533adfdeea2ceca0ab7c74cc25b3560018bce199d4ee5b170.graphql similarity index 96% rename from @app/graphql/.persisted_operations/063ffe79e5b7bcf7d58cc1b0742a2526dfd993ebd5550a37cc5d326b8fd35d00.graphql rename to @app/graphql/.persisted_operations/3b54a951d1aa12e533adfdeea2ceca0ab7c74cc25b3560018bce199d4ee5b170.graphql index ecf6dd9f3..d7d7068b1 100644 --- a/@app/graphql/.persisted_operations/063ffe79e5b7bcf7d58cc1b0742a2526dfd993ebd5550a37cc5d326b8fd35d00.graphql +++ b/@app/graphql/.persisted_operations/3b54a951d1aa12e533adfdeea2ceca0ab7c74cc25b3560018bce199d4ee5b170.graphql @@ -9,6 +9,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize 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/40299daf2530066a9fdf98480092ba41a41f6d727ed35ca47e5d8a6c0002ce7e.graphql b/@app/graphql/.persisted_operations/40299daf2530066a9fdf98480092ba41a41f6d727ed35ca47e5d8a6c0002ce7e.graphql new file mode 100644 index 000000000..8bb685bd4 --- /dev/null +++ b/@app/graphql/.persisted_operations/40299daf2530066a9fdf98480092ba41a41f6d727ed35ca47e5d8a6c0002ce7e.graphql @@ -0,0 +1,16 @@ +fragment RegistrationProfile on RegistrationProfile { + userId + telegram + dietaryRestrictions + __typename +} +query RegistrationProfile { + currentUser { + id + registrationProfile { + ...RegistrationProfile + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/eb985e5bfabc266d0fc5637eda513cac8a293bc851b29e863dbf304c4932f7f1.graphql b/@app/graphql/.persisted_operations/4279223c3efdc362aae98e81e1cda66c7a006cafd8ca8245b4216028c12901ca.graphql similarity index 93% rename from @app/graphql/.persisted_operations/eb985e5bfabc266d0fc5637eda513cac8a293bc851b29e863dbf304c4932f7f1.graphql rename to @app/graphql/.persisted_operations/4279223c3efdc362aae98e81e1cda66c7a006cafd8ca8245b4216028c12901ca.graphql index d1a3ec1b5..2022dae73 100644 --- a/@app/graphql/.persisted_operations/eb985e5bfabc266d0fc5637eda513cac8a293bc851b29e863dbf304c4932f7f1.graphql +++ b/@app/graphql/.persisted_operations/4279223c3efdc362aae98e81e1cda66c7a006cafd8ca8245b4216028c12901ca.graphql @@ -12,6 +12,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -20,6 +22,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { diff --git a/@app/graphql/.persisted_operations/567efbd2a44d533f2c0d9c75f66ab1be7bf6c166e04ad86492b75c824ee975db.graphql b/@app/graphql/.persisted_operations/567efbd2a44d533f2c0d9c75f66ab1be7bf6c166e04ad86492b75c824ee975db.graphql new file mode 100644 index 000000000..c75dc6e19 --- /dev/null +++ b/@app/graphql/.persisted_operations/567efbd2a44d533f2c0d9c75f66ab1be7bf6c166e04ad86492b75c824ee975db.graphql @@ -0,0 +1,6 @@ +mutation AdminUnmarkRegistrationPaid($input: AdminUnmarkRegistrationPaidInput!) { + adminUnmarkRegistrationPaid(input: $input) { + boolean + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/7ed3c3bc6904aa0bbc8ee96e5483d4ca9367eaa40d685d9435751b40d272b6eb.graphql b/@app/graphql/.persisted_operations/7ed3c3bc6904aa0bbc8ee96e5483d4ca9367eaa40d685d9435751b40d272b6eb.graphql new file mode 100644 index 000000000..6db2dd0f0 --- /dev/null +++ b/@app/graphql/.persisted_operations/7ed3c3bc6904aa0bbc8ee96e5483d4ca9367eaa40d685d9435751b40d272b6eb.graphql @@ -0,0 +1,18 @@ +fragment AdminFeatures_FeatureFlag on FeatureFlag { + key + state + available + description + updatedAt + retiredAt + __typename +} +mutation SetFeatureFlag($input: SetFeatureFlagInput!) { + setFeatureFlag(input: $input) { + featureFlag { + ...AdminFeatures_FeatureFlag + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/84dab768dd94228356723651b754e840eef05d581c712a4a00802656158d9db1.graphql b/@app/graphql/.persisted_operations/84dab768dd94228356723651b754e840eef05d581c712a4a00802656158d9db1.graphql new file mode 100644 index 000000000..4741b3364 --- /dev/null +++ b/@app/graphql/.persisted_operations/84dab768dd94228356723651b754e840eef05d581c712a4a00802656158d9db1.graphql @@ -0,0 +1,104 @@ +fragment SharedLayout_Query on Query { + currentUser { + ...SharedLayout_User + __typename + } + organizations(orderBy: SLUG_ASC) { + nodes { + ...SharedLayout_Organization + __typename + } + __typename + } + ssoLoginEnabled + supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList + __typename +} +fragment SharedLayout_User on User { + id + name + username + avatarUrl + isAdmin + isDeveloper + 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/894559d77667dd2e7ea2fc0efaf41669235fe335936e8833155115ccadf61330.graphql b/@app/graphql/.persisted_operations/894559d77667dd2e7ea2fc0efaf41669235fe335936e8833155115ccadf61330.graphql new file mode 100644 index 000000000..d8e9f0e8b --- /dev/null +++ b/@app/graphql/.persisted_operations/894559d77667dd2e7ea2fc0efaf41669235fe335936e8833155115ccadf61330.graphql @@ -0,0 +1,6 @@ +mutation AdminSendPaymentReminders($input: AdminSendPaymentRemindersInput!) { + adminSendPaymentReminders(input: $input) { + integer + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/7e487496b03e301f627d86bce4edd2273740b18548ad91c12bd6575aaff34ad7.graphql b/@app/graphql/.persisted_operations/8b41853c48d6d26068e2f31be3228ac4de7cba203d5bc2cda3f18aa69d4b079c.graphql similarity index 95% rename from @app/graphql/.persisted_operations/7e487496b03e301f627d86bce4edd2273740b18548ad91c12bd6575aaff34ad7.graphql rename to @app/graphql/.persisted_operations/8b41853c48d6d26068e2f31be3228ac4de7cba203d5bc2cda3f18aa69d4b079c.graphql index 273307430..b4771a08f 100644 --- a/@app/graphql/.persisted_operations/7e487496b03e301f627d86bce4edd2273740b18548ad91c12bd6575aaff34ad7.graphql +++ b/@app/graphql/.persisted_operations/8b41853c48d6d26068e2f31be3228ac4de7cba203d5bc2cda3f18aa69d4b079c.graphql @@ -27,6 +27,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -35,6 +37,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { @@ -88,6 +91,7 @@ fragment UpdateEventPage_Event on Event { quotas(orderBy: POSITION_ASC) { nodes { ...EventPage_Quota + priceCents registrations { totalCount __typename @@ -116,6 +120,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -152,6 +157,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } fragment EventPage_Question on EventQuestion { @@ -161,6 +167,7 @@ fragment EventPage_Question on EventQuestion { label isRequired data + prefill __typename } query UpdateEventPage($id: UUID!) { diff --git a/@app/graphql/.persisted_operations/2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9.graphql b/@app/graphql/.persisted_operations/92fa1d7b23f5698f63d7fd93956a8531b95100abe24cb95ec3280c132e838d55.graphql similarity index 84% rename from @app/graphql/.persisted_operations/2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9.graphql rename to @app/graphql/.persisted_operations/92fa1d7b23f5698f63d7fd93956a8531b95100abe24cb95ec3280c132e838d55.graphql index e2e80db2e..9e72b53b6 100644 --- a/@app/graphql/.persisted_operations/2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9.graphql +++ b/@app/graphql/.persisted_operations/92fa1d7b23f5698f63d7fd93956a8531b95100abe24cb95ec3280c132e838d55.graphql @@ -12,6 +12,10 @@ fragment UpdateEventRegistrationPage_Query on Query { } __typename } + paymentByUpdateToken(updateToken: $updateToken) { + ...PayPage_RegistrationPayment + __typename + } __typename } fragment SharedLayout_Query on Query { @@ -28,6 +32,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -36,6 +42,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { @@ -88,6 +95,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } fragment EventPage_Event on Event { @@ -134,6 +142,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -184,6 +193,29 @@ fragment EventPage_Question on EventQuestion { label isRequired data + prefill + __typename +} +fragment PayPage_RegistrationPayment on RegistrationPayment { + eventId + eventSlug + eventName + eventStartTime + eventEndTime + registrationEndTime + quotaTitle + firstName + lastName + queueStatus + queuePosition + status + priceCents + serviceFeeCents + totalCents + paidManually + paidTotalCents + paidAt + blockedReason __typename } query UpdateEventRegistrationPage($updateToken: String!) { diff --git a/@app/graphql/.persisted_operations/98965cb2bb84e54d0e0d6ba48046a829fc42776ce6b7b9eeae134dcae7036044.graphql b/@app/graphql/.persisted_operations/936b95b84ab4570162a3124685b9aa033c72a848ec5a288ff1cec143bf134a57.graphql similarity index 96% rename from @app/graphql/.persisted_operations/98965cb2bb84e54d0e0d6ba48046a829fc42776ce6b7b9eeae134dcae7036044.graphql rename to @app/graphql/.persisted_operations/936b95b84ab4570162a3124685b9aa033c72a848ec5a288ff1cec143bf134a57.graphql index 80e01270c..b96769ca3 100644 --- a/@app/graphql/.persisted_operations/98965cb2bb84e54d0e0d6ba48046a829fc42776ce6b7b9eeae134dcae7036044.graphql +++ b/@app/graphql/.persisted_operations/936b95b84ab4570162a3124685b9aa033c72a848ec5a288ff1cec143bf134a57.graphql @@ -9,6 +9,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize diff --git a/@app/graphql/.persisted_operations/e75fddfae08b7bdc7571c0cd3426cdda51dc0b336d6a428c214da7d7f2752708.graphql b/@app/graphql/.persisted_operations/946019cf0fe0197d6083b7c83faf8383b2327468ab7b6ec1eeff53c74b921d7e.graphql similarity index 96% rename from @app/graphql/.persisted_operations/e75fddfae08b7bdc7571c0cd3426cdda51dc0b336d6a428c214da7d7f2752708.graphql rename to @app/graphql/.persisted_operations/946019cf0fe0197d6083b7c83faf8383b2327468ab7b6ec1eeff53c74b921d7e.graphql index fe5b0684b..80e8cd82f 100644 --- a/@app/graphql/.persisted_operations/e75fddfae08b7bdc7571c0cd3426cdda51dc0b336d6a428c214da7d7f2752708.graphql +++ b/@app/graphql/.persisted_operations/946019cf0fe0197d6083b7c83faf8383b2327468ab7b6ec1eeff53c74b921d7e.graphql @@ -20,6 +20,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -28,6 +30,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { 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/368543083e66d7a6ae5e78654849ec0d94283752aece92394005e027bf3e429c.graphql b/@app/graphql/.persisted_operations/b78ccb2c8f90523ea273e051c83894e18168066d4c117484d1e585169d7e0986.graphql similarity index 98% rename from @app/graphql/.persisted_operations/368543083e66d7a6ae5e78654849ec0d94283752aece92394005e027bf3e429c.graphql rename to @app/graphql/.persisted_operations/b78ccb2c8f90523ea273e051c83894e18168066d4c117484d1e585169d7e0986.graphql index a29e5e924..e010b36aa 100644 --- a/@app/graphql/.persisted_operations/368543083e66d7a6ae5e78654849ec0d94283752aece92394005e027bf3e429c.graphql +++ b/@app/graphql/.persisted_operations/b78ccb2c8f90523ea273e051c83894e18168066d4c117484d1e585169d7e0986.graphql @@ -52,6 +52,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -88,6 +89,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } query HomePageEvents($offset: Int, $first: Int, $language: String) { diff --git a/@app/graphql/.persisted_operations/c22efb8e3e3226153a7be53c61321e72c94f3cbc667ca769cc056b4fee27678c.graphql b/@app/graphql/.persisted_operations/bf749c8be1be824ca2fc06b6a275550762c94543bbe165775804d7ab709dce20.graphql similarity index 97% rename from @app/graphql/.persisted_operations/c22efb8e3e3226153a7be53c61321e72c94f3cbc667ca769cc056b4fee27678c.graphql rename to @app/graphql/.persisted_operations/bf749c8be1be824ca2fc06b6a275550762c94543bbe165775804d7ab709dce20.graphql index 2e1a03447..2d9e6b3e8 100644 --- a/@app/graphql/.persisted_operations/c22efb8e3e3226153a7be53c61321e72c94f3cbc667ca769cc056b4fee27678c.graphql +++ b/@app/graphql/.persisted_operations/bf749c8be1be824ca2fc06b6a275550762c94543bbe165775804d7ab709dce20.graphql @@ -15,6 +15,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } subscription EventRegistrations($eventId: UUID!, $after: Datetime!) { diff --git a/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql b/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql new file mode 100644 index 000000000..c3b9a18ef --- /dev/null +++ b/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql @@ -0,0 +1,43 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + __typename + } + category { + name + __typename + } + __typename +} +query McpEvents { + signupOpenEvents: events( + filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}} + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC] + ) { + nodes { + ...McpEventSummary + __typename + } + __typename + } + signupUpcomingEvents: events( + filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}} + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC] + ) { + nodes { + ...McpEventSummary + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/3d3ae0471e11f29477713606f9d884cb6d2a031b1a8bed9e220bec4c5e54337f.graphql b/@app/graphql/.persisted_operations/bffffd864222384112f122baf9c8fa57abf446e3ab2581427e4ebd7d283a1a49.graphql similarity index 94% rename from @app/graphql/.persisted_operations/3d3ae0471e11f29477713606f9d884cb6d2a031b1a8bed9e220bec4c5e54337f.graphql rename to @app/graphql/.persisted_operations/bffffd864222384112f122baf9c8fa57abf446e3ab2581427e4ebd7d283a1a49.graphql index 6031860df..ce80f5365 100644 --- a/@app/graphql/.persisted_operations/3d3ae0471e11f29477713606f9d884cb6d2a031b1a8bed9e220bec4c5e54337f.graphql +++ b/@app/graphql/.persisted_operations/bffffd864222384112f122baf9c8fa57abf446e3ab2581427e4ebd7d283a1a49.graphql @@ -12,6 +12,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -20,6 +22,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { diff --git a/@app/graphql/.persisted_operations/c1fcbe61c9d0e1ce646b37939311ab12250ae1b8135853774796ccf215543502.graphql b/@app/graphql/.persisted_operations/c1fcbe61c9d0e1ce646b37939311ab12250ae1b8135853774796ccf215543502.graphql new file mode 100644 index 000000000..4648ca61d --- /dev/null +++ b/@app/graphql/.persisted_operations/c1fcbe61c9d0e1ce646b37939311ab12250ae1b8135853774796ccf215543502.graphql @@ -0,0 +1,6 @@ +mutation DeleteRegistrationProfile { + deleteRegistrationProfile(input: {}) { + boolean + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/301da0928db49b18b443128fd731b8815df9fd05a090c4f6e648837bc2436754.graphql b/@app/graphql/.persisted_operations/c57acae206812492a8b0dfd4e90543db58744bc4aa247c34d109f57544645dfa.graphql similarity index 96% rename from @app/graphql/.persisted_operations/301da0928db49b18b443128fd731b8815df9fd05a090c4f6e648837bc2436754.graphql rename to @app/graphql/.persisted_operations/c57acae206812492a8b0dfd4e90543db58744bc4aa247c34d109f57544645dfa.graphql index a8e2594d3..1ca55743e 100644 --- a/@app/graphql/.persisted_operations/301da0928db49b18b443128fd731b8815df9fd05a090c4f6e648837bc2436754.graphql +++ b/@app/graphql/.persisted_operations/c57acae206812492a8b0dfd4e90543db58744bc4aa247c34d109f57544645dfa.graphql @@ -43,6 +43,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -51,6 +53,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { @@ -129,6 +132,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -165,6 +169,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } query HomePage($language: String!) { 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/cb08454007d6441f08369a59c8b3e3c32da61108fcc87ac4210cb7e77cef97e1.graphql b/@app/graphql/.persisted_operations/cb08454007d6441f08369a59c8b3e3c32da61108fcc87ac4210cb7e77cef97e1.graphql new file mode 100644 index 000000000..7550c405b --- /dev/null +++ b/@app/graphql/.persisted_operations/cb08454007d6441f08369a59c8b3e3c32da61108fcc87ac4210cb7e77cef97e1.graphql @@ -0,0 +1,6 @@ +mutation CreateCheckoutSession($updateToken: String!, $language: String) { + createCheckoutSession(updateToken: $updateToken, language: $language) { + url + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/cdd10e0c3b8b2adccafdf31b35c9e2eb9bdc64e89f7135c594b2f2c8277c4710.graphql b/@app/graphql/.persisted_operations/cdd10e0c3b8b2adccafdf31b35c9e2eb9bdc64e89f7135c594b2f2c8277c4710.graphql new file mode 100644 index 000000000..0b52224d5 --- /dev/null +++ b/@app/graphql/.persisted_operations/cdd10e0c3b8b2adccafdf31b35c9e2eb9bdc64e89f7135c594b2f2c8277c4710.graphql @@ -0,0 +1,17 @@ +fragment RegistrationProfile on RegistrationProfile { + userId + telegram + dietaryRestrictions + __typename +} +mutation SetRegistrationProfile($telegram: String, $dietaryRestrictions: String) { + setRegistrationProfile( + input: {telegram: $telegram, dietaryRestrictions: $dietaryRestrictions} + ) { + registrationProfile { + ...RegistrationProfile + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/ee194a404f71f86061a2bf2a0720010115cf1b9de8fdb72b3088935ab9d15e1b.graphql b/@app/graphql/.persisted_operations/d0a176a2a68ce8d41574e0015e26607c673de6afa1be1d09a35c85beadde5d4f.graphql similarity index 75% rename from @app/graphql/.persisted_operations/ee194a404f71f86061a2bf2a0720010115cf1b9de8fdb72b3088935ab9d15e1b.graphql rename to @app/graphql/.persisted_operations/d0a176a2a68ce8d41574e0015e26607c673de6afa1be1d09a35c85beadde5d4f.graphql index f50c2e568..56b31fbe0 100644 --- a/@app/graphql/.persisted_operations/ee194a404f71f86061a2bf2a0720010115cf1b9de8fdb72b3088935ab9d15e1b.graphql +++ b/@app/graphql/.persisted_operations/d0a176a2a68ce8d41574e0015e26607c673de6afa1be1d09a35c85beadde5d4f.graphql @@ -1,6 +1,6 @@ fragment ListEventRegistrations_Query on Query { registrations( - filter: {eventId: {equalTo: $eventId}} + filter: {eventId: {equalTo: $eventId}, paymentStatus: $paymentStatus, status: $status} first: $first offset: $offset orderBy: [QUOTA_ID_ASC, POSITION_ASC] @@ -22,6 +22,7 @@ fragment ListEventRegistrations_Registration on Registration { isFinished status position + paymentStatus createdAt updatedAt quota { @@ -35,8 +36,9 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } -query ListEventRegistrations($eventId: UUID!, $offset: Int!, $first: Int!) { +query ListEventRegistrations($eventId: UUID!, $offset: Int!, $first: Int!, $paymentStatus: RegistrationPaymentStatusFilter, $status: RegistrationStatusFilter) { ...ListEventRegistrations_Query } \ 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/.persisted_operations/d89ecb8fe4cd335fc3558aac502cc51e24b3aed26c115de93b6bc8531921257a.graphql b/@app/graphql/.persisted_operations/d89ecb8fe4cd335fc3558aac502cc51e24b3aed26c115de93b6bc8531921257a.graphql new file mode 100644 index 000000000..b0f4706a9 --- /dev/null +++ b/@app/graphql/.persisted_operations/d89ecb8fe4cd335fc3558aac502cc51e24b3aed26c115de93b6bc8531921257a.graphql @@ -0,0 +1,14 @@ +mutation AdminMarkRegistrationPaid($input: AdminMarkRegistrationPaidInput!) { + adminMarkRegistrationPaid(input: $input) { + payment { + id + __typename + } + registration { + id + paymentStatus + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/f03f38c3d71fd696ef382a99987cf83cc85f699074616d593fbd4216e7de1a2f.graphql b/@app/graphql/.persisted_operations/dbd82c75d048b7c5dce1e558592e60e2e952c67840720044656af51c1dac8595.graphql similarity index 95% rename from @app/graphql/.persisted_operations/f03f38c3d71fd696ef382a99987cf83cc85f699074616d593fbd4216e7de1a2f.graphql rename to @app/graphql/.persisted_operations/dbd82c75d048b7c5dce1e558592e60e2e952c67840720044656af51c1dac8595.graphql index 3be1106e6..8b98c7598 100644 --- a/@app/graphql/.persisted_operations/f03f38c3d71fd696ef382a99987cf83cc85f699074616d593fbd4216e7de1a2f.graphql +++ b/@app/graphql/.persisted_operations/dbd82c75d048b7c5dce1e558592e60e2e952c67840720044656af51c1dac8595.graphql @@ -23,6 +23,8 @@ fragment SharedLayout_Query on Query { } ssoLoginEnabled supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList __typename } fragment SharedLayout_User on User { @@ -31,6 +33,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { diff --git a/@app/graphql/.persisted_operations/1583d624d064d3c3b0fc46fd55d971815a7a669d38c8f20fe06b2049fe048744.graphql b/@app/graphql/.persisted_operations/dc1de21028bd15259ca7c0c350e7392ea45263ffac475ef68ecbac0b9df19a81.graphql similarity index 93% rename from @app/graphql/.persisted_operations/1583d624d064d3c3b0fc46fd55d971815a7a669d38c8f20fe06b2049fe048744.graphql rename to @app/graphql/.persisted_operations/dc1de21028bd15259ca7c0c350e7392ea45263ffac475ef68ecbac0b9df19a81.graphql index 2bee7ad6f..3d94d931c 100644 --- a/@app/graphql/.persisted_operations/1583d624d064d3c3b0fc46fd55d971815a7a669d38c8f20fe06b2049fe048744.graphql +++ b/@app/graphql/.persisted_operations/dc1de21028bd15259ca7c0c350e7392ea45263ffac475ef68ecbac0b9df19a81.graphql @@ -1,4 +1,4 @@ -fragment EventPage_Subscription on Subscription { +fragment EventPage_Query on Query { currentUser { ...SharedLayout_User __typename @@ -15,6 +15,7 @@ fragment SharedLayout_User on User { username avatarUrl isAdmin + isDeveloper isVerified primaryEmail userEmails(first: 50) { @@ -93,6 +94,7 @@ fragment EventFields on Event { registrationStartTime registrationEndTime isHighlighted + highlightText isDraft headerImageFile openQuotaSize @@ -129,6 +131,7 @@ fragment EventPage_Quota on Quota { position title size + priceCents __typename } fragment EventPage_Registration on Registration { @@ -150,8 +153,9 @@ fragment EventPage_Question on EventQuestion { label isRequired data + prefill __typename } -subscription EventPage($slug: String!) { - ...EventPage_Subscription +query EventPage($slug: String!) { + ...EventPage_Query } \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/f46dd366f70bd59c89f7f201c1c3a704deab774b92ecad0f37c29d37d4cdb648.graphql b/@app/graphql/.persisted_operations/f46dd366f70bd59c89f7f201c1c3a704deab774b92ecad0f37c29d37d4cdb648.graphql new file mode 100644 index 000000000..89b3e9cdb --- /dev/null +++ b/@app/graphql/.persisted_operations/f46dd366f70bd59c89f7f201c1c3a704deab774b92ecad0f37c29d37d4cdb648.graphql @@ -0,0 +1,94 @@ +fragment SharedLayout_Query on Query { + currentUser { + ...SharedLayout_User + __typename + } + organizations(orderBy: SLUG_ASC) { + nodes { + ...SharedLayout_Organization + __typename + } + __typename + } + ssoLoginEnabled + supportedLanguages + enabledFeaturesList + adminPreviewFeaturesList + __typename +} +fragment SharedLayout_User on User { + id + name + username + avatarUrl + isAdmin + isDeveloper + 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 PayPage_RegistrationPayment on RegistrationPayment { + eventId + eventSlug + eventName + eventStartTime + eventEndTime + registrationEndTime + quotaTitle + firstName + lastName + queueStatus + queuePosition + status + priceCents + serviceFeeCents + totalCents + paidManually + paidTotalCents + paidAt + blockedReason + __typename +} +query PayPage($updateToken: String!) { + ...SharedLayout_Query + paymentByUpdateToken(updateToken: $updateToken) { + ...PayPage_RegistrationPayment + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql b/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql new file mode 100644 index 000000000..abc70cbb7 --- /dev/null +++ b/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql @@ -0,0 +1,22 @@ +query McpEventOptions { + organizations { + nodes { + id + name + __typename + } + __typename + } + eventCategories(orderBy: NAME_ASC) { + nodes { + id + name + ownerOrganization { + id + __typename + } + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/client.json b/@app/graphql/client.json index c68ae7607..30baeef4b 100644 --- a/@app/graphql/client.json +++ b/@app/graphql/client.json @@ -4,44 +4,59 @@ "CreateEventCategory": "9fb202fac8b6c91ad9ba74ce246cfc3164f66cc3e11d940048bf289fcb0f7450", "DeleteEventCategory": "f555d3fc31063758bc496e6fca37600cb6734d08aa6a8f9337f1073636a1bb8d", "ListEventCategories": "9cc733e3ca754e0697c58ff9e697d6605cfc53c15fe7946849dbef75c677d808", - "UpdateEventCategoryPage": "994c6d2a2d085b6452233787ccd1502e270b193029b1793369e0d7503ef999b5", + "UpdateEventCategoryPage": "059752747adcbd9bc1dd51f36f20f6cce2ce65b5c66c57a66905471744a48e6f", "UpdateEventCategory": "940f0de83cc5a7fbcd2d8e2d1774a59556f759b117c0b6d8e5ce8c5584907eae", "AdminListEvents": "ee0afc787cdba3845d8fe784c6585e07c101573c699914e3803ed9c17fb8360b", - "CreateEventPage": "77885919f782dbb117e2759c4918f2445a633ed0a98d08fd5d1ab699ebce9391", - "CreateEvent": "98965cb2bb84e54d0e0d6ba48046a829fc42776ce6b7b9eeae134dcae7036044", + "AdminSendPaymentReminders": "894559d77667dd2e7ea2fc0efaf41669235fe335936e8833155115ccadf61330", + "CreateEventPage": "1e004ee4f10fea6972a6c364a9d4955664248c4745f0948543200c9b8e47fdda", + "CreateEvent": "936b95b84ab4570162a3124685b9aa033c72a848ec5a288ff1cec143bf134a57", "DeleteEvent": "75c86da8b31d18d79c4dcab26bacfffb860b4c7933568ca830731c793f815338", - "ListEventsPage": "f03f38c3d71fd696ef382a99987cf83cc85f699074616d593fbd4216e7de1a2f", + "EventPaymentSummary": "37b4cd795c818a76ab63d56f5ba1009e6663d18bef8c95110a17f272b0bb94d4", + "ListEventsPage": "dbd82c75d048b7c5dce1e558592e60e2e952c67840720044656af51c1dac8595", "TranslateText": "2fd1ef03df33a4dacf0b46162521f2bec22b99971807fb81a205aa5d36a0e59c", - "UpdateEventPage": "7e487496b03e301f627d86bce4edd2273740b18548ad91c12bd6575aaff34ad7", - "UpdateEvent": "063ffe79e5b7bcf7d58cc1b0742a2526dfd993ebd5550a37cc5d326b8fd35d00", + "UpdateEventPage": "8b41853c48d6d26068e2f31be3228ac4de7cba203d5bc2cda3f18aa69d4b079c", + "UpdateEvent": "3b54a951d1aa12e533adfdeea2ceca0ab7c74cc25b3560018bce199d4ee5b170", + "AdminFeatures": "049ad46a1304886067ad2325866baed2b66979a18cc09333740a2c49ac1d7744", + "SetFeatureFlag": "7ed3c3bc6904aa0bbc8ee96e5483d4ca9367eaa40d685d9435751b40d272b6eb", "InviteToOrganization": "c639d16546c2d6c7133350ef65627885f7e11a1e33ec9ae099d0bb4a9b9af331", "OrganizationBySlug": "7d4e6fe382bf3e0467c9372406e18fd1e63b6aa3f1aea2530a66c60cdfa3da2d", - "OrganizationPage": "e75fddfae08b7bdc7571c0cd3426cdda51dc0b336d6a428c214da7d7f2752708", + "OrganizationPage": "946019cf0fe0197d6083b7c83faf8383b2327468ab7b6ec1eeff53c74b921d7e", "RemoveFromOrganization": "234a33748153a85850a5e8cd76126a46c10f300f3e3deee0b1e8b832aa66948d", "TransferOrganizationOwnership": "949e86df3cd114d207d517c292df1fc19b09e8ce9609c4ae243b61f002959bd7", "UpdateOrganization": "565716f69ef0f845afbba0bb8ff6b0b2c67e10926db9646ac20350588b4c0dc1", "AdminDeleteRegistration": "658e6abd232060aa32b938a4d434bd5596c413246ad41bcc6ab3935ef5947517", + "AdminMarkRegistrationPaid": "d89ecb8fe4cd335fc3558aac502cc51e24b3aed26c115de93b6bc8531921257a", + "AdminUnmarkRegistrationPaid": "567efbd2a44d533f2c0d9c75f66ab1be7bf6c166e04ad86492b75c824ee975db", "AdminUpdateRegistration": "99191cf15f4a3be32fc16c58978a443803ee3851ff40f927bfcdcaf63bb71c98", - "ListEventRegistrations": "ee194a404f71f86061a2bf2a0720010115cf1b9de8fdb72b3088935ab9d15e1b", + "ListEventRegistrations": "d0a176a2a68ce8d41574e0015e26607c673de6afa1be1d09a35c85beadde5d4f", "AdminDeleteUser": "272d8236ba9669d320fc31b805cbeeb08662b4f7a510392a307694c420e030fd", "AdminListUsers": "9dc8f24c328dc0dc2e150a71047eecfa5bbf8e350f9fa1b3e9bd3abef4a6edc0", "SetAdminStatus": "9622d74eaeb7042221e04a2d63ed26a4e3c673071f7538537d36fdf1f453ba69", - "EventPage": "1583d624d064d3c3b0fc46fd55d971815a7a669d38c8f20fe06b2049fe048744", - "EventRegistrations": "c22efb8e3e3226153a7be53c61321e72c94f3cbc667ca769cc056b4fee27678c", - "HomePageEvents": "368543083e66d7a6ae5e78654849ec0d94283752aece92394005e027bf3e429c", - "HomePage": "301da0928db49b18b443128fd731b8815df9fd05a090c4f6e648837bc2436754", + "EventPage": "dc1de21028bd15259ca7c0c350e7392ea45263ffac475ef68ecbac0b9df19a81", + "EventRegistrations": "bf749c8be1be824ca2fc06b6a275550762c94543bbe165775804d7ab709dce20", + "HomePageEvents": "b78ccb2c8f90523ea273e051c83894e18168066d4c117484d1e585169d7e0986", + "HomePage": "c57acae206812492a8b0dfd4e90543db58744bc4aa247c34d109f57544645dfa", "CurrentTime": "f836d34508a8ee8ab07ca87bb086fe03dbddcf1fa40ffe912ef6143a843db460", - "Shared": "eb985e5bfabc266d0fc5637eda513cac8a293bc851b29e863dbf304c4932f7f1", + "Shared": "4279223c3efdc362aae98e81e1cda66c7a006cafd8ca8245b4216028c12901ca", "AcceptOrganizationInvite": "29b135f119928bfc6de24b8aa6ec513ed62cb3cadf95eec1da607a3c760df7e9", "CreateOrganization": "61c018fcf82eca2de4bf2fe5ca833cbf1586808421b10428aa99ba75b028cc6c", "DeleteOrganization": "39f623b7dd9b3111922c0937f5985ef32d8de76b88898b043daaf53dc20877b2", - "InvitationDetail": "3d3ae0471e11f29477713606f9d884cb6d2a031b1a8bed9e220bec4c5e54337f", + "InvitationDetail": "bffffd864222384112f122baf9c8fa57abf446e3ab2581427e4ebd7d283a1a49", + "CreateCheckoutSession": "cb08454007d6441f08369a59c8b3e3c32da61108fcc87ac4210cb7e77cef97e1", + "PayPage": "f46dd366f70bd59c89f7f201c1c3a704deab774b92ecad0f37c29d37d4cdb648", "ClaimRegistrationToken": "c3c63bf12e25e4025a986f94781d706f7adb2261e91689d356069378faec2c4a", - "CreateEventRegistrationPage": "c80a1b7e4a79510cd8e544910e72dec734223574011e0a40bb00c78de8de310c", - "CreateEventRegistration": "e97c6726ce1d78c512935a15f46e8315e8ab2e50b2776d4fa1c92a5e8a54c566", + "CreateEventRegistrationPage": "20fe542e08269ad0e1479f307ce17f1b04c59e48f2dd73139d36dbdeaef3e99a", + "CreateEventRegistration": "282c98619013fc7f0e852cec433d21a04a36d1d07350d011424ac32a60d772c7", "DeleteEventRegistration": "be0f72e306dcf5e22dbaa962b5228422a5a0bd12dc68d688ee8b9a28b479318b", - "UpdateEventRegistrationPage": "2e4a7c74a71603bcec3debb7b11c003a481d28d6b25b130694e38f2760fcf7e9", - "UpdateEventRegistration": "a073a90b247942ecbca6dd214aa1b2dcbe42ab30618e881c8a8d90b1c5097739", + "UpdateEventRegistrationPage": "92fa1d7b23f5698f63d7fd93956a8531b95100abe24cb95ec3280c132e838d55", + "UpdateEventRegistration": "11644b9a58d11149330a34204af8f15f758efccc09bcb64b231648f72877a357", + "RegistrationReminders": "84dab768dd94228356723651b754e840eef05d581c712a4a00802656158d9db1", + "EventRegistrationReminder": "16a4c2e9d9f0743742df9c4ba1869f88a16ff6fef26f3cfd3996c81a8cdcc9ad", + "SetEventRegistrationReminder": "19a6eebfaa8a089df2530d97c05f87c51e1480cf01ae7fab2ec82396a11e3373", + "RequestTelegramLink": "9fc48916001fbcfd80219a6f3845ceb3ca75177a45ec44ebf459e8552639214b", + "DisconnectTelegram": "c995ce75219b91ac1d64cb9d5f10905d24d12b8dfa77e280ba963dfda631dcf3", + "SaveReminderPreferences": "3f7f7eb57188693a11465046f3f564018d51bb73560ac2915bc09565a902d10e", + "EnableEventReminder": "d2a39c6ec461a6ac752c0f4b865ea903adbd9765ceb023a2dfbef48540cadd94", "AddEmail": "da27b66ae2e115cc90ba53748aaadae32ba97b016e2783550fe847089f7423c2", "ChangePassword": "2532c897bead71cb8b9171c240298a47c4b6b13197886c990ccfcc937356ceab", "ConfirmAccountDeletion": "28c6757c5282d5f04e93b027aea1642ffd3afc54ea99778983d476e615919c04", @@ -53,11 +68,17 @@ "Logout": "953cdfb120682429839e878cb7f9e483d97dff06ed0d4eb80428cb98896c58fd", "MakeEmailPrimary": "585b5baf970ccdcfc9031b3063524111fb24c972b41b6902e0b97c26eed8407d", "PasswordStrength": "bb833917071d149b426642c0a8b641b629532a44f6c2ab3794a625f91e4d862e", + "RegistrationProfile": "40299daf2530066a9fdf98480092ba41a41f6d727ed35ca47e5d8a6c0002ce7e", + "SetRegistrationProfile": "cdd10e0c3b8b2adccafdf31b35c9e2eb9bdc64e89f7135c594b2f2c8277c4710", + "DeleteRegistrationProfile": "c1fcbe61c9d0e1ce646b37939311ab12250ae1b8135853774796ccf215543502", "RequestAccountDeletion": "a15c749947f08c4c76e36aaa48042537e7f011318cb0424a67cceb336b8f1f7d", "ResendEmailVerification": "91c3f0e452f0295520ee02ffbb79759b6a96cac6fc9ccaa514ffaa4e1ca8deba", "ResetPassword": "0c6997c5a3b8b971a99c59a3ec6bd05d7fd24ff1aa3d7bbcc8a4bb0808de0ad7", "SettingsPassword": "4ccd52e00c526690ac5b44ca911534e96f936acd4ff02a2785d9932bbe11ff6c", "UnlinkUserAuthentication": "efef5d154b91120114a5ae97193bb83daee1223c150c8bda2d6655a47482fb70", "UpdateUser": "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441", - "VerifyEmail": "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1" + "VerifyEmail": "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1", + "McpEvents": "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600", + "McpEventOptions": "f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44", + "McpEvent": "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf" } \ No newline at end of file diff --git a/@app/graphql/codegen.yml b/@app/graphql/codegen.yml index 0f185f9bb..7917255a3 100644 --- a/@app/graphql/codegen.yml +++ b/@app/graphql/codegen.yml @@ -1,6 +1,8 @@ overwrite: true schema: "../../data/schema.graphql" -documents: "../client/src/**/*.graphql" +documents: + - "../client/src/**/*.graphql" + - "../server/src/**/*.graphql" hooks: afterAllFileWrite: - node scripts/addToPersistedOperations.mjs diff --git a/@app/graphql/scripts/addToPersistedOperations.mjs b/@app/graphql/scripts/addToPersistedOperations.mjs index 3ef5bd650..1b43d8782 100644 --- a/@app/graphql/scripts/addToPersistedOperations.mjs +++ b/@app/graphql/scripts/addToPersistedOperations.mjs @@ -1,7 +1,8 @@ import { promises as fsp } from "node:fs" import path from "node:path" +import { fileURLToPath } from "node:url" -const __dirname = new URL(".", import.meta.url).pathname +const __dirname = fileURLToPath(new URL(".", import.meta.url)) const allowedQueries = await fsp.readFile( path.join(__dirname, "..", "server.json"), "utf-8" @@ -14,7 +15,7 @@ async function main() { "..", ".persisted_operations/" ) - await fsp.rmdir(persistedOperationsDir, { recursive: true }) + await fsp.rm(persistedOperationsDir, { recursive: true, force: true }) await fsp.mkdir(persistedOperationsDir) await Promise.all( Object.entries(map).map(([hash, query]) => diff --git a/@app/graphql/scripts/minifyIntrospectionSchema.mjs b/@app/graphql/scripts/minifyIntrospectionSchema.mjs index 4546895e5..e3b484bf2 100644 --- a/@app/graphql/scripts/minifyIntrospectionSchema.mjs +++ b/@app/graphql/scripts/minifyIntrospectionSchema.mjs @@ -1,8 +1,9 @@ import { minifyIntrospectionQuery } from "@urql/introspection" import { promises as fsp } from "node:fs" import path from "node:path" +import { fileURLToPath } from "node:url" -const __dirname = new URL(".", import.meta.url).pathname +const __dirname = fileURLToPath(new URL(".", import.meta.url)) const introspection = await fsp.readFile( path.join(__dirname, "..", "introspection.json"), "utf-8" diff --git a/@app/graphql/server.json b/@app/graphql/server.json index ae4556691..4438067b1 100644 --- a/@app/graphql/server.json +++ b/@app/graphql/server.json @@ -4,44 +4,59 @@ "9fb202fac8b6c91ad9ba74ce246cfc3164f66cc3e11d940048bf289fcb0f7450": "fragment 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}\nmutation CreateEventCategory($input: CreateEventCategoryInput!) {\n createEventCategory(input: $input) {\n eventCategory {\n ...EventPage_EventCategory\n __typename\n }\n __typename\n }\n}", "f555d3fc31063758bc496e6fca37600cb6734d08aa6a8f9337f1073636a1bb8d": "mutation DeleteEventCategory($id: UUID!) {\n deleteEventCategory(input: {id: $id}) {\n clientMutationId\n __typename\n }\n}", "9cc733e3ca754e0697c58ff9e697d6605cfc53c15fe7946849dbef75c677d808": "fragment ListEventCategories_Query on Query {\n eventCategories(first: $first, offset: $offset) {\n nodes {\n id\n ...ListEventCategories\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment ListEventCategories on EventCategory {\n ...EventPage_EventCategory\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}\nquery ListEventCategories($offset: Int!, $first: Int!) {\n ...ListEventCategories_Query\n}", - "994c6d2a2d085b6452233787ccd1502e270b193029b1793369e0d7503ef999b5": "fragment UpdateEventCategoryPage_Query on Query {\n ...SharedLayout_Query\n eventCategory(id: $id) {\n id\n ...EventPage_EventCategory\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 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}\nquery UpdateEventCategoryPage($id: UUID!) {\n ...UpdateEventCategoryPage_Query\n}", + "059752747adcbd9bc1dd51f36f20f6cce2ce65b5c66c57a66905471744a48e6f": "fragment UpdateEventCategoryPage_Query on Query {\n ...SharedLayout_Query\n eventCategory(id: $id) {\n id\n ...EventPage_EventCategory\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 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}\nquery UpdateEventCategoryPage($id: UUID!) {\n ...UpdateEventCategoryPage_Query\n}", "940f0de83cc5a7fbcd2d8e2d1774a59556f759b117c0b6d8e5ce8c5584907eae": "fragment 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}\nmutation UpdateEventCategory($input: UpdateEventCategoryInput!) {\n updateEventCategory(input: $input) {\n eventCategory {\n ...EventPage_EventCategory\n __typename\n }\n __typename\n }\n}", "ee0afc787cdba3845d8fe784c6585e07c101573c699914e3803ed9c17fb8360b": "fragment AdminListEvents_Query on Query {\n events(first: $first, offset: $offset, filter: $filter, orderBy: $orderBy) {\n nodes {\n ...AdminListEvents_Event\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment AdminListEvents_Event on Event {\n id\n name\n slug\n isDraft\n isHighlighted\n registrationStartTime\n eventStartTime\n category {\n id\n name\n color\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n id\n title\n size\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n registrations {\n totalCount\n __typename\n }\n __typename\n}\nquery AdminListEvents($offset: Int!, $first: Int!, $filter: EventFilter, $orderBy: [EventsOrderBy!]) {\n ...AdminListEvents_Query\n}", - "77885919f782dbb117e2759c4918f2445a633ed0a98d08fd5d1ab699ebce9391": "fragment CreateEventPage_Query on Query {\n ...SharedLayout_Query\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n ...EventPage_EventCategory\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 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}\nquery CreateEventPage {\n ...CreateEventPage_Query\n}", - "98965cb2bb84e54d0e0d6ba48046a829fc42776ce6b7b9eeae134dcae7036044": "fragment 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}\nmutation CreateEvent($input: CreateEventInput!) {\n createEvent(input: $input) {\n event {\n ...EventFields\n __typename\n }\n __typename\n }\n}", + "894559d77667dd2e7ea2fc0efaf41669235fe335936e8833155115ccadf61330": "mutation AdminSendPaymentReminders($input: AdminSendPaymentRemindersInput!) {\n adminSendPaymentReminders(input: $input) {\n integer\n __typename\n }\n}", + "1e004ee4f10fea6972a6c364a9d4955664248c4745f0948543200c9b8e47fdda": "fragment CreateEventPage_Query on Query {\n ...SharedLayout_Query\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n ...EventPage_EventCategory\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 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}\nquery CreateEventPage {\n ...CreateEventPage_Query\n}", + "936b95b84ab4570162a3124685b9aa033c72a848ec5a288ff1cec143bf134a57": "fragment EventFields on Event {\n id\n name\n slug\n description\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n isHighlighted\n highlightText\n isDraft\n headerImageFile\n openQuotaSize\n signupOpen\n signupUpcoming\n signupClosed\n createdBy\n updatedBy\n createdAt\n updatedAt\n __typename\n}\nmutation CreateEvent($input: CreateEventInput!) {\n createEvent(input: $input) {\n event {\n ...EventFields\n __typename\n }\n __typename\n }\n}", "75c86da8b31d18d79c4dcab26bacfffb860b4c7933568ca830731c793f815338": "mutation DeleteEvent($id: UUID!) {\n deleteEvent(input: {id: $id}) {\n clientMutationId\n __typename\n }\n}", - "f03f38c3d71fd696ef382a99987cf83cc85f699074616d593fbd4216e7de1a2f": "fragment ListEventsPage_Query on Query {\n ...SharedLayout_Query\n eventCategories {\n nodes {\n ...EventPage_EventCategory\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 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}\nquery ListEventsPage {\n ...ListEventsPage_Query\n}", + "37b4cd795c818a76ab63d56f5ba1009e6663d18bef8c95110a17f272b0bb94d4": "fragment EventPaymentSummary_Event on Event {\n id\n lastPaymentReminderSentAt\n quotas {\n nodes {\n id\n priceCents\n __typename\n }\n __typename\n }\n registrations {\n totalCount\n __typename\n }\n paymentSummary {\n paidCount\n unpaidCount\n dueCount\n ticketsPaidCents\n guildReceivesCents\n unlinkedCardPaymentCount\n __typename\n }\n __typename\n}\nquery EventPaymentSummary($id: UUID!) {\n event(id: $id) {\n ...EventPaymentSummary_Event\n __typename\n }\n}", + "dbd82c75d048b7c5dce1e558592e60e2e952c67840720044656af51c1dac8595": "fragment ListEventsPage_Query on Query {\n ...SharedLayout_Query\n eventCategories {\n nodes {\n ...EventPage_EventCategory\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 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}\nquery ListEventsPage {\n ...ListEventsPage_Query\n}", "2fd1ef03df33a4dacf0b46162521f2bec22b99971807fb81a205aa5d36a0e59c": "mutation TranslateText($from: SupportedLanguages!, $to: SupportedLanguages!, $text: String!) {\n translateText(fromLanguage: $from, toLanguage: $to, text: $text) {\n originalText\n translatedText\n __typename\n }\n}", - "7e487496b03e301f627d86bce4edd2273740b18548ad91c12bd6575aaff34ad7": "fragment UpdateEventPage_Query on Query {\n ...SharedLayout_Query\n event(id: $id) {\n ...UpdateEventPage_Event\n __typename\n }\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n ...EventPage_EventCategory\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 UpdateEventPage_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 registrations {\n totalCount\n __typename\n }\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_Quota on Quota {\n id\n position\n title\n size\n __typename\n}\nfragment EventPage_Question on EventQuestion {\n id\n position\n type\n label\n isRequired\n data\n __typename\n}\nquery UpdateEventPage($id: UUID!) {\n ...UpdateEventPage_Query\n}", - "063ffe79e5b7bcf7d58cc1b0742a2526dfd993ebd5550a37cc5d326b8fd35d00": "fragment 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}\nmutation UpdateEvent($input: UpdateEventInput!) {\n updateEvent(input: $input) {\n event {\n ...EventFields\n __typename\n }\n __typename\n }\n}", + "8b41853c48d6d26068e2f31be3228ac4de7cba203d5bc2cda3f18aa69d4b079c": "fragment UpdateEventPage_Query on Query {\n ...SharedLayout_Query\n event(id: $id) {\n ...UpdateEventPage_Event\n __typename\n }\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n ...EventPage_EventCategory\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 UpdateEventPage_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 priceCents\n registrations {\n totalCount\n __typename\n }\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 highlightText\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_Quota on Quota {\n id\n position\n title\n size\n priceCents\n __typename\n}\nfragment EventPage_Question on EventQuestion {\n id\n position\n type\n label\n isRequired\n data\n prefill\n __typename\n}\nquery UpdateEventPage($id: UUID!) {\n ...UpdateEventPage_Query\n}", + "3b54a951d1aa12e533adfdeea2ceca0ab7c74cc25b3560018bce199d4ee5b170": "fragment EventFields on Event {\n id\n name\n slug\n description\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n isHighlighted\n highlightText\n isDraft\n headerImageFile\n openQuotaSize\n signupOpen\n signupUpcoming\n signupClosed\n createdBy\n updatedBy\n createdAt\n updatedAt\n __typename\n}\nmutation UpdateEvent($input: UpdateEventInput!) {\n updateEvent(input: $input) {\n event {\n ...EventFields\n __typename\n }\n __typename\n }\n}", + "049ad46a1304886067ad2325866baed2b66979a18cc09333740a2c49ac1d7744": "fragment AdminFeatures_FeatureFlag on FeatureFlag {\n key\n state\n available\n description\n updatedAt\n retiredAt\n __typename\n}\nfragment AdminFeatures_FeatureFlagEvent on FeatureFlagEventsRecord {\n id\n key\n oldState\n newState\n actorId\n actorName\n actorUsername\n createdAt\n __typename\n}\nquery AdminFeatures {\n featureFlags(orderBy: KEY_ASC) {\n nodes {\n ...AdminFeatures_FeatureFlag\n __typename\n }\n __typename\n }\n featureFlagEventsList {\n ...AdminFeatures_FeatureFlagEvent\n __typename\n }\n}", + "7ed3c3bc6904aa0bbc8ee96e5483d4ca9367eaa40d685d9435751b40d272b6eb": "fragment AdminFeatures_FeatureFlag on FeatureFlag {\n key\n state\n available\n description\n updatedAt\n retiredAt\n __typename\n}\nmutation SetFeatureFlag($input: SetFeatureFlagInput!) {\n setFeatureFlag(input: $input) {\n featureFlag {\n ...AdminFeatures_FeatureFlag\n __typename\n }\n __typename\n }\n}", "c639d16546c2d6c7133350ef65627885f7e11a1e33ec9ae099d0bb4a9b9af331": "mutation InviteToOrganization($organizationId: UUID!, $email: String, $username: String) {\n inviteToOrganization(\n input: {organizationId: $organizationId, email: $email, username: $username}\n ) {\n clientMutationId\n __typename\n }\n}", "7d4e6fe382bf3e0467c9372406e18fd1e63b6aa3f1aea2530a66c60cdfa3da2d": "query OrganizationBySlug($slug: String!) {\n organizationBySlug(slug: $slug) {\n id\n name\n slug\n __typename\n }\n}", - "e75fddfae08b7bdc7571c0cd3426cdda51dc0b336d6a428c214da7d7f2752708": "fragment OrganizationPage_Query on Query {\n ...SharedLayout_Query\n organizationBySlug(slug: $slug) {\n ...OrganizationPage_Organization\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 OrganizationPage_Organization on Organization {\n ...EventPage_Organization\n currentUserIsOwner\n organizationMemberships(first: 10, offset: $offset, orderBy: [MEMBER_NAME_ASC]) {\n nodes {\n ...OrganizationPage_Membership\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment EventPage_Organization on Organization {\n id\n name\n slug\n color\n __typename\n}\nfragment OrganizationPage_Membership on OrganizationMembership {\n id\n createdAt\n isOwner\n user {\n id\n username\n name\n __typename\n }\n __typename\n}\nquery OrganizationPage($slug: String!, $offset: Int = 0) {\n ...OrganizationPage_Query\n}", + "946019cf0fe0197d6083b7c83faf8383b2327468ab7b6ec1eeff53c74b921d7e": "fragment OrganizationPage_Query on Query {\n ...SharedLayout_Query\n organizationBySlug(slug: $slug) {\n ...OrganizationPage_Organization\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 OrganizationPage_Organization on Organization {\n ...EventPage_Organization\n currentUserIsOwner\n organizationMemberships(first: 10, offset: $offset, orderBy: [MEMBER_NAME_ASC]) {\n nodes {\n ...OrganizationPage_Membership\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment EventPage_Organization on Organization {\n id\n name\n slug\n color\n __typename\n}\nfragment OrganizationPage_Membership on OrganizationMembership {\n id\n createdAt\n isOwner\n user {\n id\n username\n name\n __typename\n }\n __typename\n}\nquery OrganizationPage($slug: String!, $offset: Int = 0) {\n ...OrganizationPage_Query\n}", "234a33748153a85850a5e8cd76126a46c10f300f3e3deee0b1e8b832aa66948d": "mutation RemoveFromOrganization($organizationId: UUID!, $userId: UUID!) {\n removeFromOrganization(\n input: {organizationId: $organizationId, userId: $userId}\n ) {\n clientMutationId\n __typename\n }\n}", "949e86df3cd114d207d517c292df1fc19b09e8ce9609c4ae243b61f002959bd7": "mutation TransferOrganizationOwnership($organizationId: UUID!, $userId: UUID!) {\n transferOrganizationOwnership(\n input: {organizationId: $organizationId, userId: $userId}\n ) {\n organization {\n id\n currentUserIsOwner\n __typename\n }\n __typename\n }\n}", "565716f69ef0f845afbba0bb8ff6b0b2c67e10926db9646ac20350588b4c0dc1": "fragment EventPage_Organization on Organization {\n id\n name\n slug\n color\n __typename\n}\nmutation UpdateOrganization($input: UpdateOrganizationInput!) {\n updateOrganization(input: $input) {\n organization {\n ...EventPage_Organization\n __typename\n }\n __typename\n }\n}", "658e6abd232060aa32b938a4d434bd5596c413246ad41bcc6ab3935ef5947517": "mutation AdminDeleteRegistration($input: AdminDeleteRegistrationInput!) {\n adminDeleteRegistration(input: $input) {\n success\n __typename\n }\n}", + "d89ecb8fe4cd335fc3558aac502cc51e24b3aed26c115de93b6bc8531921257a": "mutation AdminMarkRegistrationPaid($input: AdminMarkRegistrationPaidInput!) {\n adminMarkRegistrationPaid(input: $input) {\n payment {\n id\n __typename\n }\n registration {\n id\n paymentStatus\n __typename\n }\n __typename\n }\n}", + "567efbd2a44d533f2c0d9c75f66ab1be7bf6c166e04ad86492b75c824ee975db": "mutation AdminUnmarkRegistrationPaid($input: AdminUnmarkRegistrationPaidInput!) {\n adminUnmarkRegistrationPaid(input: $input) {\n boolean\n __typename\n }\n}", "99191cf15f4a3be32fc16c58978a443803ee3851ff40f927bfcdcaf63bb71c98": "mutation AdminUpdateRegistration($input: AdminUpdateRegistrationInput!) {\n adminUpdateRegistration(input: $input) {\n updateToken\n __typename\n }\n}", - "ee194a404f71f86061a2bf2a0720010115cf1b9de8fdb72b3088935ab9d15e1b": "fragment ListEventRegistrations_Query on Query {\n registrations(\n filter: {eventId: {equalTo: $eventId}}\n first: $first\n offset: $offset\n orderBy: [QUOTA_ID_ASC, POSITION_ASC]\n ) {\n nodes {\n ...ListEventRegistrations_Registration\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment ListEventRegistrations_Registration on Registration {\n id\n fullName\n email\n answers\n isFinished\n status\n position\n createdAt\n updatedAt\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}\nquery ListEventRegistrations($eventId: UUID!, $offset: Int!, $first: Int!) {\n ...ListEventRegistrations_Query\n}", + "d0a176a2a68ce8d41574e0015e26607c673de6afa1be1d09a35c85beadde5d4f": "fragment ListEventRegistrations_Query on Query {\n registrations(\n filter: {eventId: {equalTo: $eventId}, paymentStatus: $paymentStatus, status: $status}\n first: $first\n offset: $offset\n orderBy: [QUOTA_ID_ASC, POSITION_ASC]\n ) {\n nodes {\n ...ListEventRegistrations_Registration\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment ListEventRegistrations_Registration on Registration {\n id\n fullName\n email\n answers\n isFinished\n status\n position\n paymentStatus\n createdAt\n updatedAt\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 priceCents\n __typename\n}\nquery ListEventRegistrations($eventId: UUID!, $offset: Int!, $first: Int!, $paymentStatus: RegistrationPaymentStatusFilter, $status: RegistrationStatusFilter) {\n ...ListEventRegistrations_Query\n}", "272d8236ba9669d320fc31b805cbeeb08662b4f7a510392a307694c420e030fd": "mutation AdminDeleteUser($id: UUID!) {\n adminDeleteUser(input: {id: $id}) {\n success\n __typename\n }\n}", "9dc8f24c328dc0dc2e150a71047eecfa5bbf8e350f9fa1b3e9bd3abef4a6edc0": "fragment AdminListUsers_User on User {\n id\n username\n name\n avatarUrl\n isAdmin\n isVerified\n createdAt\n __typename\n}\nquery AdminListUsers {\n adminListUsers {\n nodes {\n ...AdminListUsers_User\n __typename\n }\n __typename\n }\n}", "9622d74eaeb7042221e04a2d63ed26a4e3c673071f7538537d36fdf1f453ba69": "mutation SetAdminStatus($input: SetAdminStatusInput!) {\n setAdminStatus(input: $input) {\n success\n __typename\n }\n}", - "1583d624d064d3c3b0fc46fd55d971815a7a669d38c8f20fe06b2049fe048744": "fragment EventPage_Subscription on Subscription {\n currentUser {\n ...SharedLayout_User\n __typename\n }\n eventBySlug(slug: $slug) {\n ...EventPage_Event\n __typename\n }\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 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_Quota on Quota {\n id\n position\n title\n size\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}\nsubscription EventPage($slug: String!) {\n ...EventPage_Subscription\n}", - "c22efb8e3e3226153a7be53c61321e72c94f3cbc667ca769cc056b4fee27678c": "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}\nsubscription EventRegistrations($eventId: UUID!, $after: Datetime!) {\n eventRegistrations(eventId: $eventId) {\n registrations(after: $after) {\n ...EventPage_Registration\n quota {\n ...EventPage_Quota\n __typename\n }\n __typename\n }\n __typename\n }\n}", - "368543083e66d7a6ae5e78654849ec0d94283752aece92394005e027bf3e429c": "fragment HomePageClosedEvents_Query on Query {\n signupClosedEvents: events(\n first: $first\n offset: $offset\n filter: {signupClosed: {equalTo: true}, name: {containsKey: $language}}\n orderBy: EVENT_END_TIME_DESC\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment HomePage_Event on Event {\n ...EventFields\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n category {\n ...EventPage_EventCategory\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Quota\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n registrations {\n totalCount\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_Organization on Organization {\n id\n name\n slug\n color\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_Quota on Quota {\n id\n position\n title\n size\n __typename\n}\nquery HomePageEvents($offset: Int, $first: Int, $language: String) {\n ...HomePageClosedEvents_Query\n}", - "301da0928db49b18b443128fd731b8815df9fd05a090c4f6e648837bc2436754": "fragment HomePage_Query on Query {\n ...SharedLayout_Query\n signupOpenEvents: events(\n filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}, name: {containsKey: $language}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n __typename\n }\n signupUpcomingEvents: events(\n filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}, name: {containsKey: $language}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n __typename\n }\n eventCategories {\n nodes {\n ...EventPage_EventCategory\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 HomePage_Event on Event {\n ...EventFields\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n category {\n ...EventPage_EventCategory\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Quota\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n registrations {\n totalCount\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_Organization on Organization {\n id\n name\n slug\n color\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_Quota on Quota {\n id\n position\n title\n size\n __typename\n}\nquery HomePage($language: String!) {\n ...HomePage_Query\n}", + "dc1de21028bd15259ca7c0c350e7392ea45263ffac475ef68ecbac0b9df19a81": "fragment EventPage_Query on Query {\n currentUser {\n ...SharedLayout_User\n __typename\n }\n eventBySlug(slug: $slug) {\n ...EventPage_Event\n __typename\n }\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 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 highlightText\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_Quota on Quota {\n id\n position\n title\n size\n priceCents\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 prefill\n __typename\n}\nquery EventPage($slug: String!) {\n ...EventPage_Query\n}", + "bf749c8be1be824ca2fc06b6a275550762c94543bbe165775804d7ab709dce20": "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 priceCents\n __typename\n}\nsubscription EventRegistrations($eventId: UUID!, $after: Datetime!) {\n eventRegistrations(eventId: $eventId) {\n registrations(after: $after) {\n ...EventPage_Registration\n quota {\n ...EventPage_Quota\n __typename\n }\n __typename\n }\n __typename\n }\n}", + "b78ccb2c8f90523ea273e051c83894e18168066d4c117484d1e585169d7e0986": "fragment HomePageClosedEvents_Query on Query {\n signupClosedEvents: events(\n first: $first\n offset: $offset\n filter: {signupClosed: {equalTo: true}, name: {containsKey: $language}}\n orderBy: EVENT_END_TIME_DESC\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n totalCount\n __typename\n }\n __typename\n}\nfragment HomePage_Event on Event {\n ...EventFields\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n category {\n ...EventPage_EventCategory\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Quota\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n registrations {\n totalCount\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 highlightText\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_Organization on Organization {\n id\n name\n slug\n color\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_Quota on Quota {\n id\n position\n title\n size\n priceCents\n __typename\n}\nquery HomePageEvents($offset: Int, $first: Int, $language: String) {\n ...HomePageClosedEvents_Query\n}", + "c57acae206812492a8b0dfd4e90543db58744bc4aa247c34d109f57544645dfa": "fragment HomePage_Query on Query {\n ...SharedLayout_Query\n signupOpenEvents: events(\n filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}, name: {containsKey: $language}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n __typename\n }\n signupUpcomingEvents: events(\n filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}, name: {containsKey: $language}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...HomePage_Event\n __typename\n }\n __typename\n }\n eventCategories {\n nodes {\n ...EventPage_EventCategory\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 HomePage_Event on Event {\n ...EventFields\n ownerOrganization {\n ...EventPage_Organization\n __typename\n }\n category {\n ...EventPage_EventCategory\n __typename\n }\n quotas(orderBy: POSITION_ASC) {\n nodes {\n ...EventPage_Quota\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n registrations {\n totalCount\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 highlightText\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_Organization on Organization {\n id\n name\n slug\n color\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_Quota on Quota {\n id\n position\n title\n size\n priceCents\n __typename\n}\nquery HomePage($language: String!) {\n ...HomePage_Query\n}", "f836d34508a8ee8ab07ca87bb086fe03dbddcf1fa40ffe912ef6143a843db460": "subscription CurrentTime {\n currentTime\n}", - "eb985e5bfabc266d0fc5637eda513cac8a293bc851b29e863dbf304c4932f7f1": "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}\nquery Shared {\n ...SharedLayout_Query\n}", + "4279223c3efdc362aae98e81e1cda66c7a006cafd8ca8245b4216028c12901ca": "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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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}\nquery Shared {\n ...SharedLayout_Query\n}", "29b135f119928bfc6de24b8aa6ec513ed62cb3cadf95eec1da607a3c760df7e9": "mutation AcceptOrganizationInvite($id: UUID!, $code: String) {\n acceptInvitationToOrganization(input: {invitationId: $id, code: $code}) {\n clientMutationId\n __typename\n }\n}", "61c018fcf82eca2de4bf2fe5ca833cbf1586808421b10428aa99ba75b028cc6c": "fragment EventPage_Organization on Organization {\n id\n name\n slug\n color\n __typename\n}\nmutation CreateOrganization($name: String!, $slug: String!, $color: String!) {\n createOrganization(input: {name: $name, slug: $slug, color: $color}) {\n organization {\n ...EventPage_Organization\n __typename\n }\n query {\n organizationBySlug(slug: $slug) {\n ...EventPage_Organization\n __typename\n }\n __typename\n }\n __typename\n }\n}", "39f623b7dd9b3111922c0937f5985ef32d8de76b88898b043daaf53dc20877b2": "mutation DeleteOrganization($organizationId: UUID!) {\n deleteOrganization(input: {organizationId: $organizationId}) {\n clientMutationId\n __typename\n }\n}", - "3d3ae0471e11f29477713606f9d884cb6d2a031b1a8bed9e220bec4c5e54337f": "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}\nquery InvitationDetail($id: UUID!, $code: String) {\n ...SharedLayout_Query\n organizationForInvitation(invitationId: $id, code: $code) {\n id\n name\n slug\n __typename\n }\n}", + "bffffd864222384112f122baf9c8fa57abf446e3ab2581427e4ebd7d283a1a49": "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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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}\nquery InvitationDetail($id: UUID!, $code: String) {\n ...SharedLayout_Query\n organizationForInvitation(invitationId: $id, code: $code) {\n id\n name\n slug\n __typename\n }\n}", + "cb08454007d6441f08369a59c8b3e3c32da61108fcc87ac4210cb7e77cef97e1": "mutation CreateCheckoutSession($updateToken: String!, $language: String) {\n createCheckoutSession(updateToken: $updateToken, language: $language) {\n url\n __typename\n }\n}", + "f46dd366f70bd59c89f7f201c1c3a704deab774b92ecad0f37c29d37d4cdb648": "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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 PayPage_RegistrationPayment on RegistrationPayment {\n eventId\n eventSlug\n eventName\n eventStartTime\n eventEndTime\n registrationEndTime\n quotaTitle\n firstName\n lastName\n queueStatus\n queuePosition\n status\n priceCents\n serviceFeeCents\n totalCents\n paidManually\n paidTotalCents\n paidAt\n blockedReason\n __typename\n}\nquery PayPage($updateToken: String!) {\n ...SharedLayout_Query\n paymentByUpdateToken(updateToken: $updateToken) {\n ...PayPage_RegistrationPayment\n __typename\n }\n}", "c3c63bf12e25e4025a986f94781d706f7adb2261e91689d356069378faec2c4a": "mutation ClaimRegistrationToken($input: ClaimRegistrationTokenInput!) {\n claimRegistrationToken(input: $input) {\n claimRegistrationTokenOutput {\n registrationToken\n updateToken\n __typename\n }\n __typename\n }\n}", - "c80a1b7e4a79510cd8e544910e72dec734223574011e0a40bb00c78de8de310c": "fragment CreateEventRegistrationPage_Query on Query {\n ...SharedLayout_Query\n eventBySlug(slug: $slug) {\n ...EventPage_Event\n __typename\n }\n quota(id: $quotaId) {\n ...EventPage_Quota\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 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_Quota on Quota {\n id\n position\n title\n size\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 CreateEventRegistrationPage($slug: String!, $quotaId: UUID!) {\n ...CreateEventRegistrationPage_Query\n}", - "e97c6726ce1d78c512935a15f46e8315e8ab2e50b2776d4fa1c92a5e8a54c566": "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 CreateEventRegistration($input: CreateRegistrationInput!) {\n createRegistration(input: $input) {\n registration {\n ...EventPage_Registration\n quota {\n ...EventPage_Quota\n __typename\n }\n event {\n id\n slug\n __typename\n }\n __typename\n }\n __typename\n }\n}", + "20fe542e08269ad0e1479f307ce17f1b04c59e48f2dd73139d36dbdeaef3e99a": "fragment CreateEventRegistrationPage_Query on Query {\n ...SharedLayout_Query\n currentUser {\n id\n firstName\n lastName\n registrationProfile {\n ...RegistrationProfile\n __typename\n }\n __typename\n }\n eventBySlug(slug: $slug) {\n ...EventPage_Event\n __typename\n }\n quota(id: $quotaId) {\n ...EventPage_Quota\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 RegistrationProfile on RegistrationProfile {\n userId\n telegram\n dietaryRestrictions\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 highlightText\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_Quota on Quota {\n id\n position\n title\n size\n priceCents\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 prefill\n __typename\n}\nquery CreateEventRegistrationPage($slug: String!, $quotaId: UUID!) {\n ...CreateEventRegistrationPage_Query\n}", + "282c98619013fc7f0e852cec433d21a04a36d1d07350d011424ac32a60d772c7": "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 priceCents\n __typename\n}\nmutation CreateEventRegistration($input: CreateRegistrationInput!) {\n createRegistration(input: $input) {\n registration {\n ...EventPage_Registration\n quota {\n ...EventPage_Quota\n __typename\n }\n event {\n id\n slug\n __typename\n }\n __typename\n }\n __typename\n }\n}", "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}", + "92fa1d7b23f5698f63d7fd93956a8531b95100abe24cb95ec3280c132e838d55": "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 paymentByUpdateToken(updateToken: $updateToken) {\n ...PayPage_RegistrationPayment\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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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 priceCents\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 highlightText\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 prefill\n __typename\n}\nfragment PayPage_RegistrationPayment on RegistrationPayment {\n eventId\n eventSlug\n eventName\n eventStartTime\n eventEndTime\n registrationEndTime\n quotaTitle\n firstName\n lastName\n queueStatus\n queuePosition\n status\n priceCents\n serviceFeeCents\n totalCents\n paidManually\n paidTotalCents\n paidAt\n blockedReason\n __typename\n}\nquery UpdateEventRegistrationPage($updateToken: String!) {\n ...UpdateEventRegistrationPage_Query\n}", + "11644b9a58d11149330a34204af8f15f758efccc09bcb64b231648f72877a357": "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 priceCents\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}", + "84dab768dd94228356723651b754e840eef05d581c712a4a00802656158d9db1": "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 enabledFeaturesList\n adminPreviewFeaturesList\n __typename\n}\nfragment SharedLayout_User on User {\n id\n name\n username\n avatarUrl\n isAdmin\n isDeveloper\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}", @@ -53,11 +68,17 @@ "953cdfb120682429839e878cb7f9e483d97dff06ed0d4eb80428cb98896c58fd": "mutation Logout {\n logout {\n success\n redirectTo\n __typename\n }\n}", "585b5baf970ccdcfc9031b3063524111fb24c972b41b6902e0b97c26eed8407d": "mutation MakeEmailPrimary($emailId: UUID!) {\n makeEmailPrimary(input: {emailId: $emailId}) {\n user {\n id\n userEmails(first: 50) {\n nodes {\n id\n isPrimary\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n}", "bb833917071d149b426642c0a8b641b629532a44f6c2ab3794a625f91e4d862e": "mutation PasswordStrength($password: String!) {\n calculatePasswordStrength(password: $password) {\n score\n feedback {\n suggestions\n __typename\n }\n __typename\n }\n}", + "40299daf2530066a9fdf98480092ba41a41f6d727ed35ca47e5d8a6c0002ce7e": "fragment RegistrationProfile on RegistrationProfile {\n userId\n telegram\n dietaryRestrictions\n __typename\n}\nquery RegistrationProfile {\n currentUser {\n id\n registrationProfile {\n ...RegistrationProfile\n __typename\n }\n __typename\n }\n}", + "cdd10e0c3b8b2adccafdf31b35c9e2eb9bdc64e89f7135c594b2f2c8277c4710": "fragment RegistrationProfile on RegistrationProfile {\n userId\n telegram\n dietaryRestrictions\n __typename\n}\nmutation SetRegistrationProfile($telegram: String, $dietaryRestrictions: String) {\n setRegistrationProfile(\n input: {telegram: $telegram, dietaryRestrictions: $dietaryRestrictions}\n ) {\n registrationProfile {\n ...RegistrationProfile\n __typename\n }\n __typename\n }\n}", + "c1fcbe61c9d0e1ce646b37939311ab12250ae1b8135853774796ccf215543502": "mutation DeleteRegistrationProfile {\n deleteRegistrationProfile(input: {}) {\n boolean\n __typename\n }\n}", "a15c749947f08c4c76e36aaa48042537e7f011318cb0424a67cceb336b8f1f7d": "mutation RequestAccountDeletion {\n requestAccountDeletion(input: {}) {\n success\n __typename\n }\n}", "91c3f0e452f0295520ee02ffbb79759b6a96cac6fc9ccaa514ffaa4e1ca8deba": "mutation ResendEmailVerification($emailId: UUID!) {\n resendEmailVerificationCode(input: {emailId: $emailId}) {\n success\n __typename\n }\n}", "0c6997c5a3b8b971a99c59a3ec6bd05d7fd24ff1aa3d7bbcc8a4bb0808de0ad7": "mutation ResetPassword($userId: UUID!, $token: String!, $password: String!) {\n resetPassword(\n input: {userId: $userId, resetToken: $token, newPassword: $password}\n ) {\n success\n __typename\n }\n}", "4ccd52e00c526690ac5b44ca911534e96f936acd4ff02a2785d9932bbe11ff6c": "query SettingsPassword {\n currentUser {\n id\n hasPassword\n primaryEmail\n __typename\n }\n}", "efef5d154b91120114a5ae97193bb83daee1223c150c8bda2d6655a47482fb70": "mutation UnlinkUserAuthentication($id: UUID!) {\n deleteUserAuthentication(input: {id: $id}) {\n user {\n id\n userAuthenticationsList(first: 50) {\n id\n identifier\n service\n createdAt\n __typename\n }\n __typename\n }\n __typename\n }\n}", "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441": "mutation UpdateUser($id: UUID!, $patch: UserPatch!) {\n updateUser(input: {id: $id, patch: $patch}) {\n clientMutationId\n user {\n id\n name\n username\n __typename\n }\n __typename\n }\n}", - "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1": "mutation VerifyEmail($id: UUID!, $token: String!) {\n verifyEmail(input: {userEmailId: $id, token: $token}) {\n success\n query {\n currentUser {\n id\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n}" + "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1": "mutation VerifyEmail($id: UUID!, $token: String!) {\n verifyEmail(input: {userEmailId: $id, token: $token}) {\n success\n query {\n currentUser {\n id\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n}", + "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvents {\n signupOpenEvents: events(\n filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n signupUpcomingEvents: events(\n filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n}", + "f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44": "query McpEventOptions {\n organizations {\n nodes {\n id\n name\n __typename\n }\n __typename\n }\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n id\n name\n ownerOrganization {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}", + "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvent($slug: String!) {\n currentUser {\n name\n primaryEmail\n __typename\n }\n eventBySlug(slug: $slug) {\n ...McpEventSummary\n description\n isDraft\n openQuotaSize\n quotas(orderBy: POSITION_ASC) {\n nodes {\n id\n title\n size\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n eventQuestions(orderBy: POSITION_ASC) {\n nodes {\n id\n type\n label\n isRequired\n data\n __typename\n }\n __typename\n }\n __typename\n }\n}" } \ No newline at end of file diff --git a/@app/lib/__tests__/forms.test.ts b/@app/lib/__tests__/forms.test.ts new file mode 100644 index 000000000..184945212 --- /dev/null +++ b/@app/lib/__tests__/forms.test.ts @@ -0,0 +1,19 @@ +import { ticketPriceEurosToCents } from "../src/forms" + +describe("ticketPriceEurosToCents", () => { + test.each([ + [undefined, 0], + [null, 0], + ["", 0], + [0, 0], + [0.25, 25], + [0.29, 29], + [18, 1800], + [19.99, 1999], + ["22.5", 2250], + // Input that isn't a number gives NaN (toBe compares with Object.is) + ["abc", NaN], + ])("%p € is %p cents", (euros, cents) => { + expect(ticketPriceEurosToCents(euros)).toBe(cents) + }) +}) diff --git a/@app/lib/__tests__/paymentStates.test.ts b/@app/lib/__tests__/paymentStates.test.ts new file mode 100644 index 000000000..d2113bb2b --- /dev/null +++ b/@app/lib/__tests__/paymentStates.test.ts @@ -0,0 +1,133 @@ +import { + isStripeCheckoutUrl, + payPageState, + quotaRequiresPayment, +} from "../src/paymentStates" + +describe("quotaRequiresPayment", () => { + test.each([ + [true, 1800, true], + [true, 25, true], + [true, 0, false], + [false, 1800, false], + [null, 1800, false], + [true, null, false], + ] as const)("enabled=%p price=%p → %p", (on, price, out) => { + expect(quotaRequiresPayment(on, price)).toBe(out) + }) +}) + +describe("payPageState", () => { + const unpaid = { status: "UNPAID" as const, paidManually: false } + const paid = { status: "PAID" as const, paidManually: false } + + test.each([ + // Payments disabled wins over everything + ["disabled, unpaid", false, unpaid, undefined, "disabled"], + ["disabled, no payment", false, null, undefined, "disabled"], + // Payments switched off: a settled payment still shows, Pay does not + [ + "switched off, unpaid", + true, + { ...unpaid, blockedReason: "PAYMENTS_DISABLED" }, + undefined, + "disabled", + ], + [ + "switched off, paid", + true, + { ...paid, blockedReason: "PAYMENTS_DISABLED" }, + undefined, + "paid", + ], + ["no payment", true, null, undefined, "notFound"], + ["undefined payment", true, undefined, undefined, "notFound"], + // Settled states + ["paid by card", true, paid, undefined, "paid"], + [ + "PAID, paid manually", + true, + { status: "PAID", paidManually: true }, + undefined, + "paidManually", + ], + [ + "PAID_MANUALLY", + true, + { status: "PAID_MANUALLY", paidManually: true }, + undefined, + "paidManually", + ], + [ + "not required", + true, + { status: "NOT_REQUIRED", paidManually: false }, + undefined, + "free", + ], + // Settled states ignore the return status + [ + "paid, returned with success", + true, + paid, + { returnStatus: "success" }, + "paid", + ], + // Blocked unpaid states + [ + "unpaid, in queue", + true, + { ...unpaid, blockedReason: "IN_QUEUE" }, + undefined, + "queued", + ], + [ + "unpaid, payment not open", + true, + { ...unpaid, blockedReason: "PAYMENT_NOT_OPEN" }, + undefined, + "opensLater", + ], + // Unpaid, cancelled and confirming + ["unpaid", true, unpaid, undefined, "unpaid"], + [ + "unpaid, returned cancelled", + true, + unpaid, + { returnStatus: "cancelled" }, + "unpaid", + ], + [ + "unpaid, returned with success", + true, + unpaid, + { returnStatus: "success" }, + "confirming", + ], + [ + "unpaid, confirming timed out", + true, + unpaid, + { returnStatus: "success", confirmTimedOut: true }, + "unpaid", + ], + ] as const)("%s → %p", (_name, enabled, payment, options, expected) => { + expect(payPageState(enabled, payment, options)).toBe(expected) + }) +}) + +describe("isStripeCheckoutUrl", () => { + test.each([ + ["https://checkout.stripe.com/c/pay/cs_test_123", true], + ["https://checkout.stripe.com", true], + ["http://checkout.stripe.com/c/pay/cs_test_123", false], + ["https://checkout.stripe.com.evil.example/c/pay", false], + ["https://evil.example/?https://checkout.stripe.com", false], + ["javascript:alert(1)", false], + ["not a url", false], + ["", false], + [null, false], + ])("%p → %p", (url, expected) => { + expect(isStripeCheckoutUrl(url)).toBe(expected) + }) +}) diff --git a/@app/lib/__tests__/payments.test.ts b/@app/lib/__tests__/payments.test.ts new file mode 100644 index 000000000..5c9f81acb --- /dev/null +++ b/@app/lib/__tests__/payments.test.ts @@ -0,0 +1,109 @@ +import { + formatEuro, + guildReceivesCents, + isValidTicketPriceCents, + MIN_PAID_PRICE_CENTS, + paymentsConfigured, + totalChargeCents, +} from "../src/payments" + +describe("fee constants", () => { + test("the minimum paid price meets Stripe's 0,50 € minimum charge", () => { + expect(totalChargeCents(MIN_PAID_PRICE_CENTS)).toBeGreaterThanOrEqual(50) + }) +}) + +describe("totalChargeCents", () => { + test.each([ + [0, 0], + [25, 50], + [1800, 1825], + [2200, 2225], + ])("%i cents → %i", (price, total) => { + expect(totalChargeCents(price)).toBe(total) + }) + + test.each([-1, 1.5, NaN, Infinity])("rejects %p", (price) => { + expect(() => totalChargeCents(price)).toThrow(RangeError) + }) +}) + +describe("guildReceivesCents", () => { + test.each([ + // free: nothing charged, nothing received + [0, 0], + // 25 − 0,015 × 50 = 24,25 + [25, 24], + // 1800 − 0,015 × 1825 = 1772,625 + [1800, 1773], + // 2200 − 0,015 × 2225 = 2166,625 + [2200, 2167], + // A 10,00 € ticket gives the guild ≈ 9,85 € + [1000, 985], + // 75 − 0,015 × 100 = 73,5 exactly: halves round up + [75, 74], + [275, 271], + ])("%i cents → %i", (price, received) => { + expect(guildReceivesCents(price)).toBe(received) + }) +}) + +describe("isValidTicketPriceCents", () => { + test.each([ + [0, true], + [1, false], + [24, false], + [25, true], + [1800, true], + [1000000, true], + [1000001, false], + [-25, false], + [25.5, false], + ])("%p → %p", (price, valid) => { + expect(isValidTicketPriceCents(price)).toBe(valid) + }) +}) + +describe("formatEuro", () => { + test.each([ + [0, "0,00 €"], + [5, "0,05 €"], + [25, "0,25 €"], + [1800, "18,00 €"], + [1825, "18,25 €"], + [2200, "22,00 €"], + [75912, "759,12 €"], + [123450, "1 234,50 €"], + [-1800, "-18,00 €"], + ])("%i cents → %p", (cents, text) => { + expect(formatEuro(cents)).toBe(text) + }) + + test("rejects fractional cents", () => { + expect(() => formatEuro(18.5)).toThrow(RangeError) + }) +}) + +describe("paymentsConfigured", () => { + const ALL_SET = { + STRIPE_SECRET_KEY: "sk_test_123", + STRIPE_WEBHOOK_SECRET: "whsec_123", + } + + test("is true when both secrets are set", () => { + expect(paymentsConfigured(ALL_SET)).toBe(true) + }) + + test.each([ + ["nothing is configured", {}], + ["STRIPE_SECRET_KEY is missing", { STRIPE_WEBHOOK_SECRET: "whsec_123" }], + ["STRIPE_WEBHOOK_SECRET is missing", { STRIPE_SECRET_KEY: "sk_test_123" }], + ["a secret is empty", { ...ALL_SET, STRIPE_SECRET_KEY: "" }], + ])("is false when %s", (_name, env) => { + expect(paymentsConfigured(env)).toBe(false) + }) + + test("ignores PAYMENTS_ENABLED", () => { + expect(paymentsConfigured({ ...ALL_SET, PAYMENTS_ENABLED: "0" })).toBe(true) + }) +}) diff --git a/@app/lib/__tests__/registrationForm.test.ts b/@app/lib/__tests__/registrationForm.test.ts new file mode 100644 index 000000000..777ecce89 --- /dev/null +++ b/@app/lib/__tests__/registrationForm.test.ts @@ -0,0 +1,401 @@ +import { + buildRegistrationInitialValues, + buildRegistrationProfileUpdate, + hasPrefillQuestions, +} from "../src/registrationForm" + +const user = (name: string | null, primaryEmail: string | null = null) => ({ + name, + primaryEmail, +}) + +const keycloakUser = ( + name: string | null, + firstName: string | null, + lastName: string | null +) => ({ name, primaryEmail: "anna@example.com", firstName, lastName }) + +describe("buildRegistrationInitialValues", () => { + it("returns empty values when nobody is signed in", () => { + expect(buildRegistrationInitialValues({ currentUser: null })).toStrictEqual( + { firstName: undefined, lastName: undefined, email: undefined } + ) + expect( + buildRegistrationInitialValues({ currentUser: undefined }) + ).toStrictEqual({ + firstName: undefined, + lastName: undefined, + email: undefined, + }) + }) + + it("prefills the email from the primary email", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user("Teemu Teekkari", "teemu@example.com"), + }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: "teemu@example.com", + }) + }) + + it("keeps a missing primary email as null", () => { + expect( + buildRegistrationInitialValues({ currentUser: user("Teemu Teekkari") }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: null, + }) + }) + + it("leaves the names empty when the user has no name", () => { + for (const name of [null, ""]) { + expect( + buildRegistrationInitialValues({ + currentUser: user(name, "a@example.com"), + }) + ).toStrictEqual({ + firstName: undefined, + lastName: undefined, + email: "a@example.com", + }) + } + }) + + it("uses a one-word name as the first name only", () => { + expect( + buildRegistrationInitialValues({ currentUser: user("Teemu") }) + ).toMatchObject({ firstName: "Teemu", lastName: undefined }) + }) + + it("takes the first two words of a longer name", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user("Anna Maria von Wright"), + }) + ).toMatchObject({ firstName: "Anna", lastName: "Maria" }) + }) + + it("splits on single spaces without trimming", () => { + expect( + buildRegistrationInitialValues({ currentUser: user(" Teemu Teekkari") }) + ).toMatchObject({ firstName: "", lastName: "Teemu" }) + expect( + buildRegistrationInitialValues({ currentUser: user("Teemu Teekkari") }) + ).toMatchObject({ firstName: "Teemu", lastName: "" }) + expect( + buildRegistrationInitialValues({ currentUser: user("Teemu\tTeekkari") }) + ).toMatchObject({ firstName: "Teemu\tTeekkari", lastName: undefined }) + }) + + it("does not prefill answers from the questions", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user("Teemu Teekkari", "teemu@example.com"), + questions: [{ id: "q1" }, { id: "q2" }], + }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: "teemu@example.com", + }) + }) + + it("ignores the Keycloak names while keycloak_names is off", () => { + for (const features of [ + undefined, + {}, + { keycloak_names: false }, + ] as const) { + expect( + buildRegistrationInitialValues({ + currentUser: keycloakUser( + "Anna Maria von Wright", + "Anna Maria", + "von Wright" + ), + features, + }) + ).toStrictEqual({ + firstName: "Anna", + lastName: "Maria", + email: "anna@example.com", + }) + } + }) + + describe("with keycloak_names on", () => { + const features = { keycloak_names: true } + + it("returns empty values when nobody is signed in", () => { + expect( + buildRegistrationInitialValues({ currentUser: null, features }) + ).toStrictEqual({ + firstName: undefined, + lastName: undefined, + email: undefined, + }) + }) + + it("prefers the Keycloak first and last name", () => { + expect( + buildRegistrationInitialValues({ + currentUser: keycloakUser( + "Anna Maria von Wright", + "Anna Maria", + "von Wright" + ), + features, + }) + ).toStrictEqual({ + firstName: "Anna Maria", + lastName: "von Wright", + email: "anna@example.com", + }) + }) + + it("uses the display name unless both Keycloak names are known", () => { + for (const [firstName, lastName] of [ + [null, null], + ["Anna", null], + [null, "Wright"], + ["", "Wright"], + ]) { + expect( + buildRegistrationInitialValues({ + currentUser: keycloakUser("Teemu Teekkari", firstName, lastName), + features, + }) + ).toMatchObject({ firstName: "Teemu", lastName: "Teekkari" }) + } + }) + + it("uses a display name of at most two words", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user("Teemu Teekkari", "teemu@example.com"), + features, + }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: "teemu@example.com", + }) + expect( + buildRegistrationInitialValues({ currentUser: user("Teemu"), features }) + ).toMatchObject({ firstName: "Teemu", lastName: undefined }) + }) + + it("leaves the names empty for a display name of three or more words", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user("Anna Maria von Wright", "anna@example.com"), + features, + }) + ).toStrictEqual({ + firstName: undefined, + lastName: undefined, + email: "anna@example.com", + }) + expect( + buildRegistrationInitialValues({ + currentUser: user("Anna Maria Wright"), + features, + }) + ).toMatchObject({ firstName: undefined, lastName: undefined }) + }) + + it("trims the display name and splits it on any whitespace", () => { + expect( + buildRegistrationInitialValues({ + currentUser: user(" Teemu Teekkari "), + features, + }) + ).toMatchObject({ firstName: "Teemu", lastName: "Teekkari" }) + expect( + buildRegistrationInitialValues({ + currentUser: user("Teemu\tTeekkari"), + features, + }) + ).toMatchObject({ firstName: "Teemu", lastName: "Teekkari" }) + expect( + buildRegistrationInitialValues({ + currentUser: user(" Anna Maria\nWright "), + features, + }) + ).toMatchObject({ firstName: undefined, lastName: undefined }) + }) + + it("leaves the names empty for a blank display name", () => { + for (const name of [null, "", " "]) { + expect( + buildRegistrationInitialValues({ currentUser: user(name), features }) + ).toMatchObject({ firstName: undefined, lastName: undefined }) + } + }) + }) +}) + +const profileUser = { + name: "Teemu Teekkari", + primaryEmail: "teemu@example.com", + registrationProfile: { telegram: "@teemu", dietaryRestrictions: "Vegan" }, +} + +const prefillQuestions = [ + { id: "q-telegram", prefill: "TELEGRAM" }, + { id: "q-plain", prefill: null }, + { id: "q-diet", prefill: "DIETARY_RESTRICTIONS" }, +] + +describe("buildRegistrationInitialValues answer prefill", () => { + it("does not prefill answers while prefill_answers is off", () => { + for (const features of [ + undefined, + {}, + { prefill_answers: false }, + ] as const) { + expect( + buildRegistrationInitialValues({ + currentUser: profileUser, + questions: prefillQuestions, + features, + }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: "teemu@example.com", + }) + } + }) + + describe("with prefill_answers on", () => { + const features = { prefill_answers: true } + + it("prefills the questions marked for prefill from the profile", () => { + expect( + buildRegistrationInitialValues({ + currentUser: profileUser, + questions: prefillQuestions, + features, + }) + ).toStrictEqual({ + firstName: "Teemu", + lastName: "Teekkari", + email: "teemu@example.com", + answers: { "q-telegram": "@teemu", "q-diet": "Vegan" }, + }) + }) + + it("leaves out fields the profile does not have", () => { + expect( + buildRegistrationInitialValues({ + currentUser: { + ...profileUser, + registrationProfile: { telegram: null, dietaryRestrictions: "" }, + }, + questions: prefillQuestions, + features, + }) + ).not.toHaveProperty("answers") + expect( + buildRegistrationInitialValues({ + currentUser: { + ...profileUser, + registrationProfile: { telegram: "@teemu" }, + }, + questions: prefillQuestions, + features, + }).answers + ).toStrictEqual({ "q-telegram": "@teemu" }) + }) + + it("prefills nothing without a profile or a signed-in user", () => { + for (const currentUser of [ + null, + { ...profileUser, registrationProfile: null }, + ]) { + expect( + buildRegistrationInitialValues({ + currentUser, + questions: prefillQuestions, + features, + }) + ).not.toHaveProperty("answers") + } + }) + + it("ignores unknown prefill values", () => { + expect( + buildRegistrationInitialValues({ + currentUser: profileUser, + questions: [{ id: "q1", prefill: "SHOE_SIZE" }], + features, + }) + ).not.toHaveProperty("answers") + }) + }) +}) + +describe("hasPrefillQuestions", () => { + it("is true only when a question is marked for prefill", () => { + expect(hasPrefillQuestions(prefillQuestions)).toBe(true) + expect(hasPrefillQuestions([{ id: "q1", prefill: null }])).toBe(false) + expect(hasPrefillQuestions([{ id: "q1" }])).toBe(false) + expect(hasPrefillQuestions(null)).toBe(false) + }) +}) + +describe("buildRegistrationProfileUpdate", () => { + it("returns the trimmed answers of the prefill questions", () => { + expect( + buildRegistrationProfileUpdate(prefillQuestions, { + "q-telegram": " @teemu ", + "q-plain": "something else", + "q-diet": "Vegan", + }) + ).toStrictEqual({ telegram: "@teemu", dietaryRestrictions: "Vegan" }) + }) + + it("keeps fields the event does not ask for as null", () => { + expect( + buildRegistrationProfileUpdate( + [{ id: "q-telegram", prefill: "TELEGRAM" }], + { + "q-telegram": "@teemu", + } + ) + ).toStrictEqual({ telegram: "@teemu", dietaryRestrictions: null }) + }) + + it("clears a field whose answer was left empty", () => { + expect( + buildRegistrationProfileUpdate(prefillQuestions, { "q-diet": "Vegan" }) + ).toStrictEqual({ telegram: "", dietaryRestrictions: "Vegan" }) + }) + + it("leaves out an over-length answer", () => { + expect( + buildRegistrationProfileUpdate(prefillQuestions, { + "q-telegram": "@" + "a".repeat(64), + "q-diet": "d".repeat(1000), + }) + ).toStrictEqual({ telegram: null, dietaryRestrictions: "d".repeat(1000) }) + expect( + buildRegistrationProfileUpdate( + [{ id: "q-telegram", prefill: "TELEGRAM" }], + { "q-telegram": "@" + "a".repeat(64) } + ) + ).toBeNull() + }) + + it("returns null when no question is marked for prefill", () => { + expect( + buildRegistrationProfileUpdate([{ id: "q-plain" }], { "q-plain": "x" }) + ).toBeNull() + expect(buildRegistrationProfileUpdate(undefined, undefined)).toBeNull() + }) +}) diff --git a/@app/lib/__tests__/tableUtils.test.ts b/@app/lib/__tests__/tableUtils.test.ts new file mode 100644 index 000000000..cca09944e --- /dev/null +++ b/@app/lib/__tests__/tableUtils.test.ts @@ -0,0 +1,97 @@ +import { downloadRegistrations } from "../src/tableUtils" + +import type { + EventPage_QuestionFragment, + ListEventRegistrations_RegistrationFragment, +} from "@app/graphql" + +const questions = [ + { id: "q1", label: { fi: "Ruokavalio", en: "Diet" } }, +] as unknown as EventPage_QuestionFragment[] + +function registration( + overrides: Partial = {} +) { + return { + id: "r1", + fullName: "Aino Virtanen", + email: "aino@example.com", + answers: { q1: "Vegan" }, + isFinished: true, + status: "IN_QUOTA", + position: 1, + paymentStatus: "PAID", + createdAt: "2026-10-17T12:00:00Z", + updatedAt: "2026-10-17T12:00:00Z", + quota: { + id: "quota1", + position: 0, + title: { fi: "Jäsenet" }, + size: 10, + priceCents: 1800, + }, + ...overrides, + } as unknown as ListEventRegistrations_RegistrationFragment +} + +describe("downloadRegistrations", () => { + test("leaves out payment columns by default", () => { + const [row] = downloadRegistrations(questions)([registration()]) + expect(Object.keys(row)).toEqual([ + "fullName", + "email", + "status", + "position", + "quota", + "Ruokavalio", + ]) + }) + + test("adds payment status and price after the quota when asked to", () => { + const [row] = downloadRegistrations(questions, { includePayments: true })([ + registration(), + ]) + expect(Object.keys(row)).toEqual([ + "fullName", + "email", + "status", + "position", + "quota", + "paymentStatus", + "price", + "Ruokavalio", + ]) + expect(row).toMatchObject({ + quota: "Jäsenet", + paymentStatus: "PAID", + price: "18,00 €", + Ruokavalio: "Vegan", + }) + + const [labelled] = downloadRegistrations(questions, { + includePayments: true, + paymentStatusLabel: (status) => `label:${status}`, + })([registration()]) + expect(labelled).toMatchObject({ paymentStatus: "label:PAID" }) + }) + + test("writes empty payment cells for a free quota without a status", () => { + const free = registration({ paymentStatus: null }) + const [row] = downloadRegistrations(questions, { includePayments: true })([ + { ...free, quota: { ...free.quota!, priceCents: 0 } }, + ]) + expect(row).toMatchObject({ paymentStatus: "", price: "" }) + }) + + test("keeps a question labelled like a payment column", () => { + const [row] = downloadRegistrations( + [{ ...questions[0], label: { fi: "price", en: "price" } }], + { includePayments: true } + )([registration()]) + expect(row).toMatchObject({ + price: "Vegan", + "price (Ilmo)": "18,00 €", + paymentStatus: "PAID", + }) + }) +}) diff --git a/@app/lib/jest.config.ts b/@app/lib/jest.config.ts new file mode 100644 index 000000000..9bc2d71a8 --- /dev/null +++ b/@app/lib/jest.config.ts @@ -0,0 +1,3 @@ +module.exports = { + ...require("../../jest.config.base")(__dirname), +} 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/featureFlags.ts b/@app/lib/src/featureFlags.ts new file mode 100644 index 000000000..c722517b8 --- /dev/null +++ b/@app/lib/src/featureFlags.ts @@ -0,0 +1,132 @@ +/** + * The registry of runtime feature flags. + * + * Every key here has a row in `app_public.feature_flags`, inserted by the + * migration that introduces the feature, and a database test fails when the + * two disagree. The database is authoritative: `app_public.feature_enabled()` + * decides whether a feature is on, and the code on every tier asks it through + * `useFeature` / `` (client), `isFeatureEnabled` (server) and + * `withFeature` (worker). A key that is missing from the table reads as off. + * + * Adding a feature is one entry: + * + * my_feature: { + * description: "What the flag gates", + * // Only for features that need server configuration. The server marks + * // the flag unavailable at boot unless every variable is non-empty. + * requiresEnv: ["MY_SERVICE_SECRET"], + * // Only for features without anything a signed-in admin can see. + * adminPreview: false, + * }, + * + * The Features page (/admin/features) names the flag from the optional + * translations under `features.flags.` in the client's admin.json: + * `name`, `turnOn` (what everyone starts seeing), `stops` and `keeps` (what + * turning it off ends and what keeps working) and `notConfigured`. Without + * them it shows the key and generic texts. + * + * Removing a flag starts by deleting its entry: `FeatureKey` then no longer + * accepts the key, so the compiler lists every gate that still names it. + */ + +export interface FeatureDefinition { + /** What the flag gates. Shown to developers next to the switch. */ + readonly description: string + /** + * Environment variables the server needs for this feature. When any of them + * is missing or empty the server records the flag as unavailable, and the + * feature reads as off whatever its state. + */ + readonly requiresEnv?: readonly string[] + /** + * False for a feature that has nothing a signed-in admin could preview: it + * only serves outside callers or runs in the server or worker, where + * Admins only reads as off. The Features page then does not offer Admins + * only for it. + */ + readonly adminPreview?: false +} + +export const FEATURES = { + keycloak_names: { + description: + "Prefill the registration form with the first and last name from Keycloak instead of splitting the display name.", + }, + typed_time_input: { + description: + "Typed hour, minute and second boxes for the event and registration times in the event form, and default times when a day is clicked.", + }, + event_templates: { + description: + "Event templates in the event form: template selectors and ready-made quotas and questions.", + }, + form_preview: { + description: "Registration form preview tab in the event form.", + }, + confetti: { + description: "Confetti after an event or a registration has been created.", + }, + ribbon_text: { + description: "Custom ribbon text for highlighted events.", + }, + calendar_invites: { + description: + "Calendar invitation in registration emails and calendar links after signing up.", + }, + registration_reminders: { + description: + "Reminders before registration opens: the reminder button, reminder settings and reminder emails.", + }, + telegram_reminders: { + description: + "Registration reminders through the Telegram bot, and linking a Telegram account.", + requiresEnv: ["TELEGRAM_BOT_TOKEN"], + }, + mcp_server: { + description: + "MCP server at /mcp for AI assistants: browse events, register, and let admins create draft events.", + requiresEnv: ["KEYCLOAK_ISSUER"], + // /mcp is called by MCP clients, not from an admin's browser session + adminPreview: false, + }, + payments: { + description: + "Stripe payments for paid quotas: prices, the pay page, Checkout, organizer payment tools and payment emails.", + requiresEnv: ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"], + }, + prefill_answers: { + description: + "Prefill Telegram and dietary restriction answers from a registration profile the user saves on request.", + }, +} as const satisfies Record + +export type FeatureKey = keyof typeof FEATURES + +/** The states of `app_public.feature_state`, as stored in the database. */ +export type FeatureFlagState = "off" | "admins_only" | "on" + +export const FEATURE_FLAG_STATES: readonly FeatureFlagState[] = [ + "off", + "admins_only", + "on", +] + +/** Every key in the registry. */ +export const featureKeys = (): FeatureKey[] => + Object.keys(FEATURES) as FeatureKey[] + +/** + * Whether Admins only lets admins preview a feature. Keys outside the + * registry can be previewed. + */ +export const featureAdminPreview = (key: string): boolean => + (FEATURES as Record)[key]?.adminPreview !== false + +/** + * Whether the environment holds every variable a feature requires. Features + * without requirements are always configured. + */ +export const featureConfigured = ( + definition: FeatureDefinition, + env: Record +): boolean => (definition.requiresEnv ?? []).every((name) => Boolean(env[name])) diff --git a/@app/lib/src/forms.ts b/@app/lib/src/forms.ts index 526d30df3..dbd69018d 100644 --- a/@app/lib/src/forms.ts +++ b/@app/lib/src/forms.ts @@ -34,3 +34,23 @@ export const registrationFormItemLayout = { sm: { span: 12 }, }, } + +/** + * Converts a ticket price entered in euros (the event form's price input) to + * integer cents. An empty input means a free ticket. Returns NaN for input + * that isn't a number, which isValidTicketPriceCents rejects. + */ +export function ticketPriceEurosToCents( + euros: number | string | null | undefined +): number { + if (euros === null || euros === undefined || euros === "") return 0 + const value = typeof euros === "number" ? euros : Number(euros) + return Math.round(value * 100) +} + +/** Converts integer cents to euros for the event form's price input. */ +export function ticketPriceCentsToEuros( + cents: number | null | undefined +): number | undefined { + return cents === null || cents === undefined ? undefined : cents / 100 +} diff --git a/@app/lib/src/index.ts b/@app/lib/src/index.ts index d6b5b3c89..eb6a4d7a0 100644 --- a/@app/lib/src/index.ts +++ b/@app/lib/src/index.ts @@ -1,9 +1,14 @@ +export * from "./calendar" export * from "./colors" export * from "./constants" export * from "./cookies" export * from "./dates" export * from "./errors" +export * from "./featureFlags" export * from "./forms" +export * from "./payments" +export * from "./paymentStates" +export * from "./registrationForm" export * from "./sso" export * from "./tableUtils" export * from "./types" diff --git a/@app/lib/src/paymentStates.ts b/@app/lib/src/paymentStates.ts new file mode 100644 index 000000000..2d7d427a8 --- /dev/null +++ b/@app/lib/src/paymentStates.ts @@ -0,0 +1,84 @@ +/** + * Participant-facing payment states: whether the registration form shows + * the payment notice and which state the /pay page shows. Pure functions so + * the UI decisions are unit tested; amounts are integer cents. + */ +type PaymentStatus = "NOT_REQUIRED" | "UNPAID" | "PAID" | "PAID_MANUALLY" + +/** + * True when registering in this quota costs money: payments are on and the + * ticket is not free. The registration form then says that the payment link + * comes by email when registration closes. + */ +export function quotaRequiresPayment( + paymentsEnabled: boolean | null | undefined, + priceCents: number | null | undefined +): boolean { + return !!paymentsEnabled && (priceCents ?? 0) > 0 +} + +export type PayPageState = + | "disabled" + | "notFound" + | "unpaid" + | "confirming" + | "paid" + | "paidManually" + | "queued" + | "opensLater" + | "free" + +export interface PayPagePayment { + status: PaymentStatus + paidManually: boolean + blockedReason?: string | null +} + +/** + * The state the /pay page shows (boards 4 and 5). `returnStatus` is the + * `status` query parameter Stripe redirects back with; after `success` the + * page shows "confirming" until the webhook has marked the payment paid, or + * until `confirmTimedOut`. A payment that exists is shown while payments are + * switched off; only Pay is replaced by "disabled" (blockedReason + * PAYMENTS_DISABLED). + */ +export function payPageState( + paymentsEnabled: boolean | null | undefined, + payment: PayPagePayment | null | undefined, + { + returnStatus, + confirmTimedOut = false, + }: { returnStatus?: string | null; confirmTimedOut?: boolean } = {} +): PayPageState { + if (!paymentsEnabled) return "disabled" + if (!payment) return "notFound" + switch (payment.status) { + case "PAID_MANUALLY": + return "paidManually" + case "PAID": + return payment.paidManually ? "paidManually" : "paid" + case "NOT_REQUIRED": + return "free" + } + if (payment.blockedReason === "PAYMENTS_DISABLED") return "disabled" + if (payment.blockedReason === "IN_QUEUE") return "queued" + if (payment.blockedReason === "PAYMENT_NOT_OPEN") return "opensLater" + if (returnStatus === "success" && !confirmTimedOut) return "confirming" + return "unpaid" +} + +const STRIPE_CHECKOUT_ORIGIN = "https://checkout.stripe.com" + +/** + * True for a Stripe Checkout page URL. The client only redirects to URLs + * that pass this check, so a bad server response can't send people + * elsewhere. + */ +export function isStripeCheckoutUrl(url: string | null | undefined): boolean { + if (!url) return false + try { + return new URL(url).origin === STRIPE_CHECKOUT_ORIGIN + } catch { + return false + } +} diff --git a/@app/lib/src/payments.ts b/@app/lib/src/payments.ts new file mode 100644 index 000000000..aa067cde9 --- /dev/null +++ b/@app/lib/src/payments.ts @@ -0,0 +1,115 @@ +import { featureConfigured, FEATURES } from "./featureFlags" + +/** + * Stripe payments: the configuration check and the fee maths shared by the + * server, the worker and the client. Money is always integer cents; only + * `formatEuro` turns it into text. + */ + +/** + * Whether this process has both Stripe secrets (`requiresEnv` of the + * `payments` flag). A partial configuration counts as not configured. + * + * This says whether Stripe can be called, not whether payments are on: that + * is the `payments` feature flag, which the server marks unavailable when + * this is false. Code that needs Stripe for payments already in flight (the + * webhook) checks only this. + */ +export function paymentsConfigured( + env: Record = process.env +): boolean { + return featureConfigured(FEATURES.payments, env) +} + +/** + * Stripe's fixed per-payment fee, charged to the customer as a separate + * "service fee" line item at Checkout. + */ +export const SERVICE_FEE_CENTS = 25 + +/** Stripe's percentage fee, taken from the total charge. */ +export const STRIPE_PERCENT_FEE = 0.015 + +/** + * The smallest non-zero ticket price. Together with the service fee it makes + * the total charge reach Stripe's 0,50 € minimum. + */ +export const MIN_PAID_PRICE_CENTS = 25 + +/** + * The largest ticket price, 10 000 €. The database enforces the same bound + * on quotas.price_cents. + */ +export const MAX_TICKET_PRICE_CENTS = 1_000_000 + +// The percentage fee in per-mille, so the maths below stays in integers. +const STRIPE_PERCENT_FEE_PER_MILLE = Math.round(STRIPE_PERCENT_FEE * 1000) + +function assertCents(cents: number, name: string): void { + if (!Number.isSafeInteger(cents) || cents < 0) { + throw new RangeError( + `${name} must be a non-negative integer number of cents, got ${cents}` + ) + } +} + +/** + * A ticket price is valid when it is free (0) or between + * `MIN_PAID_PRICE_CENTS` and `MAX_TICKET_PRICE_CENTS`. + */ +export function isValidTicketPriceCents(priceCents: number): boolean { + return ( + Number.isSafeInteger(priceCents) && + (priceCents === 0 || + (priceCents >= MIN_PAID_PRICE_CENTS && + priceCents <= MAX_TICKET_PRICE_CENTS)) + ) +} + +/** + * What the customer pays at Checkout: the ticket price plus the service fee. + * A free ticket is never charged, so it costs 0. + */ +export function totalChargeCents(priceCents: number): number { + assertCents(priceCents, "priceCents") + if (priceCents === 0) return 0 + return priceCents + SERVICE_FEE_CENTS +} + +/** + * What the guild receives for a ticket: Stripe keeps the service fee plus + * 1,5 % of the total charge, so the guild gets + * `P − 1,5 % × (P + 0,25 €)`, rounded to the nearest cent (halves up). + * 0 for a free ticket. + * + * Computed as `(985·P − 375) / 1000` so the only floating point step is one + * correctly rounded division: an exact half stays an exact half and rounds + * up, instead of landing a hair either side of it. + */ +export function guildReceivesCents(priceCents: number): number { + assertCents(priceCents, "priceCents") + if (priceCents === 0) return 0 + const numerator = + 1000 * priceCents - + STRIPE_PERCENT_FEE_PER_MILLE * (priceCents + SERVICE_FEE_CENTS) + return Math.round(numerator / 1000) +} + +/** + * Formats cents as euros in the style of the designs, e.g. `18,00 €`. + * Every language uses the Finnish decimal comma and a trailing euro sign; + * thousands are grouped with a space (`1 234,50 €`). `lang` is accepted so + * call sites need not change if a locale ever needs its own format. + */ +export function formatEuro(cents: number, _lang?: string): string { + if (!Number.isSafeInteger(cents)) { + throw new RangeError(`cents must be an integer, got ${cents}`) + } + const sign = cents < 0 ? "-" : "" + const abs = Math.abs(cents) + const euros = Math.floor(abs / 100) + .toString() + .replace(/\B(?=(\d{3})+(?!\d))/g, " ") + const rest = (abs % 100).toString().padStart(2, "0") + return `${sign}${euros},${rest} €` +} diff --git a/@app/lib/src/registrationForm.ts b/@app/lib/src/registrationForm.ts new file mode 100644 index 000000000..54d47e48f --- /dev/null +++ b/@app/lib/src/registrationForm.ts @@ -0,0 +1,205 @@ +import type { FeatureKey } from "./featureFlags" + +/** + * The parts of the signed-in user that the registration form is prefilled + * from. Structural, so that any query selecting these fields can pass its + * `currentUser` as is. + */ +export interface RegistrationPrefillUser { + name?: string | null + primaryEmail?: string | null + /** First name(s) from Keycloak; null for accounts that never used it. */ + firstName?: string | null + /** Last name from Keycloak; null for accounts that never used it. */ + lastName?: string | null + /** The answer defaults the user has saved; only readable by the user. */ + registrationProfile?: RegistrationProfileValues | null +} + +/** The fields of `app_public.registration_profiles` that prefill answers. */ +export interface RegistrationProfileValues { + telegram?: string | null + dietaryRestrictions?: string | null +} + +/** + * The values of `app_public.question_prefill`: which registration profile + * field an event question asks for. + */ +export type QuestionPrefillField = "TELEGRAM" | "DIETARY_RESTRICTIONS" + +/** The registration profile field each prefill question reads and writes. */ +export const QUESTION_PREFILL_PROFILE_FIELDS: Readonly< + Record +> = { + TELEGRAM: "telegram", + DIETARY_RESTRICTIONS: "dietaryRestrictions", +} + +/** A question of the event the registration form is shown for. */ +export interface RegistrationPrefillQuestion { + id: string + /** Set on TEXT questions whose answer comes from the registration profile. */ + prefill?: string | null +} + +const profileFieldOf = ( + question: RegistrationPrefillQuestion +): keyof RegistrationProfileValues | undefined => + question.prefill + ? QUESTION_PREFILL_PROFILE_FIELDS[question.prefill as QuestionPrefillField] + : undefined + +export interface RegistrationPrefillInput { + /** The signed-in user, or null/undefined when signed out or loading. */ + currentUser?: RegistrationPrefillUser | null + /** + * The questions of the event. Questions marked for prefill get their + * answer from the user's registration profile. + */ + questions?: readonly RegistrationPrefillQuestion[] | null + /** + * The feature flags that change the prefill, as read by the caller (for + * example with `useFeature`). A missing key reads as off. + */ + features?: Partial> +} + +export interface RegistrationInitialValues { + firstName: string | undefined + lastName: string | undefined + email: string | null | undefined + /** + * Answers by question id. Present only when at least one answer is + * prefilled. + */ + answers?: Record +} + +type NamePair = [string | undefined, string | undefined] + +/** + * Splits the display name on single spaces: the first part is the first name + * and the second part the last name. Any further parts are dropped. + */ +const splitDisplayName = (name: string | null | undefined): NamePair => { + const [firstName, lastName] = name ? name.split(" ") : [] + return [firstName, lastName] +} + +/** + * The first and last name from Keycloak when both are known. Otherwise the + * display name, trimmed and split on whitespace, but only when it has at most + * two words: with three or more ("Anna Maria von Wright") there is no telling + * where the first name ends, so the names are left for the user to fill in. + */ +const keycloakOrUnambiguousName = (user: RegistrationPrefillUser): NamePair => { + if (user.firstName && user.lastName) { + return [user.firstName, user.lastName] + } + const trimmed = user.name?.trim() + const parts = trimmed ? trimmed.split(/\s+/) : [] + if (parts.length > 2) { + return [undefined, undefined] + } + return [parts[0], parts[1]] +} + +/** + * Answers to the questions marked for prefill, from the registration profile. + * Questions without a saved value are left out. + */ +const prefilledAnswers = ( + questions: readonly RegistrationPrefillQuestion[] | null | undefined, + profile: RegistrationProfileValues | null | undefined +): Record => { + const answers: Record = {} + for (const question of questions ?? []) { + const field = profileFieldOf(question) + const value = field ? profile?.[field] : undefined + if (value) { + answers[question.id] = value + } + } + return answers +} + +/** + * The initial values of the registration form for a new registration. + * + * Without the `keycloak_names` feature the first and last name are inferred + * from the user's display name by splitting it on single spaces. With it, + * the Keycloak first and last name are preferred, and the display name is + * used only when it splits unambiguously. The email is the primary email. + * With the `prefill_answers` feature, answers to questions marked for prefill + * come from the user's registration profile. + * + * Pure: the register page memoises the result, so the form is only reset + * when the inputs change. + */ +export const buildRegistrationInitialValues = ({ + currentUser, + questions, + features, +}: RegistrationPrefillInput): RegistrationInitialValues => { + const user = currentUser || {} + const [firstName, lastName] = features?.keycloak_names + ? keycloakOrUnambiguousName(user) + : splitDisplayName(user.name) + const answers = features?.prefill_answers + ? prefilledAnswers(questions, user.registrationProfile) + : {} + + return { + firstName, + lastName, + email: user.primaryEmail, + ...(Object.keys(answers).length > 0 ? { answers } : {}), + } +} + +/** The longest value each registration profile field accepts. */ +export const REGISTRATION_PROFILE_MAX_LENGTHS: Readonly< + Record +> = { + telegram: 64, + dietaryRestrictions: 1000, +} + +/** Whether any of the questions is marked for prefill. */ +export const hasPrefillQuestions = ( + questions: readonly RegistrationPrefillQuestion[] | null | undefined +): boolean => (questions ?? []).some((question) => !!profileFieldOf(question)) + +/** + * The arguments of `setRegistrationProfile` that remember the answers given + * to the questions marked for prefill, for when the registrant ticks + * "remember these answers". Only the fields the event asks for are set, the + * others stay null (keep the saved value). An empty answer clears the saved + * value. An answer longer than the profile accepts is left out, so that it + * does not overwrite the saved value. Null when there is nothing to save. + */ +export const buildRegistrationProfileUpdate = ( + questions: readonly RegistrationPrefillQuestion[] | null | undefined, + answers: Record | null | undefined +): { telegram: string | null; dietaryRestrictions: string | null } | null => { + const update: { + telegram: string | null + dietaryRestrictions: string | null + } = { telegram: null, dietaryRestrictions: null } + let changed = false + for (const question of questions ?? []) { + const field = profileFieldOf(question) + if (!field || update[field] !== null) { + continue + } + const answer = answers?.[question.id] + const value = typeof answer === "string" ? answer.trim() : "" + if (value.length > REGISTRATION_PROFILE_MAX_LENGTHS[field]) { + continue + } + update[field] = value + changed = true + } + return changed ? update : null +} diff --git a/@app/lib/src/tableUtils.ts b/@app/lib/src/tableUtils.ts index 8a4697a67..b6d369b13 100644 --- a/@app/lib/src/tableUtils.ts +++ b/@app/lib/src/tableUtils.ts @@ -4,7 +4,9 @@ import { } from "@app/graphql" import dayjs from "dayjs" -import { CsvRow, filterObjectByKeys } from "." +import { formatEuro } from "./payments" +import { CsvRow } from "./types" +import { filterObjectByKeys } from "./utils" /** * Table utils @@ -43,9 +45,56 @@ const registrationColsToDownload = [ "answers", ] +interface DownloadRegistrationsOptions { + /** + * Adds the payment status and ticket price columns. Only set when payments + * are on and the event has a paid quota, so the CSV is unchanged otherwise. + */ + includePayments?: boolean + /** + * The text written for a payment status (for example a translated label); + * the raw status (PAID, PAID_MANUALLY, ...) by default. + */ + paymentStatusLabel?: (status: string) => string +} + +/** + * Returns a copy of a CSV row with the payment status and ticket price columns + * inserted right after the quota column, before the answer columns. A + * question whose label is already "paymentStatus" or "price" keeps its + * column; the payment column then gets a " (Ilmo)" suffix. + */ +function withPaymentColumns( + row: Record, + registration: ListEventRegistrations_RegistrationFragment, + paymentStatusLabel: (status: string) => string +) { + const columnName = (name: string) => (name in row ? `${name} (Ilmo)` : name) + const paymentColumns = { + [columnName("paymentStatus")]: registration.paymentStatus + ? paymentStatusLabel(registration.paymentStatus) + : "", + [columnName("price")]: registration.quota?.priceCents + ? formatEuro(registration.quota.priceCents) + : "", + } + return Object.keys(row).reduce( + (acc, key) => + key === "quota" + ? { ...acc, [key]: row[key], ...paymentColumns } + : { ...acc, [key]: row[key] }, + {} as Record + ) +} + export function downloadRegistrations( - questions: EventPage_QuestionFragment[] | undefined + questions: EventPage_QuestionFragment[] | undefined, + options: DownloadRegistrationsOptions = {} ) { + const { + includePayments = false, + paymentStatusLabel = (status: string) => status, + } = options return (data: ListEventRegistrations_RegistrationFragment[]) => { return data.reduce((acc, cur) => { if (cur.isFinished) { @@ -72,7 +121,11 @@ export function downloadRegistrations( } }) delete newRow["answers"] - acc.push(newRow as CsvRow) + acc.push( + (includePayments + ? withPaymentColumns(newRow, cur, paymentStatusLabel) + : newRow) as CsvRow + ) } return acc }, [] as CsvRow[]) 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/src/withUrql.ts b/@app/lib/src/withUrql.ts index 7d23f7479..c8774d6a9 100644 --- a/@app/lib/src/withUrql.ts +++ b/@app/lib/src/withUrql.ts @@ -17,12 +17,24 @@ import { getSessionAndCSRFToken } from "." import type { Event, GraphCacheConfig } from "@app/graphql" import type { SSRExchange } from "@urql/core" +import type { Cache } from "@urql/exchange-graphcache" import type { IntrospectionQuery, OperationDefinitionNode } from "graphql" import type { Client } from "graphql-ws" const isDev = process.env.NODE_ENV === "development" const isSSR = typeof window === "undefined" +/** + * Invalidates one field of the signed-in user, so that queries selecting it + * refetch. Does nothing when no user is cached. + */ +function invalidateCurrentUserField(cache: Cache, fieldName: string) { + const userKey = cache.resolve("Query", "currentUser") + if (typeof userKey === "string") { + cache.invalidate(userKey, fieldName) + } +} + let wsClient: Client | null = null let rootURL: string | null = null @@ -76,8 +88,42 @@ export const withUrql = withUrqlClient( isDev && devtoolsExchange, cacheExchange({ schema: minifiedSchema as unknown as IntrospectionQuery, + keys: { + // Feature flags are identified by their key, not an id. + FeatureFlag: (data) => (data.key as string | undefined) ?? null, + // A computed composite with no id; embed it in its event + EventPaymentSummary: () => null, + // Payment state of a registration, read by update token. It has + // no id of its own, so it is embedded in its parent query. + RegistrationPayment: () => null, + CreateCheckoutSessionPayload: () => null, + // A user has at most one registration profile. + RegistrationProfile: (data) => + (data.userId as string | undefined) ?? null, + }, updates: { Mutation: { + setFeatureFlag(_result, _args, cache, _info) { + // Refetch what depends on flag states: the layout's enabled + // and preview lists and the change history. + const key = "Query" + cache + .inspectFields(key) + .filter((field) => + [ + "enabledFeaturesList", + "adminPreviewFeaturesList", + "featureFlagEventsList", + ].includes(field.fieldName) + ) + .forEach((field) => cache.invalidate(key, field.fieldKey)) + }, + setRegistrationProfile(_result, _args, cache, _info) { + invalidateCurrentUserField(cache, "registrationProfile") + }, + deleteRegistrationProfile(_result, _args, cache, _info) { + invalidateCurrentUserField(cache, "registrationProfile") + }, logout(result, _args, cache, _info) { // Invalidate currentUser on logout. This refetches queries that // depend on the currentUser field. @@ -169,6 +215,26 @@ export const withUrql = withUrqlClient( id: args.input.id, }) }, + // Marking a registration paid or unpaid moves it between the + // registrations tab's All / Unpaid / Paid lists, so refetch them. + adminMarkRegistrationPaid(_result, _args, cache, _info) { + const key = "Query" + cache + .inspectFields(key) + .filter((field) => field.fieldName === "registrations") + .forEach((field) => cache.invalidate(key, field.fieldKey)) + }, + adminUnmarkRegistrationPaid(_result, args, cache, _info) { + cache.invalidate({ + __typename: "Registration", + id: args.input.registrationId, + }) + const key = "Query" + cache + .inspectFields(key) + .filter((field) => field.fieldName === "registrations") + .forEach((field) => cache.invalidate(key, field.fieldKey)) + }, }, }, }), 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__/app.test.ts b/@app/server/__tests__/app.test.ts new file mode 100644 index 000000000..adc1c2fce --- /dev/null +++ b/@app/server/__tests__/app.test.ts @@ -0,0 +1,128 @@ +import { FastifyInstance } from "fastify" +import { Pool } from "pg" + +import { makeApp } from "../src/app" +import { STRIPE_WEBHOOK_PATH } from "../src/stripeWebhook" + +import { + configureStripeForEachTest, + STRIPE_WEBHOOK_SECRET, + unconfigureStripe, +} from "./payments" + +/* + * makeApp registers the Stripe webhook (an external route) only while + * Stripe is configured, whatever the state of the `payments` flag. + * Everything heavy (database pools, Redis, PostGraphile, Next.js) is + * stubbed; the session, CSRF protection and webhook plugins are the real + * ones, in makeApp's order. + */ + +jest.mock("stripe", () => require("./stripeMock").mockStripeModule()) + +let testPool: Pool + +jest.mock("../src/middleware", () => { + const actual = jest.requireActual("../src/middleware") + const fastifyPlugin = jest.requireActual("fastify-plugin") + const noop = fastifyPlugin(async () => {}) + return { + ...actual, + installDatabasePools: fastifyPlugin(async (app: FastifyInstance) => { + app.decorate("rootPgPool", testPool) + }), + installRedis: noop, + installWorkerUtils: noop, + installHelmet: noop, + installSameOrigin: noop, + installPassport: noop, + installKeycloak: noop, + installStaticUploads: noop, + // Stands in for /graphql: an ordinary route after the webhook + installPostGraphile: fastifyPlugin(async (app: FastifyInstance) => { + app.post("/graphql", async (request) => ({ body: request.body })) + }), + installFileUpload: noop, + installSSR: noop, + } +}) + +jest.mock("../src/middleware/installCypressServerCommand", () => ({ + __esModule: true, + default: jest.requireActual("fastify-plugin")(async () => {}), +})) + +const ActualStripe = jest.requireActual("stripe") +const { webhooks } = new ActualStripe("sk_test_123") + +configureStripeForEachTest() + +let app: FastifyInstance | null = null + +beforeAll(() => { + testPool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }) +}) + +afterAll(async () => { + await testPool.end() +}) + +afterEach(async () => { + await app?.close() + app = null +}) + +function signedEvent() { + const payload = JSON.stringify({ + id: `evt_test_app_${Date.now()}`, + object: "event", + type: "customer.created", + data: { object: { id: "cus_1", object: "customer" } }, + }) + return { + payload, + signature: webhooks.generateTestHeaderString({ + payload, + secret: STRIPE_WEBHOOK_SECRET, + }), + } +} + +async function postWebhook(instance: FastifyInstance) { + const { payload, signature } = signedEvent() + return instance.inject({ + method: "POST", + url: STRIPE_WEBHOOK_PATH, + headers: { + "content-type": "application/json", + "stripe-signature": signature, + }, + payload, + }) +} + +it("registers the webhook while Stripe is configured, keeping CSRF protection for other routes", async () => { + app = await makeApp() + await app.ready() + + const res = await postWebhook(app) + expect(res.statusCode).toBe(200) + expect(res.json()).toEqual({ received: true }) + + const graphql = await app.inject({ + method: "POST", + url: "/graphql", + headers: { "content-type": "application/json" }, + payload: { hello: "world" }, + }) + // Only the webhook is exempt from the CSRF token + expect(graphql.statusCode).toBe(403) +}) + +it("has no webhook route while Stripe is not configured", async () => { + unconfigureStripe() + app = await makeApp() + await app.ready() + + expect(app.hasRoute({ method: "POST", url: STRIPE_WEBHOOK_PATH })).toBe(false) +}) diff --git a/@app/server/__tests__/helpers.ts b/@app/server/__tests__/helpers.ts index d806b6b86..1509d0053 100644 --- a/@app/server/__tests__/helpers.ts +++ b/@app/server/__tests__/helpers.ts @@ -29,26 +29,47 @@ import { createRegistrationSecrets, createSession, createUsers, + deleteTestData as deleteSharedTestData, poolFromUrl, - refreshMaterializedView, + setFeatureFlag as setSharedFeatureFlag, TEST_DATABASE_URL, } from "../../__tests__/helpers" import { getPostGraphileOptions } from "../src/middleware/installPostGraphile" +import { + configureFeatureFlags, + invalidateFeatureFlags, +} from "../src/utils/featureFlags" export * from "../../__tests__/helpers" const MockReq = require("mock-req") +/* + * The server caches flag states for a few seconds. These two shadow the + * shared helpers of the same name and drop that cache, so a test sees its own + * flag changes immediately. + */ +export const setFeatureFlag: typeof setSharedFeatureFlag = async (...args) => { + await setSharedFeatureFlag(...args) + invalidateFeatureFlags() +} + +export const deleteTestData: typeof deleteSharedTestData = async () => { + await deleteSharedTestData() + invalidateFeatureFlags() +} + interface CreateUserAndLogInArgs { isAdmin?: boolean + isDeveloper?: boolean } export async function createUserAndLogIn(args?: CreateUserAndLogInArgs) { - const { isAdmin = false } = args || {} + const { isAdmin = false, isDeveloper = false } = args || {} const pool = poolFromUrl(TEST_DATABASE_URL!) const client = await pool.connect() try { - const [user] = await createUsers(client, 1, true, isAdmin) + const [user] = await createUsers(client, 1, true, isAdmin, isDeveloper) const session = await createSession(client, user.id) return { user, session } @@ -63,6 +84,7 @@ interface CreateEventDataAndLogin { amount?: number isVerified?: boolean isAdmin?: boolean + isDeveloper?: boolean } organizationOptions?: { create: boolean @@ -131,7 +153,8 @@ export async function createEventDataAndLogin(args?: CreateEventDataAndLogin) { client, userOptions.amount, userOptions.isVerified, - userOptions.isAdmin + userOptions.isAdmin, + userOptions.isDeveloper ) } const primaryUser = users[0] @@ -227,8 +250,6 @@ export async function createEventDataAndLogin(args?: CreateEventDataAndLogin) { ) } - await refreshMaterializedView(client) - await client.query("commit") return { users, @@ -345,55 +366,81 @@ interface ICtx { schema: GraphQLSchema } let ctx: ICtx | null = null - -export const setup = async () => { - const rootPgPool = new Pool({ - connectionString: TEST_DATABASE_URL, - }) - const redisClient = new Redis( - process.env.TEST_REDIS_URL - ) as unknown as FastifyRedis - const workerUtils = await makeWorkerUtils({ - connectionString: TEST_DATABASE_URL, - }) - const options = getPostGraphileOptions({ - rootPgPool, - redisClient, - workerUtils, - }) - const schema = await createPostGraphileSchema( - rootPgPool, - "app_public", - options - ) - - // Store the context - ctx = { - rootPgPool, - redisClient, - workerUtils, - options, - schema, - } +// Every resource setup() has created so far, whether or not setup() finished. +// teardown() must release these even when setup() threw (e.g. the test DB was +// dropped by a concurrent `pnpm setup:db` / `pnpm test`) or is still running +// (beforeAll timed out); otherwise the open redis socket / pg pools keep the +// event loop alive and jest never exits. +let pending: Partial = {} +let settingUp: Promise | null = null + +export const setup = () => { + settingUp = (async () => { + const rootPgPool = new Pool({ + connectionString: TEST_DATABASE_URL, + }) + pending.rootPgPool = rootPgPool + const redisClient = new Redis( + process.env.TEST_REDIS_URL + ) as unknown as FastifyRedis + pending.redisClient = redisClient + const workerUtils = await makeWorkerUtils({ + connectionString: TEST_DATABASE_URL, + }) + pending.workerUtils = workerUtils + const options = getPostGraphileOptions({ + rootPgPool, + redisClient, + workerUtils, + }) + const schema = await createPostGraphileSchema( + rootPgPool, + "app_public", + options + ) + // As installFeatureFlags does at boot + configureFeatureFlags(rootPgPool) + + // Store the context + ctx = { + rootPgPool, + redisClient, + workerUtils, + options, + schema, + } + })() + return settingUp } export const teardown = async () => { - try { - if (!ctx) { - return null + // Let an in-flight setup() settle first so nothing it creates afterwards + // escapes cleanup. + await settingUp?.catch(() => {}) + settingUp = null + const { rootPgPool, redisClient, workerUtils } = pending + pending = {} + ctx = null + const attempt = async (fn: () => unknown) => { + try { + await fn() + } catch (e) { + console.error(e) + } + } + if (redisClient) { + if ((redisClient as unknown as Redis).status === "ready") { + // Flush redis after tests have run + await attempt(() => redisClient.flushdb()) + await attempt(() => redisClient.quit()) } - const { rootPgPool, redisClient, workerUtils } = ctx - ctx = null - rootPgPool.end() - workerUtils.release() - // Flush redis after tests have run - await redisClient.flushdb() - await redisClient.quit() - return null - } catch (e) { - console.error(e) - return null + // Also stops ioredis reconnecting forever if it never got (or lost) a + // connection + redisClient.disconnect() } + if (workerUtils) await attempt(() => workerUtils.release()) + if (rootPgPool) await attempt(() => rootPgPool.end()) + return null } export const runGraphQLQuery = async ( diff --git a/@app/server/__tests__/makeApp.test.ts b/@app/server/__tests__/makeApp.test.ts new file mode 100644 index 000000000..345e9bc11 --- /dev/null +++ b/@app/server/__tests__/makeApp.test.ts @@ -0,0 +1,109 @@ +import { FastifyInstance } from "fastify" + +import { makeApp } from "../src/app" + +/* + * makeApp with everything heavy (database pools, Redis, PostGraphile, + * Next.js) stubbed; the health, same-origin, session, CSRF and external + * route plugins are the real ones, in makeApp's order. The external route + * registry holds one test module. + */ + +jest.mock("../src/externalRoutes", () => { + const actual = jest.requireActual("../src/externalRoutes") + const ok = async () => ({ ok: true }) + return { + ...actual, + externalRoutes: [ + { + name: "test webhook", + configured: () => true, + paths: [ + { method: "POST", path: "/hooks/test", csrfExempt: true }, + { method: "POST", path: "/hooks/test/protected" }, + ], + register: async (app: FastifyInstance) => { + app.post("/hooks/test", ok) + app.post("/hooks/test/protected", ok) + }, + }, + ], + } +}) + +jest.mock("../src/middleware", () => { + const actual = jest.requireActual("../src/middleware") + const fastifyPlugin = jest.requireActual("fastify-plugin") + const noop = fastifyPlugin(async () => {}) + return { + ...actual, + installDatabasePools: noop, + installRedis: noop, + installWorkerUtils: noop, + installHelmet: noop, + installPassport: noop, + installKeycloak: noop, + installStaticUploads: noop, + // Stands in for PostGraphile's /graphql + installPostGraphile: fastifyPlugin(async (app: FastifyInstance) => { + app.post("/graphql", async () => ({ data: {} })) + }), + installFileUpload: noop, + installSSR: noop, + } +}) + +jest.mock("../src/middleware/installCypressServerCommand", () => ({ + __esModule: true, + default: jest.requireActual("fastify-plugin")(async () => {}), +})) + +let app: FastifyInstance + +beforeAll(async () => { + process.env.LOG_LEVEL = "silent" + app = await makeApp() + await app.ready() +}) + +afterAll(async () => { + await app.close() + delete process.env.LOG_LEVEL +}) + +it("serves the health check", async () => { + const res = await app.inject({ method: "GET", url: "/healthz" }) + expect(res.statusCode).toBe(200) + expect(res.body).toBe("ok") +}) + +it("rejects a POST to /graphql without a CSRF token", async () => { + const res = await app.inject({ + method: "POST", + url: "/graphql", + headers: { "content-type": "application/json" }, + payload: { query: "{__typename}" }, + }) + expect(res.statusCode).toBe(403) +}) + +it("serves a registered external route without a CSRF token when it is exempt", async () => { + const res = await app.inject({ + method: "POST", + url: "/hooks/test", + headers: { "content-type": "application/json" }, + payload: {}, + }) + expect(res.statusCode).toBe(200) + expect(res.json()).toEqual({ ok: true }) +}) + +it("rejects an external route that is not exempt without a CSRF token", async () => { + const res = await app.inject({ + method: "POST", + url: "/hooks/test/protected", + headers: { "content-type": "application/json" }, + payload: {}, + }) + expect(res.statusCode).toBe(403) +}) diff --git a/@app/server/__tests__/mcp/auth.test.ts b/@app/server/__tests__/mcp/auth.test.ts new file mode 100644 index 000000000..da8f2c91f --- /dev/null +++ b/@app/server/__tests__/mcp/auth.test.ts @@ -0,0 +1,149 @@ +import { randomUUID } from "crypto" + +import { McpAuthError, resolveMcpSession } from "../../src/mcp/auth" +import { + deleteTestData, + poolFromUrl, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" + +beforeEach(deleteTestData) +beforeAll(setup) +afterAll(teardown) + +const logger = { debug: () => {}, warn: () => {}, error: () => {} } +const pool = poolFromUrl(TEST_DATABASE_URL!) + +function claims(overrides: Record = {}) { + const sub = randomUUID() + return { + sub, + sid: randomUUID(), + email: `testuser_${sub.slice(0, 8)}@example.com`, + email_verified: true, + name: "Testi Käyttäjä", + ...overrides, + } +} + +async function sessionRow(uuid: string) { + const { + rows: [row], + } = await pool.query( + `select s.kind, s.oauth_sid, s.user_id, ua.identifier + from app_private.sessions s + join app_public.user_authentications ua + on ua.user_id = s.user_id and ua.service = 'keycloak' + where s.uuid = $1`, + [uuid] + ) + return row +} + +describe("resolveMcpSession", () => { + it("registers a new identity and creates an mcp session for its sid", async () => { + const c = claims() + const sessionId = await resolveMcpSession(pool, c, logger) + + const row = await sessionRow(sessionId) + expect(row).toMatchObject({ + kind: "mcp", + oauth_sid: c.sid, + identifier: c.sub, + }) + }) + + it("reuses the session for the same Keycloak session", async () => { + const c = claims() + const first = await resolveMcpSession(pool, c, logger) + const second = await resolveMcpSession(pool, c, logger) + expect(second).toEqual(first) + + const third = await resolveMcpSession( + pool, + { ...c, sid: randomUUID() }, + logger + ) + expect(third).not.toEqual(first) + expect((await sessionRow(third)).user_id).toEqual( + (await sessionRow(first)).user_id + ) + }) + + it("leaves the web login's stored secrets alone for a linked identity", async () => { + const c = claims() + await resolveMcpSession(pool, c, logger) + await pool.query( + `update app_private.user_authentication_secrets uas + set details = '{"id_token": "web-login-hint"}' + from app_public.user_authentications ua + where ua.id = uas.user_authentication_id and ua.identifier = $1`, + [c.sub] + ) + + await resolveMcpSession(pool, { ...c, sid: randomUUID() }, logger) + + const { + rows: [secret], + } = await pool.query( + `select uas.details from app_private.user_authentication_secrets uas + join app_public.user_authentications ua on ua.id = uas.user_authentication_id + where ua.identifier = $1`, + [c.sub] + ) + expect(secret.details).toEqual({ id_token: "web-login-hint" }) + }) + + it("refuses to create a user from an unverified email", async () => { + await expect( + resolveMcpSession(pool, claims({ email_verified: false }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses a token without a sid", async () => { + await expect( + resolveMcpSession(pool, claims({ sid: undefined }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses a Keycloak session that already belongs to another user", async () => { + const a = claims() + await resolveMcpSession(pool, a, logger) + await expect( + resolveMcpSession(pool, claims({ sid: a.sid }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses an identity that resolves to a break-glass account", async () => { + const c = claims() + await resolveMcpSession(pool, c, logger) + const { + rows: [{ user_id: userId }], + } = await pool.query( + `select user_id from app_public.user_authentications where identifier = $1`, + [c.sub] + ) + const { + rows: [original], + } = await pool.query( + "select username from app_public.users where id = $1", + [userId] + ) + await pool.query( + "update app_public.users set username = 'toimari' where id = $1", + [userId] + ) + try { + await expect( + resolveMcpSession(pool, { ...c, sid: randomUUID() }, logger) + ).rejects.toBeInstanceOf(McpAuthError) + } finally { + await pool.query( + "update app_public.users set username = $1 where id = $2", + [original.username, userId] + ) + } + }) +}) diff --git a/@app/server/__tests__/mcp/events.test.ts b/@app/server/__tests__/mcp/events.test.ts new file mode 100644 index 000000000..40385106c --- /dev/null +++ b/@app/server/__tests__/mcp/events.test.ts @@ -0,0 +1,205 @@ +import { McpEventOptionsQuery, QuestionType } from "@app/graphql" +import { Client } from "@modelcontextprotocol/sdk/client/index.js" +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js" + +import { tokenGrantsAdmin } from "../../src/mcp/auth" +import { + createEventInput, + eventSlug, + NewEvent, + plainToRichText, + validateNewEvent, +} from "../../src/mcp/events" +import { createMcpServer, GraphQLRunner } from "../../src/mcp/server" + +const options = { + organizations: { nodes: [{ id: "org-1", name: "PoRa" }] }, + eventCategories: { + nodes: [ + { + id: "cat-1", + name: { fi: "Liikunta" }, + ownerOrganization: { id: "org-1" }, + }, + { id: "cat-2", name: { fi: "Muu" }, ownerOrganization: { id: "org-2" } }, + ], + }, +} as McpEventOptionsQuery + +const valid: NewEvent = { + organizationId: "org-1", + categoryId: "cat-1", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { fi: "Ensimmäinen.\n\nToinen\nrivi." }, + location: "Otaniemi", + eventStartTime: "2026-12-01T23:30:00+02:00", + eventEndTime: "2026-12-02T02:00:00+02:00", + registrationStartTime: "2026-11-01T12:00:00+02:00", + registrationEndTime: "2026-11-30T12:00:00+02:00", + openQuotaSize: 0, + isHighlighted: false, + quotas: [{ title: { fi: "Kaikki" }, size: 10 }], + questions: [ + { type: QuestionType.Text, label: { fi: "Allergiat" }, required: false }, + { + type: QuestionType.Radio, + label: { fi: "Koko" }, + required: true, + options: [{ fi: "S" }, { fi: "M", en: "M" }], + }, + ], +} + +describe("validateNewEvent", () => { + it("accepts a valid event", () => { + expect(validateNewEvent(valid, options)).toEqual([]) + }) + + it("rejects a category of another organization and unknown ids", () => { + expect( + validateNewEvent({ ...valid, categoryId: "cat-2" }, options) + ).toEqual(["The category belongs to another organization."]) + expect( + validateNewEvent( + { ...valid, organizationId: "nope", categoryId: "nope" }, + options + ) + ).toEqual([ + "organizationId is not an organization.", + "categoryId is not an event category.", + ]) + }) + + it("rejects inconsistent times, missing quotas and option mismatches", () => { + expect( + validateNewEvent( + { + ...valid, + description: { fi: " " }, + eventEndTime: valid.eventStartTime, + registrationEndTime: valid.eventStartTime, + quotas: [], + questions: [ + { + type: QuestionType.Text, + label: { fi: "a" }, + required: false, + options: [{ fi: "x" }], + }, + { + type: QuestionType.Checkbox, + label: { fi: "b" }, + required: false, + }, + ], + }, + options + ) + ).toEqual([ + "A description in Finnish or English is required.", + "The event must end after it starts.", + "Registration must close before the event starts.", + "Give at least one quota or an open quota size above zero.", + "Question 1: TEXT questions take no options.", + "Question 2: CHECKBOX questions need options.", + ]) + }) +}) + +describe("createEventInput", () => { + it("always creates a draft and maps quotas, questions and texts", () => { + const input = createEventInput(valid) + expect(input.event).toMatchObject({ + isDraft: true, + slug: "2026-12-1-testitapahtuma", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { + fi: [ + { type: "paragraph", children: [{ text: "Ensimmäinen." }] }, + { type: "paragraph", children: [{ text: "Toinen rivi." }] }, + ], + }, + ownerOrganizationId: "org-1", + categoryId: "cat-1", + }) + expect(input.quotas).toEqual([ + { position: 0, title: { fi: "Kaikki" }, size: 10 }, + ]) + expect(input.questions).toEqual([ + { + position: 0, + type: "TEXT", + label: { fi: "Allergiat" }, + isRequired: false, + data: null, + }, + { + position: 1, + type: "RADIO", + label: { fi: "Koko" }, + isRequired: true, + data: [{ fi: "S" }, { fi: "M", en: "M" }], + }, + ]) + }) +}) + +describe("eventSlug", () => { + it("uses the start date in Finnish time", () => { + // 22:30 UTC on Nov 30 is already Dec 1 in Helsinki + expect(eventSlug({ fi: "Pikkujoulut" }, "2026-11-30T22:30:00Z")).toBe( + "2026-12-1-pikkujoulut" + ) + }) +}) + +describe("plainToRichText", () => { + it("drops empty paragraphs", () => { + expect(plainToRichText("\n\nYksi\n\n\n\n")).toEqual([ + { type: "paragraph", children: [{ text: "Yksi" }] }, + ]) + }) +}) + +describe("admin tools", () => { + it("are granted only by the ilmo-admin realm role in the token", () => { + expect(tokenGrantsAdmin({ realm_access: { roles: ["ilmo-admin"] } })).toBe( + true + ) + expect( + tokenGrantsAdmin({ realm_access: { roles: ["offline_access"] } }) + ).toBe(false) + expect(tokenGrantsAdmin({})).toBe(false) + }) + + it.each([ + [false, ["list_events", "get_event", "register_to_event"]], + [ + true, + [ + "list_events", + "get_event", + "register_to_event", + "list_event_options", + "create_event", + ], + ], + ])("are listed only for admins (isAdmin: %s)", async (isAdmin, expected) => { + const runner: GraphQLRunner = { + transaction: () => Promise.reject(new Error("not used")), + } + const server = createMcpServer(runner, { isAdmin }) + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair() + const client = new Client({ name: "test", version: "0" }) + await server.connect(serverTransport) + await client.connect(clientTransport) + try { + const { tools } = await client.listTools() + expect(tools.map((t) => t.name)).toEqual(expected) + } finally { + await client.close() + await server.close() + } + }) +}) diff --git a/@app/server/__tests__/mcp/registration.test.ts b/@app/server/__tests__/mcp/registration.test.ts new file mode 100644 index 000000000..3672d7d8e --- /dev/null +++ b/@app/server/__tests__/mcp/registration.test.ts @@ -0,0 +1,128 @@ +import { McpEventQuery, QuestionType } from "@app/graphql" + +import { + richTextToPlain, + validateRegistration, +} from "../../src/mcp/registration" + +type McpEvent = NonNullable + +const event = { + signupOpen: true, + quotas: { nodes: [{ id: "quota-1" }] }, + eventQuestions: { + nodes: [ + { + id: "q-text", + type: QuestionType.Text, + label: { fi: "Allergiat", en: "Allergies" }, + isRequired: false, + data: null, + }, + { + id: "q-radio", + type: QuestionType.Radio, + label: { fi: "Koko", en: "Size" }, + isRequired: true, + data: [ + { fi: "Pieni", en: "Small" }, + { fi: "Iso", en: "Large" }, + ], + }, + { + id: "q-checkbox", + type: QuestionType.Checkbox, + label: { fi: "Lähde", en: "Source" }, + isRequired: false, + data: [ + { fi: "Kaveri", en: "Friend" }, + { fi: "Muu", en: "Other" }, + ], + }, + ], + }, +} as unknown as McpEvent + +const valid = { + quotaId: "quota-1", + firstName: "Testi", + lastName: "Henkilö", + email: "testi@example.com", + answers: { "q-radio": "Iso", "q-checkbox": ["Friend", "Muu"] }, +} + +describe("validateRegistration", () => { + it("accepts a valid registration with options in either language", () => { + expect(validateRegistration(event, valid)).toEqual([]) + }) + + it("rejects a closed event and a quota of another event", () => { + expect( + validateRegistration( + { ...event, signupOpen: false }, + { ...valid, quotaId: "other" } + ) + ).toEqual([ + "Registration for this event is not open.", + "quotaId is not one of this event's quotas.", + ]) + }) + + it("rejects names with spaces and missing names", () => { + expect( + validateRegistration(event, { + ...valid, + firstName: "Anna Maria", + lastName: "", + }) + ).toEqual(["firstName must not contain spaces.", "lastName is required."]) + }) + + it("requires required questions and known question ids", () => { + expect( + validateRegistration(event, { ...valid, answers: { unknown: "x" } }) + ).toEqual([ + "Answer unknown does not match a question of this event.", + '"Size" is required.', + ]) + }) + + it("rejects answers that are not options or have the wrong shape", () => { + expect( + validateRegistration(event, { + ...valid, + answers: { + "q-text": ["not", "a", "string"], + "q-radio": "Medium", + "q-checkbox": "Friend", + }, + }) + ).toEqual([ + '"Allergies" expects a string.', + '"Size" expects exactly one of: Pieni, Small, Iso, Large.', + '"Source" expects a list of options from: Kaveri, Friend, Muu, Other.', + ]) + }) +}) + +describe("richTextToPlain", () => { + it("joins paragraphs and nested leaves", () => { + expect( + richTextToPlain([ + { + type: "paragraph", + children: [{ text: "Hello " }, { text: "world" }], + }, + { type: "paragraph", children: [{ text: "" }] }, + { + type: "bulleted-list", + children: [{ type: "list-item", children: [{ text: "Item" }] }], + }, + ]) + ).toEqual("Hello world\n\nItem") + }) + + it("returns an empty string for missing content", () => { + expect(richTextToPlain(undefined)).toEqual("") + }) +}) diff --git a/@app/server/__tests__/mcp/routes.test.ts b/@app/server/__tests__/mcp/routes.test.ts new file mode 100644 index 000000000..4cfefb59a --- /dev/null +++ b/@app/server/__tests__/mcp/routes.test.ts @@ -0,0 +1,240 @@ +import { createServer, Server } from "http" +import { AddressInfo } from "net" + +import { fastify, FastifyInstance } from "fastify" +import { exportJWK, generateKeyPair, JWTPayload, KeyLike, SignJWT } from "jose" + +import { + McpAuthError, + mcpResourceUrl, + verifyAccessToken, +} from "../../src/mcp/auth" +import { mcpRoutes } from "../../src/mcp/routes" +import installExternalRoutes from "../../src/middleware/installExternalRoutes" + +let issuerServer: Server +let issuer: string +let signingKey: KeyLike +let foreignKey: KeyLike +let app: FastifyInstance +const savedIssuer = process.env.KEYCLOAK_ISSUER + +beforeAll(async () => { + const keys = await generateKeyPair("RS256") + signingKey = keys.privateKey + foreignKey = (await generateKeyPair("RS256")).privateKey + const jwk = { + ...(await exportJWK(keys.publicKey)), + kid: "test", + alg: "RS256", + } + + // Stands in for Keycloak: the discovery document and the realm's JWKS. + issuerServer = createServer((req, res) => { + res.setHeader("content-type", "application/json") + if (req.url === "/realms/test/.well-known/openid-configuration") { + res.end(JSON.stringify({ issuer, jwks_uri: `${issuer}/certs` })) + } else if (req.url === "/realms/test/certs") { + res.end(JSON.stringify({ keys: [jwk] })) + } else { + res.statusCode = 404 + res.end("{}") + } + }) + await new Promise((resolve) => + issuerServer.listen(0, "127.0.0.1", resolve) + ) + const { port } = issuerServer.address() as AddressInfo + issuer = `http://127.0.0.1:${port}/realms/test` + process.env.KEYCLOAK_ISSUER = issuer + + app = fastify() + await app.register(mcpRoutes.register) + await app.ready() +}) + +afterAll(async () => { + await app.close() + await new Promise((resolve) => issuerServer.close(resolve)) + process.env.KEYCLOAK_ISSUER = savedIssuer +}) + +function token( + overrides: JWTPayload = {}, + { + key = signingKey, + expiresIn = "5m", + }: { key?: KeyLike; expiresIn?: string } = {} +) { + return new SignJWT({ + typ: "Bearer", + sub: "test-sub", + sid: "test-sid", + ...overrides, + }) + .setProtectedHeader({ alg: "RS256", kid: "test" }) + .setIssuer((overrides.iss as string) ?? issuer) + .setAudience((overrides.aud as string) ?? mcpResourceUrl()) + .setIssuedAt() + .setExpirationTime(expiresIn) + .sign(key) +} + +describe("verifyAccessToken", () => { + it("accepts an access token issued for the MCP resource", async () => { + const payload = await verifyAccessToken(await token()) + expect(payload).toMatchObject({ sub: "test-sub", sid: "test-sid" }) + }) + + it.each([ + ["another audience", () => token({ aud: "https://other.prodeko.org" })], + [ + "another issuer", + () => token({ iss: "https://evil.example/realms/test" }), + ], + ["an ID token", () => token({ typ: "ID" })], + ["an expired token", () => token({}, { expiresIn: "-1m" })], + ["a token signed with another key", () => token({}, { key: foreignKey })], + ])("rejects %s", async (_, make) => { + await expect(verifyAccessToken(await make())).rejects.toBeInstanceOf( + McpAuthError + ) + }) + + it("rejects a malformed token", async () => { + await expect(verifyAccessToken("not-a-jwt")).rejects.toBeInstanceOf( + McpAuthError + ) + }) +}) + +describe("/mcp routes", () => { + const metadataUrl = `${process.env.ROOT_URL}/.well-known/oauth-protected-resource/mcp` + + it("serves protected resource metadata pointing at the issuer", async () => { + const res = await app.inject({ + method: "GET", + url: "/.well-known/oauth-protected-resource/mcp", + }) + expect(res.statusCode).toBe(200) + expect(res.json()).toMatchObject({ + resource: mcpResourceUrl(), + authorization_servers: [issuer], + }) + }) + + it("answers a request without a token with 401 and the metadata pointer", async () => { + const res = await app.inject({ method: "POST", url: "/mcp", payload: {} }) + expect(res.statusCode).toBe(401) + expect(res.headers["www-authenticate"]).toBe( + `Bearer resource_metadata="${metadataUrl}"` + ) + }) + + it("answers a token for another audience with invalid_token", async () => { + const res = await app.inject({ + method: "POST", + url: "/mcp", + payload: {}, + headers: { + authorization: `Bearer ${await token({ aud: "https://other.prodeko.org" })}`, + }, + }) + expect(res.statusCode).toBe(401) + expect(res.headers["www-authenticate"]).toContain('error="invalid_token"') + }) + + it.each(["GET", "DELETE"] as const)( + "answers %s with 405 instead of holding the connection open", + async (method) => { + const res = await app.inject({ method, url: "/mcp" }) + expect(res.statusCode).toBe(405) + expect(res.headers.allow).toBe("POST") + } + ) +}) + +describe("the mcp_server flag", () => { + const routes = [ + ["POST", "/mcp"], + ["GET", "/mcp"], + ["DELETE", "/mcp"], + ["GET", "/.well-known/oauth-protected-resource/mcp"], + ["GET", "/.well-known/oauth-protected-resource"], + ] as const + + let gated: FastifyInstance + let enabled: boolean + // Stands in for the root pool: resolveMcpSession writes the session row + // through it, which is the first side effect of an authenticated request. + const connect = jest.fn(async () => { + throw new Error("no database in this test") + }) + + beforeAll(async () => { + gated = fastify() + gated.decorate("rootPgPool", { connect } as any) + await gated.register(installExternalRoutes, { + externalRoutes: [mcpRoutes], + isFeatureEnabled: async (key) => key === "mcp_server" && enabled, + }) + await gated.ready() + }) + + afterAll(() => gated.close()) + + beforeEach(() => connect.mockClear()) + + it("names the mcp_server flag and declares every route the module registers", () => { + expect(mcpRoutes.feature).toBe("mcp_server") + expect(mcpRoutes.gateWhenOff).not.toBe(false) + for (const [method, url] of routes) { + expect(gated.hasRoute({ method, url })).toBe(true) + } + }) + + it("answers 404 on every MCP route while the flag is off, and touches no session", async () => { + enabled = false + const authorization = `Bearer ${await token()}` + for (const [method, url] of routes) { + const res = await gated.inject({ + method, + url, + payload: method === "POST" ? {} : undefined, + headers: { authorization }, + }) + expect([method, url, res.statusCode]).toEqual([method, url, 404]) + expect(res.headers["www-authenticate"]).toBeUndefined() + } + expect(connect).not.toHaveBeenCalled() + }) + + it("serves the MCP routes while the flag is on", async () => { + enabled = true + expect( + ( + await gated.inject({ + method: "GET", + url: "/.well-known/oauth-protected-resource/mcp", + }) + ).statusCode + ).toBe(200) + expect( + (await gated.inject({ method: "POST", url: "/mcp", payload: {} })) + .statusCode + ).toBe(401) + expect( + (await gated.inject({ method: "GET", url: "/mcp" })).statusCode + ).toBe(405) + + // A valid token reaches session resolution, which needs the database. + const res = await gated.inject({ + method: "POST", + url: "/mcp", + payload: {}, + headers: { authorization: `Bearer ${await token()}` }, + }) + expect(res.statusCode).toBe(503) + expect(connect).toHaveBeenCalledTimes(1) + }) +}) diff --git a/@app/server/__tests__/middleware/installCSRFProtection.test.ts b/@app/server/__tests__/middleware/installCSRFProtection.test.ts new file mode 100644 index 000000000..a38c5ddf6 --- /dev/null +++ b/@app/server/__tests__/middleware/installCSRFProtection.test.ts @@ -0,0 +1,230 @@ +import { fastify, FastifyInstance, LightMyRequestResponse } from "fastify" + +import { ExternalRouteModule } from "../../src/externalRoutes" +import installCSRFProtection from "../../src/middleware/installCSRFProtection" +import installExternalRoutes from "../../src/middleware/installExternalRoutes" +import installSameOrigin from "../../src/middleware/installSameOrigin" +import installSession from "../../src/middleware/installSession" + +/* + * The session, same-origin and CSRF plugins are the real ones, in makeApp's + * order. POST /graphql and GET /page stand in for PostGraphile and Next.js. + */ +async function buildApp( + plugins = { + installCSRFProtection, + installSameOrigin, + installSession, + } +) { + const app = fastify() + await app.register(plugins.installSameOrigin) + await app.register(plugins.installSession) + await app.register(plugins.installCSRFProtection) + app.get("/page", async () => "page") + app.post("/graphql", async () => ({ data: {} })) + await app.ready() + return app +} + +/** Cookie values exactly as sent, still encoded, as a browser returns them. */ +function cookiesOf(res: LightMyRequestResponse): Record { + const header = res.headers["set-cookie"] ?? [] + const lines = Array.isArray(header) ? header : [header] + return Object.fromEntries( + lines.map((line) => { + const pair = line.split(";")[0] + const eq = pair.indexOf("=") + return [pair.slice(0, eq), pair.slice(eq + 1)] + }) + ) +} + +/** A GET, as a browser loading a page does, then its session and token. */ +async function getSessionAndToken(app: FastifyInstance) { + const res = await app.inject({ method: "GET", url: "/page" }) + const { session, csrfToken } = cookiesOf(res) + return { session, csrfToken: decodeURIComponent(csrfToken) } +} + +function postGraphql(app: FastifyInstance, headers: Record) { + return app.inject({ + method: "POST", + url: "/graphql", + headers: { "content-type": "application/json", ...headers }, + payload: { query: "{__typename}" }, + }) +} + +describe("CSRF protection", () => { + let app: FastifyInstance + + beforeEach(async () => { + app = await buildApp() + }) + + afterEach(async () => { + await app.close() + }) + + it("issues a session and a CSRF token cookie on GET", async () => { + const { session, csrfToken } = await getSessionAndToken(app) + expect(session).toBeTruthy() + expect(csrfToken).toBeTruthy() + }) + + it("rejects a POST without a token", async () => { + const res = await postGraphql(app, {}) + expect(res.statusCode).toBe(403) + }) + + it("rejects a POST with a session but no token header", async () => { + const { session, csrfToken } = await getSessionAndToken(app) + const res = await postGraphql(app, { + cookie: `session=${session}; csrfToken=${csrfToken}`, + }) + expect(res.statusCode).toBe(403) + }) + + it("rejects a POST with a wrong token", async () => { + const { session } = await getSessionAndToken(app) + const res = await postGraphql(app, { + cookie: `session=${session}`, + "csrf-token": "not-the-token", + }) + expect(res.statusCode).toBe(403) + }) + + it("accepts a POST with the session's token", async () => { + const { session, csrfToken } = await getSessionAndToken(app) + const res = await postGraphql(app, { + cookie: `session=${session}; csrfToken=${csrfToken}`, + "csrf-token": csrfToken, + }) + expect(res.statusCode).toBe(200) + }) + + it("does not check GET requests", async () => { + const res = await app.inject({ method: "GET", url: "/page" }) + expect(res.statusCode).toBe(200) + }) + + it("does not bypass the check for the GraphiQL referer outside development", async () => { + const res = await postGraphql(app, { + referer: `${process.env.ROOT_URL}/graphiql`, + }) + expect(res.statusCode).toBe(403) + }) +}) + +describe("CSRF protection in development", () => { + let app: FastifyInstance + // NODE_ENV is typed read-only + const env = process.env as Record + const savedNodeEnv = env.NODE_ENV + + beforeEach(async () => { + // installCSRFProtection reads NODE_ENV when it is loaded + env.NODE_ENV = "development" + let plugins: Parameters[0] + jest.isolateModules(() => { + plugins = { + installCSRFProtection: + require("../../src/middleware/installCSRFProtection").default, + installSameOrigin: require("../../src/middleware/installSameOrigin") + .default, + installSession: require("../../src/middleware/installSession").default, + } + }) + env.NODE_ENV = savedNodeEnv + app = await buildApp(plugins!) + }) + + afterEach(async () => { + await app.close() + }) + + it("lets GraphiQL post to /graphql without a token", async () => { + const res = await postGraphql(app, { + referer: `${process.env.ROOT_URL}/graphiql`, + }) + expect(res.statusCode).toBe(200) + }) + + it("still rejects other POSTs without a token", async () => { + const res = await postGraphql(app, {}) + expect(res.statusCode).toBe(403) + }) +}) + +describe("CSRF exemptions from the external route registry", () => { + const ok = async () => ({ ok: true }) + + const webhook: ExternalRouteModule = { + name: "test webhook", + configured: () => true, + paths: [ + { method: "POST", path: "/hooks/test", csrfExempt: true }, + { method: "POST", path: "/hooks/test/protected" }, + ], + register: async (app) => { + app.post("/hooks/test", ok) + app.post("/hooks/test/protected", ok) + }, + } + + const notConfigured: ExternalRouteModule = { + name: "not configured", + configured: () => false, + paths: [{ method: "POST", path: "/hooks/off", csrfExempt: true }], + register: async (app) => { + app.post("/hooks/off", ok) + }, + } + + let app: FastifyInstance + + beforeEach(async () => { + const externalRoutes = [webhook, notConfigured] + app = fastify() + await app.register(installSameOrigin) + await app.register(installSession) + await app.register(installCSRFProtection, { externalRoutes }) + await app.register(installExternalRoutes, { externalRoutes }) + app.post("/graphql", ok) + // Not external routes: a path below an exempt one, and the path of a + // module that is not configured + app.post("/hooks/test/other", ok) + app.post("/hooks/off", ok) + await app.ready() + }) + + afterEach(async () => { + await app.close() + }) + + function postWithoutToken(url: string) { + return app.inject({ + method: "POST", + url, + headers: { "content-type": "application/json" }, + payload: {}, + }) + } + + it.each(["/hooks/test", "/hooks/test?x=1"])( + "lets %s through without a token", + async (url) => { + expect((await postWithoutToken(url)).statusCode).toBe(200) + } + ) + + it.each([ + "/graphql", + "/hooks/test/protected", + "/hooks/test/other", + "/hooks/off", + ])("still rejects %s without a token", async (url) => { + expect((await postWithoutToken(url)).statusCode).toBe(403) + }) +}) diff --git a/@app/server/__tests__/middleware/installExternalRoutes.test.ts b/@app/server/__tests__/middleware/installExternalRoutes.test.ts new file mode 100644 index 000000000..ef508ea78 --- /dev/null +++ b/@app/server/__tests__/middleware/installExternalRoutes.test.ts @@ -0,0 +1,360 @@ +import { fastify, FastifyInstance } from "fastify" +import fp from "fastify-plugin" + +import { + csrfExemptions, + ExternalRouteModule, + externalRoutes, +} from "../../src/externalRoutes" +import installExternalRoutes from "../../src/middleware/installExternalRoutes" + +import type { FeatureKey } from "@app/lib" + +const ok = async () => ({ ok: true }) + +function module( + overrides: Partial & Pick +): ExternalRouteModule { + return { + configured: () => true, + paths: [], + register: async () => {}, + ...overrides, + } +} + +let app: FastifyInstance + +beforeEach(() => { + app = fastify() +}) + +afterEach(async () => { + await app.close() +}) + +it("registers the routes of configured modules only", async () => { + const on = module({ + name: "on", + paths: [ + { method: "POST", path: "/on" }, + { method: "GET", path: "/on/status" }, + ], + register: async (scope) => { + scope.post("/on", ok) + scope.get("/on/status", ok) + }, + }) + const off = module({ + name: "off", + configured: () => false, + paths: [{ method: "POST", path: "/off" }], + register: async (scope) => { + scope.post("/off", ok) + }, + }) + await app.register(installExternalRoutes, { externalRoutes: [on, off] }) + await app.ready() + + expect(app.hasRoute({ method: "POST", url: "/on" })).toBe(true) + expect(app.hasRoute({ method: "GET", url: "/on/status" })).toBe(true) + expect(app.hasRoute({ method: "POST", url: "/off" })).toBe(false) + expect( + (await app.inject({ method: "HEAD", url: "/on/status" })).statusCode + ).toBe(200) +}) + +it.each([ + ["a plain plugin", (register: ExternalRouteModule["register"]) => register], + [ + "a fastify-plugin", + (register: ExternalRouteModule["register"]) => fp(register), + ], +])( + "refuses a route the module did not declare, registered by %s", + async (_, wrap) => { + const sneaky = module({ + name: "sneaky", + paths: [{ method: "POST", path: "/declared" }], + register: wrap(async (scope) => { + scope.post("/declared", ok) + scope.post("/undeclared", ok) + }), + }) + await expect( + app.register(installExternalRoutes, { externalRoutes: [sneaky] }) + ).rejects.toThrow( + "External route module 'sneaky' registered POST /undeclared, which is not in its paths" + ) + } +) + +it("refuses a declared path under another method", async () => { + const wrongMethod = module({ + name: "wrong method", + paths: [{ method: "POST", path: "/hook" }], + register: async (scope) => { + scope.put("/hook", ok) + }, + }) + await expect( + app.register(installExternalRoutes, { externalRoutes: [wrongMethod] }) + ).rejects.toThrow("registered PUT /hook") +}) + +describe("the feature flag gate", () => { + // The registry may not have a key a test can use, so the tests pass their own. + const testFlag = "external_routes_test" as FeatureKey + + function gated( + overrides: Partial = {}, + calls: string[] = [] + ) { + return module({ + name: "gated", + feature: testFlag, + paths: [ + { method: "POST", path: "/gated" }, + { method: "GET", path: "/gated" }, + ], + register: async (scope) => { + scope.addHook("onRequest", async (request) => { + calls.push(`hook ${request.method}`) + }) + scope.post("/gated", async () => { + calls.push("POST") + return { ok: true } + }) + scope.get("/gated", async () => { + calls.push("GET") + return { ok: true } + }) + }, + ...overrides, + }) + } + + it.each([ + ["a plain plugin", (register: ExternalRouteModule["register"]) => register], + [ + "a fastify-plugin", + (register: ExternalRouteModule["register"]) => fp(register), + ], + ])( + "answers 404 before any of the module's code runs while the flag is off, with %s", + async (_, wrap) => { + const calls: string[] = [] + const base = gated({}, calls) + const isFeatureEnabled = jest.fn(async () => false) + await app.register(installExternalRoutes, { + externalRoutes: [{ ...base, register: wrap(base.register) }], + isFeatureEnabled, + }) + + for (const method of ["POST", "GET", "HEAD"] as const) { + const res = await app.inject({ method, url: "/gated" }) + expect(res.statusCode).toBe(404) + } + expect(calls).toEqual([]) + expect(isFeatureEnabled).toHaveBeenCalledWith(testFlag) + } + ) + + it("reads the flag on every request", async () => { + const calls: string[] = [] + let enabled = true + await app.register(installExternalRoutes, { + externalRoutes: [gated({}, calls)], + isFeatureEnabled: async () => enabled, + }) + + expect( + (await app.inject({ method: "POST", url: "/gated" })).json() + ).toEqual({ ok: true }) + enabled = false + expect( + (await app.inject({ method: "POST", url: "/gated" })).statusCode + ).toBe(404) + enabled = true + expect( + (await app.inject({ method: "GET", url: "/gated" })).statusCode + ).toBe(200) + expect(calls).toEqual(["hook POST", "POST", "hook GET", "GET"]) + }) + + it("keeps the routes answering while the flag is off when gateWhenOff is false", async () => { + const isFeatureEnabled = jest.fn(async () => false) + await app.register(installExternalRoutes, { + externalRoutes: [gated({ gateWhenOff: false })], + isFeatureEnabled, + }) + + expect( + (await app.inject({ method: "POST", url: "/gated" })).statusCode + ).toBe(200) + expect(isFeatureEnabled).not.toHaveBeenCalled() + }) + + it("does not read any flag for a module without a feature, nor for other modules", async () => { + const isFeatureEnabled = jest.fn(async () => false) + const open = module({ + name: "open", + paths: [{ method: "POST", path: "/open" }], + register: async (scope) => { + scope.post("/open", ok) + }, + }) + await app.register(installExternalRoutes, { + externalRoutes: [gated(), open], + isFeatureEnabled, + }) + + expect( + (await app.inject({ method: "POST", url: "/open" })).statusCode + ).toBe(200) + expect(isFeatureEnabled).not.toHaveBeenCalled() + }) +}) + +describe("csrfExemptions", () => { + it("lists the exempt paths of configured modules", () => { + expect( + csrfExemptions([ + module({ + name: "on", + paths: [ + { method: "POST", path: "/a", csrfExempt: true }, + { method: "POST", path: "/b" }, + { method: "GET", path: "/a" }, + ], + }), + module({ + name: "off", + configured: () => false, + paths: [{ method: "POST", path: "/c", csrfExempt: true }], + }), + ]) + ).toEqual([{ method: "POST", path: "/a" }]) + }) + + describe("for the registry as it stands", () => { + const saved = { ...process.env } + const telegramWebhookEnv = { + TELEGRAM_BOT_TOKEN: "test-token", + TELEGRAM_UPDATE_MODE: "webhook", + TELEGRAM_WEBHOOK_SECRET: "test-webhook-secret", + } + const stripeEnv = { + STRIPE_SECRET_KEY: "sk_test_123", + STRIPE_WEBHOOK_SECRET: "whsec_test", + } + beforeEach(() => { + delete process.env.TELEGRAM_BOT_TOKEN + delete process.env.STRIPE_SECRET_KEY + delete process.env.STRIPE_WEBHOOK_SECRET + process.env.KEYCLOAK_ISSUER = "" + }) + afterEach(() => { + process.env = { ...saved } + }) + + it("has the Telegram webhook, the MCP server and the Stripe webhook", () => { + expect(externalRoutes.map((m) => m.name)).toEqual([ + "telegram", + "mcp", + "stripe", + ]) + }) + + it("is empty when none is configured", () => { + expect(csrfExemptions()).toEqual([]) + }) + + it("exempts the Telegram webhook only when it is configured", () => { + Object.assign(process.env, telegramWebhookEnv) + expect(csrfExemptions()).toEqual([ + { method: "POST", path: "/telegram/webhook" }, + ]) + }) + + it("exempts POST /mcp when Keycloak is configured", () => { + process.env.KEYCLOAK_ISSUER = "https://id.example.org/realms/test" + expect(csrfExemptions()).toEqual([{ method: "POST", path: "/mcp" }]) + }) + + it("exempts the Stripe webhook only when both Stripe secrets are set", () => { + process.env.STRIPE_SECRET_KEY = stripeEnv.STRIPE_SECRET_KEY + expect(csrfExemptions()).toEqual([]) + Object.assign(process.env, stripeEnv) + expect(csrfExemptions()).toEqual([ + { method: "POST", path: "/api/stripe/webhook" }, + ]) + }) + + it("keeps the Stripe webhook answering while the payments flag is off", () => { + const stripe = externalRoutes.find((m) => m.name === "stripe") + expect(stripe).toMatchObject({ feature: "payments", gateWhenOff: false }) + }) + + it("exempts all three when all are configured", () => { + Object.assign(process.env, telegramWebhookEnv, stripeEnv) + process.env.KEYCLOAK_ISSUER = "https://id.example.org/realms/test" + expect(csrfExemptions()).toEqual([ + { method: "POST", path: "/telegram/webhook" }, + { method: "POST", path: "/mcp" }, + { method: "POST", path: "/api/stripe/webhook" }, + ]) + }) + }) +}) + +describe("feature flag gate with a registry key", () => { + const gated = (overrides: Partial = {}) => + module({ + name: "gated", + feature: "telegram_reminders", + paths: [{ method: "POST", path: "/gated" }], + register: async (scope) => { + scope.post("/gated", ok) + }, + ...overrides, + }) + + it("answers 404 while the flag is off, checked per request", async () => { + let enabled = false + const isFeatureEnabled = jest.fn(async () => enabled) + await app.register(installExternalRoutes, { + externalRoutes: [gated()], + isFeatureEnabled, + }) + const off = await app.inject({ method: "POST", url: "/gated" }) + expect(off.statusCode).toBe(404) + enabled = true + const on = await app.inject({ method: "POST", url: "/gated" }) + expect(on.statusCode).toBe(200) + expect(isFeatureEnabled).toHaveBeenCalledWith("telegram_reminders") + }) + + it("does not gate a module with gateWhenOff false", async () => { + const isFeatureEnabled = jest.fn(async () => false) + await app.register(installExternalRoutes, { + externalRoutes: [gated({ gateWhenOff: false })], + isFeatureEnabled, + }) + const response = await app.inject({ method: "POST", url: "/gated" }) + expect(response.statusCode).toBe(200) + expect(isFeatureEnabled).not.toHaveBeenCalled() + }) + + it("does not gate other routes", async () => { + const isFeatureEnabled = jest.fn(async () => false) + app.post("/outside", ok) + await app.register(installExternalRoutes, { + externalRoutes: [gated()], + isFeatureEnabled, + }) + const response = await app.inject({ method: "POST", url: "/outside" }) + expect(response.statusCode).toBe(200) + expect(isFeatureEnabled).not.toHaveBeenCalled() + }) +}) diff --git a/@app/server/__tests__/middleware/installFeatureFlags.test.ts b/@app/server/__tests__/middleware/installFeatureFlags.test.ts new file mode 100644 index 000000000..fa8d83464 --- /dev/null +++ b/@app/server/__tests__/middleware/installFeatureFlags.test.ts @@ -0,0 +1,97 @@ +import { FeatureKey } from "@app/lib" +import { fastify, FastifyInstance } from "fastify" +import { Pool } from "pg" + +import installFeatureFlags from "../../src/middleware/installFeatureFlags" +import { + invalidateFeatureFlags, + isFeatureEnabled, +} from "../../src/utils/featureFlags" + +// Boot reads the real registry, which has no integration-backed keys yet, so +// it is replaced by one fake entry here. +jest.mock("@app/lib", () => ({ + ...jest.requireActual("@app/lib"), + FEATURES: { + server_boot_test: { + description: "Test flag", + requiresEnv: ["SERVER_BOOT_TEST_SECRET"], + }, + }, +})) + +const KEY = "server_boot_test" as FeatureKey + +let pool: Pool +let app: FastifyInstance | null = null + +const boot = async (logger = { warn: jest.fn(), error: jest.fn() }) => { + app = fastify() + app.decorate("rootPgPool", pool) + const log = app.log + Object.assign(log, logger) + await app.register(installFeatureFlags) + await app.ready() + return logger +} + +beforeAll(() => { + pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }) +}) + +afterEach(async () => { + delete process.env.SERVER_BOOT_TEST_SECRET + await app?.close() + app = null + await pool.query( + "delete from app_public.feature_flags where key = 'server_boot_test'" + ) + invalidateFeatureFlags() +}) + +afterAll(() => pool.end()) + +const insertFlag = () => + pool.query( + `insert into app_public.feature_flags (key, state, description) + values ('server_boot_test', 'on', 'Test flag')` + ) + +describe("installFeatureFlags", () => { + it("marks a feature unavailable at boot when its configuration is missing", async () => { + await insertFlag() + const logger = await boot() + const { + rows: [row], + } = await pool.query( + "select available from app_public.feature_flags where key = 'server_boot_test'" + ) + expect(row.available).toBe(false) + expect(logger.warn).toHaveBeenCalledWith( + { feature: "server_boot_test" }, + expect.stringContaining("not configured") + ) + // ...and points isFeatureEnabled at the root pool. + expect(await isFeatureEnabled(KEY)).toBe(false) + }) + + it("marks a configured feature available and enabled", async () => { + await insertFlag() + await pool.query( + "update app_public.feature_flags set available = false where key = 'server_boot_test'" + ) + process.env.SERVER_BOOT_TEST_SECRET = "secret" + const logger = await boot() + expect(logger.warn).not.toHaveBeenCalled() + expect(await isFeatureEnabled(KEY)).toBe(true) + }) + + it("logs registry keys without a row and still boots", async () => { + const logger = await boot() + expect(logger.error).toHaveBeenCalledWith( + { features: ["server_boot_test"] }, + expect.stringContaining("no row") + ) + expect(await isFeatureEnabled(KEY)).toBe(false) + }) +}) diff --git a/@app/server/__tests__/middleware/installKeycloak.test.ts b/@app/server/__tests__/middleware/installKeycloak.test.ts index adbd61f73..37b17ab20 100644 --- a/@app/server/__tests__/middleware/installKeycloak.test.ts +++ b/@app/server/__tests__/middleware/installKeycloak.test.ts @@ -586,6 +586,40 @@ describe("GET /auth/keycloak/callback", () => { expect(user.is_admin).toBe(false) }) + it("stores given and family names on the user and refreshes them on every login", async () => { + const selectNames = () => + pool.query( + `select u.first_name, u.last_name from app_public.users u + join app_public.user_authentications ua on ua.user_id = u.id + where ua.identifier = 'kc-sub-1'` + ) + let res = await doCallback({ + name: "Anna Maria von Wright", + given_name: "Anna Maria", + family_name: "von Wright", + }) + expect(res.statusCode).toBe(302) + let { + rows: [user], + } = await selectNames() + expect(user).toEqual({ first_name: "Anna Maria", last_name: "von Wright" }) + + res = await doCallback({ given_name: "Anna", family_name: "Wright" }) + expect(res.statusCode).toBe(302) + ;({ + rows: [user], + } = await selectNames()) + expect(user).toEqual({ first_name: "Anna", last_name: "Wright" }) + + // A token without both claims leaves the stored names alone + res = await doCallback({ given_name: "Anna" }) + expect(res.statusCode).toBe(302) + ;({ + rows: [user], + } = await selectNames()) + expect(user).toEqual({ first_name: "Anna", last_name: "Wright" }) + }) + it("leaves is_admin untouched when the id token has no realm_access claim", async () => { // A dropped realm-roles mapper makes the roles unknown, which must not // read as "not an admin": stamping false here would demote every admin @@ -607,6 +641,50 @@ describe("GET /auth/keycloak/callback", () => { expect(user.is_admin).toBe(true) }) + describe("ilmo-developer role", () => { + const readRoles = async () => { + const { + rows: [user], + } = await pool.query( + `select u.is_admin, u.is_developer from app_public.users u + join app_public.user_authentications ua on ua.user_id = u.id + where ua.identifier = 'kc-sub-1'` + ) + return user + } + + it("stamps is_developer true when the role is present", async () => { + const res = await doCallback({ + realm_access: { roles: ["membership", "ilmo-admin", "ilmo-developer"] }, + }) + expect(res.statusCode).toBe(302) + expect(await readRoles()).toEqual({ is_admin: true, is_developer: true }) + }) + + it("revokes is_developer at the next login once the role is gone", async () => { + let res = await doCallback({ + realm_access: { roles: ["membership", "ilmo-admin", "ilmo-developer"] }, + }) + expect(res.statusCode).toBe(302) + res = await doCallback({ + realm_access: { roles: ["membership", "ilmo-admin"] }, + }) + expect(res.statusCode).toBe(302) + expect(await readRoles()).toEqual({ is_admin: true, is_developer: false }) + }) + + it("leaves is_developer untouched when the id token has no realm_access claim", async () => { + let res = await doCallback({ + realm_access: { roles: ["membership", "ilmo-admin", "ilmo-developer"] }, + }) + expect(res.statusCode).toBe(302) + res = await doCallback({ realm_access: undefined }) + expect(res.statusCode).toBe(302) + expect(res.headers.location).toBe("/event/foo") + expect(await readRoles()).toEqual({ is_admin: true, is_developer: true }) + }) + }) + it("sends a cancelled sign-in home without an error", async () => { const login = await startLogin() mockOidc.authorizationCodeGrant.mockRejectedValue( diff --git a/@app/server/__tests__/mutations/__snapshots__/createCheckoutSession.test.ts.snap b/@app/server/__tests__/mutations/__snapshots__/createCheckoutSession.test.ts.snap new file mode 100644 index 000000000..dd6bc923b --- /dev/null +++ b/@app/server/__tests__/mutations/__snapshots__/createCheckoutSession.test.ts.snap @@ -0,0 +1,55 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`createCheckoutSession creates a card-only Checkout Session with two line items and metadata 1`] = ` +{ + "allowed_payment_method_types": [ + "card", + ], + "cancel_url": "[rootUrl]/fi/pay/[updateToken]?status=cancelled", + "client_reference_id": "[registrationId]", + "customer_email": "[email]", + "line_items": [ + { + "price_data": { + "currency": "eur", + "product_data": { + "name": "[eventName] – Kiintiö 0", + }, + "unit_amount": 1800, + }, + "quantity": 1, + }, + { + "price_data": { + "currency": "eur", + "product_data": { + "name": "Service fee / Palvelumaksu", + }, + "unit_amount": 25, + }, + "quantity": 1, + }, + ], + "locale": "fi", + "metadata": { + "event_id": "[eventId]", + "event_slug": "[eventSlug]", + "ilmo_url": "[rootUrl]", + "payment_id": "[paymentId]", + "quota_id": "[quotaId]", + "registration_id": "[registrationId]", + }, + "mode": "payment", + "payment_intent_data": { + "metadata": { + "event_id": "[eventId]", + "event_slug": "[eventSlug]", + "ilmo_url": "[rootUrl]", + "payment_id": "[paymentId]", + "quota_id": "[quotaId]", + "registration_id": "[registrationId]", + }, + }, + "success_url": "[rootUrl]/fi/pay/[updateToken]?status=success", +} +`; diff --git a/@app/server/__tests__/mutations/__snapshots__/createEvent.test.ts.snap b/@app/server/__tests__/mutations/__snapshots__/createEvent.test.ts.snap index a48572514..e88010023 100644 --- a/@app/server/__tests__/mutations/__snapshots__/createEvent.test.ts.snap +++ b/@app/server/__tests__/mutations/__snapshots__/createEvent.test.ts.snap @@ -11,6 +11,10 @@ exports[`CreateEvent can create event while logged in 1`] = ` "eventEndTime": "[timestamp-2]", "eventStartTime": "[timestamp-1]", "headerImageFile": "[random-5]", + "highlightText": { + "en": "Big party", + "fi": "Kova meno", + }, "id": "[id-1]", "isDraft": false, "isHighlighted": true, @@ -75,7 +79,7 @@ exports[`CreateEvent must specify at least one event quota 1`] = ` "severity": "ERROR", "where": "PL/pgSQL function app_public.create_event_quotas(uuid,app_public.create_event_quotas[]) line 12 at RAISE SQL statement "SELECT * from app_public.create_event_quotas(v_event.id, quotas)" -PL/pgSQL function app_public.create_event(app_public.event_input,app_public.create_event_quotas[],app_public.create_event_questions[]) line 45 at PERFORM", +PL/pgSQL function app_public.create_event(app_public.event_input,app_public.create_event_quotas[],app_public.create_event_questions[]) line 47 at PERFORM", }, }, "locations": [ diff --git a/@app/server/__tests__/mutations/__snapshots__/createRegistration.test.ts.snap b/@app/server/__tests__/mutations/__snapshots__/createRegistration.test.ts.snap index fd3e90c73..71087c2c0 100644 --- a/@app/server/__tests__/mutations/__snapshots__/createRegistration.test.ts.snap +++ b/@app/server/__tests__/mutations/__snapshots__/createRegistration.test.ts.snap @@ -1,5 +1,32 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`CreateRegistration can create a registration with spaces in first and last name 1`] = ` +{ + "data": { + "createRegistration": { + "registration": { + "createdAt": "[timestamp-1]", + "event": { + "id": "[id-3]", + "slug": "[random-3]", + }, + "fullName": "Anna Maria von Wright", + "id": "[id-1]", + "position": 1, + "quota": { + "id": "[id-2]", + "position": 0, + "priceCents": 0, + "size": "[random-2]", + "title": "[random-1]", + }, + "status": "IN_QUOTA", + }, + }, + }, +} +`; + exports[`CreateRegistration can create registration 1`] = ` { "data": { @@ -16,6 +43,7 @@ exports[`CreateRegistration can create registration 1`] = ` "quota": { "id": "[id-2]", "position": 0, + "priceCents": 0, "size": "[random-2]", "title": "[random-1]", }, @@ -26,7 +54,7 @@ exports[`CreateRegistration can create registration 1`] = ` } `; -exports[`CreateRegistration can't create a registration if first or last name contains spaces 1`] = ` +exports[`CreateRegistration can't create a registration if first or last name is blank 1`] = ` { "data": { "createRegistration": null, @@ -69,7 +97,7 @@ PL/pgSQL function app_public.create_registration(text,uuid,uuid,text,text,citext } `; -exports[`CreateRegistration can't create a registration if first or last name contains spaces 2`] = ` +exports[`CreateRegistration can't create a registration if first or last name is blank 2`] = ` { "data": { "createRegistration": null, diff --git a/@app/server/__tests__/mutations/__snapshots__/updateEvent.test.ts.snap b/@app/server/__tests__/mutations/__snapshots__/updateEvent.test.ts.snap index 6fd44d52d..bcb923a90 100644 --- a/@app/server/__tests__/mutations/__snapshots__/updateEvent.test.ts.snap +++ b/@app/server/__tests__/mutations/__snapshots__/updateEvent.test.ts.snap @@ -11,6 +11,7 @@ exports[`UpdateEvent can update an existing event 1`] = ` "eventEndTime": "[timestamp-2]", "eventStartTime": "[timestamp-1]", "headerImageFile": "[random-5]", + "highlightText": null, "id": "[id-1]", "isDraft": false, "isHighlighted": false, @@ -75,7 +76,7 @@ exports[`UpdateEvent must specify at least one event quota 1`] = ` "severity": "ERROR", "where": "PL/pgSQL function app_public.update_event_quotas(uuid,app_public.update_event_quotas[]) line 14 at RAISE SQL statement "SELECT * from app_public.update_event_quotas(id, quotas)" -PL/pgSQL function app_public.update_event(uuid,app_public.event_input,app_public.update_event_quotas[],app_public.update_event_questions[]) line 30 at PERFORM", +PL/pgSQL function app_public.update_event(uuid,app_public.event_input,app_public.update_event_quotas[],app_public.update_event_questions[]) line 34 at PERFORM", }, }, "locations": [ diff --git a/@app/server/__tests__/mutations/__snapshots__/updateRegistration.test.ts.snap b/@app/server/__tests__/mutations/__snapshots__/updateRegistration.test.ts.snap index a9e22aa44..6b8dc4e9c 100644 --- a/@app/server/__tests__/mutations/__snapshots__/updateRegistration.test.ts.snap +++ b/@app/server/__tests__/mutations/__snapshots__/updateRegistration.test.ts.snap @@ -1,5 +1,32 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`UpdateRegistration admin can update registration after event signup has closed 1`] = ` +{ + "data": { + "updateRegistration": { + "registration": { + "answers": "[random-3]", + "createdAt": "[timestamp-1]", + "firstName": "Päivi", + "fullName": "Päivi Tetty", + "id": "[id-1]", + "lastName": "Tetty", + "position": 1, + "quota": { + "id": "[id-2]", + "position": 0, + "priceCents": 0, + "size": "[random-2]", + "title": "[random-1]", + }, + "status": "IN_QUOTA", + "updatedAt": "[timestamp-2]", + }, + }, + }, +} +`; + exports[`UpdateRegistration can update a registration with a valid updateToken 1`] = ` { "data": { @@ -15,6 +42,7 @@ exports[`UpdateRegistration can update a registration with a valid updateToken 1 "quota": { "id": "[id-2]", "position": 0, + "priceCents": 0, "size": "[random-2]", "title": "[random-1]", }, @@ -37,7 +65,7 @@ exports[`UpdateRegistration can't update registration if registration token is n "exception": { "code": "NTFND", "severity": "ERROR", - "where": "PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 12 at RAISE", + "where": "PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 13 at RAISE", }, }, "locations": [ @@ -68,7 +96,7 @@ exports[`UpdateRegistration can't update registration if required answers are no "severity": "ERROR", "where": "PL/pgSQL function app_public.validate_registration_answers(uuid,uuid[],jsonb) line 50 at RAISE SQL statement "SELECT app_public.validate_registration_answers(v_registration_secret.event_id, v_required_question_ids, answers)" -PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 18 at PERFORM", +PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 26 at PERFORM", }, }, "locations": [ @@ -85,3 +113,32 @@ PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 18 a ], } `; + +exports[`UpdateRegistration can't update registration once event signup has closed 1`] = ` +{ + "data": { + "updateRegistration": null, + }, + "errors": [ + { + "extensions": { + "exception": { + "code": "DNIED", + "severity": "ERROR", + "where": "PL/pgSQL function app_public.update_registration(text,text,text,jsonb) line 20 at RAISE", + }, + }, + "locations": [ + { + "column": 3, + "line": 2, + }, + ], + "message": "Updating a registration after event signup has closed is not allowed. Please contact the event organizers.", + "path": [ + "updateRegistration", + ], + }, + ], +} +`; diff --git a/@app/server/__tests__/mutations/claimRegistrationToken.test.ts b/@app/server/__tests__/mutations/claimRegistrationToken.test.ts index 95f36ca71..a4c82ce5c 100644 --- a/@app/server/__tests__/mutations/claimRegistrationToken.test.ts +++ b/@app/server/__tests__/mutations/claimRegistrationToken.test.ts @@ -1,12 +1,16 @@ import { ClaimRegistrationTokenDocument } from "@app/graphql" +import { ExecutionResult } from "graphql" import { asRoot, createEventDataAndLogin, + createSession, deleteTestData, + poolFromUrl, runGraphQLQuery, setup, teardown, + TEST_DATABASE_URL, } from "../helpers" beforeEach(deleteTestData) @@ -75,7 +79,7 @@ describe("ClaimRegistrationToken", () => { expect(registrationRows[0].email).toBeNull() const rateLimitId = `${eventId}:${quotaId}` - const redisKey = `rate-limit:claimRegistrationToken:${rateLimitId}:${req.ip}` + const redisKey = `rate-limit:claimRegistrationToken:${rateLimitId}:ip:${req.ip}` const value = await redisClient.get(redisKey) // Redis should contain rate limit value after calling @@ -85,6 +89,53 @@ describe("ClaimRegistrationToken", () => { ) }) + it("rate limits a signed-in user per user, not per session", async () => { + const { events, quotas, users, session } = await createEventDataAndLogin() + const eventId = events[0].id + const quotaId = quotas[0].id + const userId = users[0].id + + const pool = poolFromUrl(TEST_DATABASE_URL!) + const client = await pool.connect() + let otherSession: Awaited> + try { + otherSession = await createSession(client, userId) + } finally { + client.release() + } + + const claim = (sessionId: string) => + runGraphQLQuery( + ClaimRegistrationTokenDocument, + { input: { eventId, quotaId } }, + { user: { sessionId } }, + (json) => json, + true, + false + ) + + for (let i = 0; i < 3; i++) { + const json = (await claim(session.uuid)) as ExecutionResult + expect(json.errors).toBeFalsy() + } + + // A fresh session for the same user must not reset the limit. + await runGraphQLQuery( + ClaimRegistrationTokenDocument, + { input: { eventId, quotaId } }, + { user: { sessionId: otherSession.uuid } }, + async (json, { redisClient }) => { + expect(json.errors).toBeTruthy() + expect(json.errors![0].extensions.exception.code).toEqual("RLIMIT") + + const key = `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:user:${userId}` + expect(await redisClient.get(key)).toEqual("3") + }, + true, + false + ) + }) + it("can't claim a token when eventId is incorrect", async () => { const { quotas } = await createEventDataAndLogin() const quotaId = quotas[0].id diff --git a/@app/server/__tests__/mutations/createCheckoutSession.test.ts b/@app/server/__tests__/mutations/createCheckoutSession.test.ts new file mode 100644 index 000000000..60a13f380 --- /dev/null +++ b/@app/server/__tests__/mutations/createCheckoutSession.test.ts @@ -0,0 +1,406 @@ +import { CHECKOUT_RATE_LIMIT } from "../../src/plugins/PaymentsPlugin" +import { + deleteTestData, + poolFromUrl, + runGraphQLQuery, + setFeatureFlag, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" +import { + configureStripeForEachTest, + createPaidEvent, + insertPayment, + paymentsOfEvent, + stripeMock, +} from "../payments" + +jest.mock("stripe", () => require("../stripeMock").mockStripeModule()) + +beforeEach(deleteTestData) +beforeAll(setup) +afterAll(teardown) +configureStripeForEachTest() + +const pool = () => poolFromUrl(TEST_DATABASE_URL) + +beforeEach(() => setFeatureFlag(pool(), "payments", "on")) + +const CreateCheckoutSessionMutation = ` + mutation CreateCheckoutSession($updateToken: String!, $language: String) { + createCheckoutSession(updateToken: $updateToken, language: $language) { + url + } + } +` + +let sessionCounter = 0 + +beforeEach(() => { + const { sessions } = stripeMock().checkout + sessions.create.mockReset() + sessions.expire.mockReset() + sessions.retrieve.mockReset() + sessions.create.mockImplementation(async () => { + sessionCounter++ + return { + id: `cs_test_${sessionCounter}`, + url: `https://checkout.stripe.com/c/pay/cs_test_${sessionCounter}`, + } + }) + sessions.expire.mockImplementation(async (id: string) => ({ + id, + status: "expired", + })) +}) + +async function createCheckoutSession(updateToken: string, language?: string) { + return runGraphQLQuery( + CreateCheckoutSessionMutation, + { updateToken, language }, + {}, + () => {}, + true, + false + ) +} + +async function expectRefusal(updateToken: string, code: string) { + const result = await createCheckoutSession(updateToken) + expect(result.data?.createCheckoutSession).toBeFalsy() + expect(result.errors).toHaveLength(1) + expect(result.errors![0].extensions!.exception).toMatchObject({ code }) + expect(stripeMock().checkout.sessions.create).not.toHaveBeenCalled() +} + +/** Replaces the generated ids in the params so they can be snapshotted. */ +function maskIds(value: unknown, ids: Record): unknown { + let json = JSON.stringify(value) + for (const [name, id] of Object.entries(ids)) { + json = json.split(id).join(`[${name}]`) + } + return JSON.parse(json) +} + +describe("createCheckoutSession", () => { + it("creates a card-only Checkout Session with two line items and metadata", async () => { + const { event, quota, registrations, tokens } = await createPaidEvent() + const [registration] = registrations + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + expect(result.data!.createCheckoutSession).toEqual({ + url: expect.stringMatching( + /^https:\/\/checkout\.stripe\.com\/c\/pay\/cs_test_\d+$/ + ), + }) + + const [payment] = await paymentsOfEvent(pool(), event.id) + expect(payment).toMatchObject({ + registration_id: registration.id, + event_id: event.id, + quota_id: quota.id, + event_name: event.name, + quota_title: quota.title, + method: "STRIPE", + status: "PENDING", + ticket_amount_cents: 1800, + service_fee_cents: 25, + currency: "eur", + stripe_checkout_session_id: `cs_test_${sessionCounter}`, + paid_at: null, + }) + + const { create } = stripeMock().checkout.sessions + expect(create).toHaveBeenCalledTimes(1) + const [params, options] = create.mock.calls[0] + expect(options).toEqual({ + idempotencyKey: `checkout-session-${payment.id}`, + }) + expect( + maskIds(params, { + registrationId: registration.id, + eventId: event.id, + quotaId: quota.id, + paymentId: payment.id, + updateToken: tokens[0], + eventSlug: event.slug, + email: registration.email, + eventName: event.name.fi, + rootUrl: process.env.ROOT_URL!, + }) + ).toMatchSnapshot() + }) + + it.each([ + ["se", "sv", "se"], + ["xx", "fi", "fi"], + ])( + "uses language %p as Stripe locale %p and returns to /%s/pay", + async (language, locale, path) => { + const { event, tokens } = await createPaidEvent() + const result = await createCheckoutSession(tokens[0], language) + expect(result.errors).toBeFalsy() + const [params] = stripeMock().checkout.sessions.create.mock.calls[0] + expect(params.locale).toBe(locale) + const payUrl = `${process.env.ROOT_URL}/${path}/pay/${tokens[0]}` + expect(params.success_url).toBe(`${payUrl}?status=success`) + expect(params.cancel_url).toBe(`${payUrl}?status=cancelled`) + const productName = params.line_items[0].price_data.product_data.name + expect(productName).toBe( + `${language === "en" || language === "se" ? event.name.en : event.name.fi} – ${ + language === "en" || language === "se" ? "Quota 0" : "Kiintiö 0" + }` + ) + } + ) + + it("expires the registration's older pending session", async () => { + const { event, tokens } = await createPaidEvent() + + await createCheckoutSession(tokens[0]) + const firstSessionId = `cs_test_${sessionCounter}` + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + + const { expire } = stripeMock().checkout.sessions + expect(expire).toHaveBeenCalledTimes(1) + expect(expire).toHaveBeenCalledWith(firstSessionId) + const payments = await paymentsOfEvent(pool(), event.id) + expect( + payments.map((p) => [p.stripe_checkout_session_id, p.status]) + ).toEqual([ + [firstSessionId, "EXPIRED"], + [`cs_test_${sessionCounter}`, "PENDING"], + ]) + }) + + it("accepts an older session that Stripe already expired", async () => { + const { event, registrations, tokens } = await createPaidEvent() + await insertPayment(pool(), registrations[0], { + status: "PENDING", + sessionId: "cs_test_old", + }) + const { expire, retrieve } = stripeMock().checkout.sessions + expire.mockRejectedValueOnce(new Error("Session is not open")) + retrieve.mockResolvedValueOnce({ id: "cs_test_old", status: "expired" }) + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + const payments = await paymentsOfEvent(pool(), event.id) + expect(payments.map((p) => p.status)).toEqual(["EXPIRED", "PENDING"]) + }) + + it("refuses while an older session's payment is being confirmed", async () => { + const { event, registrations, tokens } = await createPaidEvent() + await insertPayment(pool(), registrations[0], { + status: "PENDING", + sessionId: "cs_test_paid", + }) + const { expire, retrieve } = stripeMock().checkout.sessions + expire.mockRejectedValueOnce(new Error("Session is not open")) + retrieve.mockResolvedValueOnce({ id: "cs_test_paid", status: "complete" }) + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors![0].extensions!.exception).toMatchObject({ + code: "ALREADY_PAID", + }) + expect(stripeMock().checkout.sessions.create).not.toHaveBeenCalled() + // Left for the webhook to mark paid + const payments = await paymentsOfEvent(pool(), event.id) + expect(payments.map((p) => p.status)).toEqual(["PENDING"]) + }) + + it("hides Stripe's error text behind CHECKOUT_FAILED and leaves no payment row behind", async () => { + const { event, tokens } = await createPaidEvent() + stripeMock().checkout.sessions.create.mockRejectedValueOnce( + new Error("Invalid API Key provided: sk_live_****1234") + ) + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toHaveLength(1) + const [error] = result.errors! + expect(error.extensions!.exception).toMatchObject({ + code: "CHECKOUT_FAILED", + }) + expect(JSON.stringify(error)).not.toMatch(/sk_live|Invalid API Key/) + expect(await paymentsOfEvent(pool(), event.id)).toEqual([]) + }) + + it("holds no lock on the registration while Stripe is called", async () => { + const { registrations, tokens } = await createPaidEvent() + const { create } = stripeMock().checkout.sessions + let lockedDuringCall: boolean | null = null + create.mockImplementationOnce(async () => { + const client = await pool().connect() + try { + await client.query("begin") + await client.query( + "select 1 from app_public.registrations where id = $1 for update nowait", + [registrations[0].id] + ) + lockedDuringCall = false + } catch { + lockedDuringCall = true + } finally { + await client.query("rollback") + client.release() + } + return { + id: "cs_test_unlocked", + url: "https://checkout.stripe.com/c/pay/cs_test_unlocked", + } + }) + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + expect(lockedDuringCall).toBe(false) + }) + + it("gives up its session when a newer click expired its payment meanwhile", async () => { + const { event, registrations, tokens } = await createPaidEvent() + const { create, expire } = stripeMock().checkout.sessions + create.mockImplementationOnce(async () => { + // A second click's first step expires this call's pending row + await pool().query( + `update app_public.payments set status = 'EXPIRED' + where registration_id = $1 and status = 'PENDING'`, + [registrations[0].id] + ) + return { + id: "cs_test_superseded", + url: "https://checkout.stripe.com/c/pay/cs_test_superseded", + } + }) + + const result = await createCheckoutSession(tokens[0]) + expect(result.errors![0].extensions!.exception).toMatchObject({ + code: "CHECKOUT_FAILED", + }) + expect(expire).toHaveBeenCalledWith("cs_test_superseded") + expect(await paymentsOfEvent(pool(), event.id)).toEqual([]) + }) + + it(`refuses more than ${CHECKOUT_RATE_LIMIT} attempts per registration and requester before calling Stripe`, async () => { + const { tokens } = await createPaidEvent({ registrationCount: 2 }) + const { create } = stripeMock().checkout.sessions + for (let i = 0; i < CHECKOUT_RATE_LIMIT; i++) { + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + } + expect(create).toHaveBeenCalledTimes(CHECKOUT_RATE_LIMIT) + + const limited = await createCheckoutSession(tokens[0]) + expect(limited.errors![0].extensions!.exception).toMatchObject({ + code: "RLIMIT", + }) + expect(create).toHaveBeenCalledTimes(CHECKOUT_RATE_LIMIT) + + // Another registration has its own limit + const other = await createCheckoutSession(tokens[1]) + expect(other.errors).toBeFalsy() + }) + + describe("refusals", () => { + it("PAYMENTS_DISABLED while payments are off", async () => { + const { tokens } = await createPaidEvent() + await setFeatureFlag(pool(), "payments", "off") + const result = await createCheckoutSession(tokens[0]) + expect(result.errors![0].extensions!.exception).toMatchObject({ + code: "PAYMENTS_DISABLED", + }) + }) + + it.each< + [ + string, + (data: Awaited>) => Promise, + ] + >([ + ["an unknown token", async () => "not-a-token"], + [ + "an unfinished registration", + async ({ registrations, tokens }) => { + await pool().query( + "update app_public.registrations set is_finished = false where id = $1", + [registrations[0].id] + ) + return tokens[0] + }, + ], + ])("REGISTRATION_NOT_FOUND for %s", async (_name, tokenOf) => { + const token = await tokenOf(await createPaidEvent()) + await expectRefusal(token, "REGISTRATION_NOT_FOUND") + }) + + it("PAYMENT_NOT_REQUIRED for a free quota", async () => { + const { tokens } = await createPaidEvent({ priceCents: 0 }) + await expectRefusal(tokens[0], "PAYMENT_NOT_REQUIRED") + }) + + it.each(["STRIPE", "MANUAL"] as const)( + "ALREADY_PAID for a %s payment", + async (method) => { + const { registrations, tokens } = await createPaidEvent() + await insertPayment(pool(), registrations[0], { method }) + await expectRefusal(tokens[0], "ALREADY_PAID") + } + ) + + it("IN_QUEUE for a queued registration", async () => { + const { registrations, tokens } = await createPaidEvent({ + quotaSize: 1, + registrationCount: 2, + }) + const { rows } = await pool().query( + `select id, status from app_hidden.registrations_status_and_position + where id = any($1)`, + [registrations.map((r) => r.id)] + ) + const queued = rows.find((r) => r.status === "IN_QUEUE") + const inQuota = rows.find((r) => r.status === "IN_QUOTA") + const tokenOf = (id: string) => + tokens[registrations.findIndex((r) => r.id === id)] + + await expectRefusal(tokenOf(queued.id), "IN_QUEUE") + const result = await createCheckoutSession(tokenOf(inQuota.id)) + expect(result.errors).toBeFalsy() + }) + + it("PAYMENT_NOT_OPEN while signup is open", async () => { + const { tokens } = await createPaidEvent({ signupClosed: false }) + await expectRefusal(tokens[0], "PAYMENT_NOT_OPEN") + }) + + it("PAYMENT_NOT_OPEN again when registration is reopened", async () => { + const { event, tokens } = await createPaidEvent() + await pool().query( + `update app_public.events + set registration_end_time = now() + interval '1 day' + where id = $1`, + [event.id] + ) + await expectRefusal(tokens[0], "PAYMENT_NOT_OPEN") + }) + + it("charges the quota price in effect at checkout", async () => { + const { quota, tokens } = await createPaidEvent({ priceCents: 1800 }) + await pool().query( + "update app_public.quotas set price_cents = 2200 where id = $1", + [quota.id] + ) + const result = await createCheckoutSession(tokens[0]) + expect(result.errors).toBeFalsy() + const [params] = stripeMock().checkout.sessions.create.mock.calls.at(-1)! + expect(params.line_items[0].price_data.unit_amount).toBe(2200) + const { + rows: [payment], + } = await pool().query( + "select ticket_amount_cents from app_public.payments where quota_id = $1", + [quota.id] + ) + expect(payment.ticket_amount_cents).toBe(2200) + }) + }) +}) diff --git a/@app/server/__tests__/mutations/createEvent.test.ts b/@app/server/__tests__/mutations/createEvent.test.ts index e3d1a8696..65feb8da1 100644 --- a/@app/server/__tests__/mutations/createEvent.test.ts +++ b/@app/server/__tests__/mutations/createEvent.test.ts @@ -114,6 +114,7 @@ describe("CreateEvent", () => { ownerOrganizationId: organization.id, categoryId: eventCategory.id, isHighlighted: true, + highlightText: { fi: "Kova meno", en: "Big party" }, isDraft: false, eventStartTime: day.add(1, "days").toISOString(), eventEndTime: day.add(2, "days").toISOString(), @@ -165,6 +166,11 @@ describe("CreateEvent", () => { if (questionRows.length !== 3) { throw new Error("Wrong amount of questions after mutation!") } + + expect(eventRows[0].highlight_text).toEqual({ + fi: "Kova meno", + en: "Big party", + }) } ) }) diff --git a/@app/server/__tests__/mutations/createRegistration.test.ts b/@app/server/__tests__/mutations/createRegistration.test.ts index c36e82bf2..f80da72e6 100644 --- a/@app/server/__tests__/mutations/createRegistration.test.ts +++ b/@app/server/__tests__/mutations/createRegistration.test.ts @@ -112,9 +112,8 @@ describe("CreateRegistration", () => { expect(rateLimitjobs).toHaveLength(1) const [rateLimitJob] = rateLimitjobs - expect(rateLimitJob.payload).toMatchObject({ - eventId: eventId, - ipAddress: req.ip, + expect(rateLimitJob.payload).toEqual({ + key: `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:ip:${req.ip}`, }) const confirmationEmailJobs = await getJobs( @@ -153,7 +152,7 @@ describe("CreateRegistration", () => { // Redis should not contain a rate limiting key after // successful registration const rateLimitId = `${eventId}:${quotaId}` - const key = `rate-limit:claimRegistrationToken:${rateLimitId}:127.1.1.1` + const key = `rate-limit:claimRegistrationToken:${rateLimitId}:ip:127.1.1.1` const value = await redisClient.get(key) expect(value).toEqual(null) // TODO: Figure out a way to test gdpr__delete_event_registrations @@ -373,7 +372,7 @@ describe("CreateRegistration", () => { ) }) - it("can't create a registration if first or last name contains spaces", async () => { + it("can't create a registration if first or last name is blank", async () => { const { quotas, events } = await createEventDataAndLogin({ questionOptions: { create: false }, registrationOptions: { create: false }, @@ -426,7 +425,7 @@ describe("CreateRegistration", () => { quotaId, registrationToken, firstName: "Testname", - lastName: "Last name", + lastName: " ", email: "testuser@example.com", }, }, @@ -448,6 +447,44 @@ describe("CreateRegistration", () => { ) }) + it("can create a registration with spaces in first and last name", async () => { + const { quotas, events } = await createEventDataAndLogin({ + questionOptions: { create: false }, + registrationOptions: { create: false }, + }) + const eventId = events[0].id + const quotaId = quotas[0].id + + const { registrationToken } = await claimRegistrationToken(eventId, quotaId) + + await runGraphQLQuery( + CreateEventRegistrationDocument, + + // GraphQL variables: + { + input: { + eventId, + quotaId, + registrationToken, + firstName: "Anna Maria", + lastName: "von Wright", + email: "testuser@example.com", + }, + }, + + // Additional props to add to `req` (e.g. `user: {sessionId: '...'}`) + {}, + + // This function runs all your test assertions: + async (json) => { + expect(json.errors).toBeFalsy() + + const registration = json.data!.createRegistration.registration + expect(registration.fullName).toEqual("Anna Maria von Wright") + } + ) + }) + it("can't create a registration if a registration already exists with the same email", async () => { const { quotas, events, registrations } = await createEventDataAndLogin({ questionOptions: { create: false }, diff --git a/@app/server/__tests__/mutations/deleteRegistration.test.ts b/@app/server/__tests__/mutations/deleteRegistration.test.ts index 482b30285..b453f411a 100644 --- a/@app/server/__tests__/mutations/deleteRegistration.test.ts +++ b/@app/server/__tests__/mutations/deleteRegistration.test.ts @@ -9,13 +9,33 @@ import { deleteTestData, getEmails, getJobs, + poolFromUrl, runGraphQLQuery, runJobs, setup, sleep, teardown, + TEST_DATABASE_URL, } from "../helpers" +// Registrations created in one transaction share created_at, so their order +// is read from the positions table instead of assumed from creation order. +async function registrationIdsByStatus(eventId: string) { + const { rows } = await poolFromUrl(TEST_DATABASE_URL!).query( + `select id, status + from app_hidden.registrations_status_and_position + where event_id = $1`, + [eventId] + ) + const idsWith = (status: string) => + rows.filter((row) => row.status === status).map((row) => row.id) + return { + inQuota: idsWith("IN_QUOTA"), + inOpenQuota: idsWith("IN_OPEN_QUOTA"), + inQueue: idsWith("IN_QUEUE"), + } +} + beforeEach(deleteTestData) beforeAll(setup) afterAll(teardown) @@ -160,8 +180,14 @@ describe("DeleteRegistration", () => { quotaOptions: { create: true, amount: 1, size: 2 }, }) const event = events[0] - const receivedSpot = registrations[2] - const updateToken = registrationSecrets[1].update_token + const { + inQuota: [leavingId], + inQueue: [queuedId], + } = await registrationIdsByStatus(event.id) + const receivedSpot = registrations.find((r) => r.id === queuedId)! + const updateToken = registrationSecrets.find( + (secret) => secret.registration_id === leavingId + )!.update_token await runGraphQLQuery( DeleteEventRegistrationDocument, @@ -190,8 +216,7 @@ describe("DeleteRegistration", () => { id: receivedSpot.id, event_id: receivedSpot.event_id, quota_id: receivedSpot.quota_id, - status: "IN_QUEUE", - position: 1, + status: "IN_QUOTA", }, }) @@ -220,8 +245,14 @@ describe("DeleteRegistration", () => { registrationOptions: { create: true, amount: 3 }, }) const event = events[0] - const receivedSpot = registrations[2] - const updateToken = registrationSecrets[1].update_token + const { + inOpenQuota: [leavingId], + inQueue: [queuedId], + } = await registrationIdsByStatus(event.id) + const receivedSpot = registrations.find((r) => r.id === queuedId)! + const updateToken = registrationSecrets.find( + (secret) => secret.registration_id === leavingId + )!.update_token await runGraphQLQuery( DeleteEventRegistrationDocument, @@ -250,7 +281,7 @@ describe("DeleteRegistration", () => { id: receivedSpot.id, event_id: receivedSpot.event_id, quota_id: receivedSpot.quota_id, - status: "IN_QUEUE", + status: "IN_OPEN_QUOTA", position: 1, }, }) diff --git a/@app/server/__tests__/mutations/setFeatureFlag.test.ts b/@app/server/__tests__/mutations/setFeatureFlag.test.ts new file mode 100644 index 000000000..88de3c484 --- /dev/null +++ b/@app/server/__tests__/mutations/setFeatureFlag.test.ts @@ -0,0 +1,106 @@ +import { FeatureKey } from "@app/lib" + +import { isFeatureEnabled } from "../../src/utils/featureFlags" +import { + createUserAndLogIn, + deleteTestData, + poolFromUrl, + runGraphQLQuery, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" + +// The registry has no keys yet; this test uses its own row. +const KEY = "server_mutation_test" as FeatureKey + +const SET_FEATURE_FLAG = ` + mutation SetFeatureFlag($key: String!, $state: FeatureState!) { + setFeatureFlag(input: { key: $key, state: $state }) { + featureFlag { + key + state + } + } + } +` + +const pool = () => poolFromUrl(TEST_DATABASE_URL) + +beforeAll(setup) +afterAll(teardown) + +beforeEach(async () => { + await deleteTestData() + await pool().query( + `insert into app_public.feature_flags (key, state, description) + values ($1, 'off', 'Test flag')`, + [KEY] + ) +}) + +afterEach(async () => { + await pool().query("delete from app_public.feature_flags where key = $1", [ + KEY, + ]) + await pool().query( + "delete from app_private.feature_flag_events where key = $1", + [KEY] + ) +}) + +describe("SetFeatureFlag", () => { + it("is visible to server-side gates as soon as the switch commits", async () => { + const { session } = await createUserAndLogIn({ + isAdmin: true, + isDeveloper: true, + }) + // Fill the cache with the old state. + expect(await isFeatureEnabled(KEY)).toBe(false) + + await runGraphQLQuery( + SET_FEATURE_FLAG, + { key: KEY, state: "ON" }, + { user: { sessionId: session.uuid } }, + (json) => { + expect(json.errors).toBeFalsy() + expect(json.data!.setFeatureFlag.featureFlag).toEqual({ + key: KEY, + state: "ON", + }) + }, + false, // commit + false + ) + + expect(await isFeatureEnabled(KEY)).toBe(true) + }) + + it("keeps serving the cached state for a change made outside the server", async () => { + // The counterpart of the test above: without the mutation passing through + // the server, the cache holds the old state until its TTL runs out. + expect(await isFeatureEnabled(KEY)).toBe(false) + await pool().query( + "update app_public.feature_flags set state = 'on' where key = $1", + [KEY] + ) + expect(await isFeatureEnabled(KEY)).toBe(false) + }) + + it("is refused for an admin without the developer role", async () => { + const { session } = await createUserAndLogIn({ isAdmin: true }) + + await runGraphQLQuery( + SET_FEATURE_FLAG, + { key: KEY, state: "ON" }, + { user: { sessionId: session.uuid } }, + (json) => { + expect(json.errors).toBeTruthy() + expect(json.errors![0].extensions.exception.code).toBe("DNIED") + }, + true, + false + ) + expect(await isFeatureEnabled(KEY)).toBe(false) + }) +}) diff --git a/@app/server/__tests__/mutations/updateEvent.test.ts b/@app/server/__tests__/mutations/updateEvent.test.ts index b4567da4a..af17d4c0e 100644 --- a/@app/server/__tests__/mutations/updateEvent.test.ts +++ b/@app/server/__tests__/mutations/updateEvent.test.ts @@ -191,6 +191,76 @@ describe("UpdateEvent", () => { ) }) + it("updates highlight text together with isHighlighted", async () => { + const { events, quotas, questions, session } = + await createEventDataAndLogin({ + userOptions: { create: true, isAdmin: true }, + }) + const event = events[0] + const quotaInput = quotas.map((q) => + pick(camelizeKeys(q), ["id", "position", "size", "title"]) + ) + const questionInput = questions.map((q) => + pick(camelizeKeys(q), [ + "id", + "position", + "type", + "label", + "isRequired", + "data", + ]) + ) + + // Runs the update without rolling back, so each step builds on the last + const updateAndExpectHighlightText = ( + eventInput: object, + expected: object | null + ) => + runGraphQLQuery( + UpdateEventDocument, + { + input: { + id: event.id, + // The rich text validator requires a description on every update + event: { description: event.description, ...eventInput }, + quotas: quotaInput, + questions: questionInput, + }, + }, + { user: { sessionId: session.uuid } }, + async (json, { pgClient }) => { + expect(json.errors).toBeFalsy() + const { rows } = await asRoot(pgClient, () => + pgClient.query( + `SELECT highlight_text FROM app_public.events WHERE id = $1`, + [event.id] + ) + ) + expect(rows[0].highlight_text).toEqual(expected) + }, + false, + false + ) + + // Set + await updateAndExpectHighlightText( + { isHighlighted: true, highlightText: { fi: "Kova meno" } }, + { fi: "Kova meno" } + ) + + // Kept when isHighlighted is not part of the update + await updateAndExpectHighlightText( + { location: "Uusi paikka" }, + { fi: "Kova meno" } + ) + + // Cleared with null + await updateAndExpectHighlightText( + { isHighlighted: true, highlightText: null }, + null + ) + }) + it("can't update an event if not logged in as admin", async () => { const { events, quotas, questions, session } = await createEventDataAndLogin({ diff --git a/@app/server/__tests__/mutations/updateRegistration.test.ts b/@app/server/__tests__/mutations/updateRegistration.test.ts index a9d1f8e0f..dff3a2aad 100644 --- a/@app/server/__tests__/mutations/updateRegistration.test.ts +++ b/@app/server/__tests__/mutations/updateRegistration.test.ts @@ -4,12 +4,27 @@ import { asRoot, createEventDataAndLogin, deleteTestData, + poolFromUrl, removePropFromObject, runGraphQLQuery, setup, teardown, + TEST_DATABASE_URL, } from "../helpers" +// Closes signup of an event created with open signup by moving its end into +// the past. The signup window is checked against NOW() in the database, so +// the end time is set there too. +async function closeSignup(eventId: string) { + const { rowCount } = await poolFromUrl(TEST_DATABASE_URL).query( + `update app_public.events + set registration_end_time = now() - interval '1 minute' + where id = $1 and registration_start_time < now() - interval '1 minute'`, + [eventId] + ) + expect(rowCount).toBe(1) +} + beforeEach(deleteTestData) beforeAll(setup) afterAll(teardown) @@ -133,4 +148,87 @@ describe("UpdateRegistration", () => { } ) }) + + it("can't update registration once event signup has closed", async () => { + const { events, registrations, registrationSecrets } = + await createEventDataAndLogin() + const { update_token: updateToken } = registrationSecrets[0] + const answers = registrations[0].answers + + await closeSignup(events[0].id) + + await runGraphQLQuery( + UpdateEventRegistrationDocument, + + // GraphQL variables: + { + input: { + updateToken, + firstName: "Päivi", + lastName: "Tetty", + answers, + }, + }, + + // Additional props to add to `req` (e.g. `user: {sessionId: '...'}`) + {}, + + // This function runs all your test assertions: + async (json) => { + expect(json.errors).toBeTruthy() + + const message = json.errors![0].message + const code = json.errors![0].extensions.exception.code + expect(message).toEqual( + "Updating a registration after event signup has closed is not allowed. Please contact the event organizers." + ) + expect(code).toEqual("DNIED") + } + ) + }) + + it("admin can update registration after event signup has closed", async () => { + const { events, registrations, registrationSecrets, session } = + await createEventDataAndLogin({ + userOptions: { + create: true, + amount: 1, + isVerified: true, + isAdmin: true, + }, + }) + const { update_token: updateToken } = registrationSecrets[0] + const answers = registrations[0].answers + + await closeSignup(events[0].id) + + await runGraphQLQuery( + UpdateEventRegistrationDocument, + + // GraphQL variables: + { + input: { + updateToken, + firstName: "Päivi", + lastName: "Tetty", + answers, + }, + }, + + // Additional props to add to `req` (e.g. `user: {sessionId: '...'}`) + { + user: { sessionId: session.uuid }, + }, + + // This function runs all your test assertions: + async (json) => { + expect(json.errors).toBeFalsy() + + const { firstName, lastName } = + json.data!.updateRegistration.registration + expect(firstName).toEqual("Päivi") + expect(lastName).toEqual("Tetty") + } + ) + }) }) diff --git a/@app/server/__tests__/payments.ts b/@app/server/__tests__/payments.ts new file mode 100644 index 000000000..72ab8a740 --- /dev/null +++ b/@app/server/__tests__/payments.ts @@ -0,0 +1,200 @@ +import { Pool } from "pg" + +import { getStripe, resetStripeClient } from "../src/utils/stripe" + +import { + createEventDataAndLogin, + poolFromUrl, + TEST_DATABASE_URL, +} from "./helpers" + +/* + * Shared setup for the payments tests. Test files mock the `stripe` package + * with `mockStripeModule` (see below), so nothing here talks to Stripe. + */ + +const STRIPE_ENV_KEYS = ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"] as const + +export const STRIPE_WEBHOOK_SECRET = "whsec_test_secret" + +/** + * Gives the test file a Stripe configuration (test keys; the `stripe` + * package is mocked) and restores the environment afterwards, since jest + * shares the process between test files. Whether payments are on is the + * `payments` feature flag: switch it with `setFeatureFlag` from ./helpers. + */ +export function configureStripeForEachTest() { + const saved: Record = {} + beforeEach(() => { + for (const key of STRIPE_ENV_KEYS) { + saved[key] = process.env[key] + } + process.env.STRIPE_SECRET_KEY = "sk_test_123" + process.env.STRIPE_WEBHOOK_SECRET = STRIPE_WEBHOOK_SECRET + resetStripeClient() + }) + afterEach(() => { + for (const key of STRIPE_ENV_KEYS) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + resetStripeClient() + }) +} + +/** Removes the Stripe configuration for the rest of the current test. */ +export function unconfigureStripe() { + for (const key of STRIPE_ENV_KEYS) { + delete process.env[key] + } + resetStripeClient() +} + +export interface StripeMock { + checkout: { + sessions: { + create: jest.Mock + expire: jest.Mock + retrieve: jest.Mock + } + } + webhooks: { + generateTestHeaderString(opts: { payload: string; secret: string }): string + } +} + +/** The fake client behind getStripe(); Stripe must be configured. */ +export function stripeMock(): StripeMock { + return getStripe() as unknown as StripeMock +} + +interface PaidEventOptions { + priceCents?: number + quotaSize?: number + registrationCount?: number + /** + * Move registration end into the past (default), so that the registrations + * can be paid. False leaves registration open. + */ + signupClosed?: boolean +} + +/** + * Commits an event with one quota and some registrations (with secrets), as + * createEventDataAndLogin does, then makes it paid by setting the quota + * price. Registrations are + * in creation order, so with `quotaSize` smaller than `registrationCount` + * the last ones are queued. + */ +export async function createPaidEvent({ + priceCents = 1800, + quotaSize = 10, + registrationCount = 1, + signupClosed = true, +}: PaidEventOptions = {}) { + const data = await createEventDataAndLogin({ + quotaOptions: { create: true, amount: 1, size: quotaSize }, + questionOptions: { create: false }, + registrationOptions: { create: true, amount: registrationCount }, + }) + const pool = poolFromUrl(TEST_DATABASE_URL) + let [event] = data.events + const [quota] = data.quotas + if (signupClosed) { + ;({ + rows: [event], + } = await pool.query( + `update app_public.events + set + registration_start_time = now() - interval '2 days', + registration_end_time = now() - interval '1 minute' + where id = $1 + returning *`, + [event.id] + )) + } + await pool.query( + "update app_public.quotas set price_cents = $2 where id = $1", + [quota.id, priceCents] + ) + + const registrations = data.registrations + const tokens = registrations.map( + (r) => + data.registrationSecrets.find((s) => s.registration_id === r.id)! + .update_token as string + ) + return { ...data, event, quota, registrations, tokens } +} + +interface PaymentOptions { + method?: "STRIPE" | "MANUAL" + status?: "PENDING" | "PAID" | "EXPIRED" + ticketAmountCents?: number + sessionId?: string | null + paymentIntentId?: string | null +} + +/** Inserts a payment row, as the server or worker would. */ +export async function insertPayment( + pool: Pool, + registration: { id: string; event_id: string; quota_id: string }, + { + method = "STRIPE", + status = "PAID", + ticketAmountCents = 1800, + sessionId = null, + paymentIntentId = null, + }: PaymentOptions = {} +) { + const { + rows: [payment], + } = await pool.query( + `insert into app_public.payments( + registration_id, event_id, quota_id, event_name, quota_title, + method, status, ticket_amount_cents, service_fee_cents, paid_at, + stripe_checkout_session_id, stripe_payment_intent_id + ) + values ($1, $2, $3, '{"fi": "Tapahtuma", "en": "Event"}', '{"fi": "Kiintiö", "en": "Quota"}', + $4::app_public.payment_method, $5::app_public.payment_status, $6, + case when $4::app_public.payment_method = 'STRIPE' then 25 else 0 end, + case when $5::app_public.payment_status = 'PAID' then now() end, + $7, $8) + returning *`, + [ + registration.id, + registration.event_id, + registration.quota_id, + method, + status, + ticketAmountCents, + sessionId, + paymentIntentId, + ] + ) + return payment +} + +export async function paymentsOfEvent(pool: Pool, eventId: string) { + const { rows } = await pool.query( + "select * from app_public.payments where event_id = $1 order by created_at, id", + [eventId] + ) + return rows +} + +/** + * Payloads of the queued jobs of a task, or of every payment task + * (`payment__*`) when omitted. + */ +export async function jobsOf(pool: Pool, taskIdentifier?: string) { + const { rows } = await pool.query( + `select jobs.payload + from graphile_worker._private_jobs as jobs + join graphile_worker._private_tasks as tasks on tasks.id = jobs.task_id + where coalesce(tasks.identifier = $1::text, tasks.identifier like 'payment\\_%') + order by jobs.id`, + [taskIdentifier ?? null] + ) + return rows.map((row) => row.payload) +} 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).
+ +
+ + + + + + + +
+ + Open event + +
+ +
+ +
You requested a reminder for this event. This reminder does not reserve a place.
+ +
+ +
+ + +
+ +
+ + + +
+ +
+ + + + + + + + + + + +
+ + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + +
+ + + + + + + + + +
+ +
© Tuotantotalouden Kilta Prodeko ry.
+ +
+ +
+ +
+ + +
+ +
+ + + +
+ +
+ + + + + +
+ +
+ + + + ", + "id": "[id-8]", + "name": "[random-8]", + "text": "Registration opens soon: Test event + +Registration opens 1 January 2021 at 12:00 (Finland time). + +Open event [http://localhost:5678/en/event/2021-01-01-testitapahtuma] + +You requested a reminder for this event. This reminder does not reserve a place. + +© Tuotantotalouden Kilta Prodeko ry. + +", + }, + { + "html": " + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2605,8 +2933,8 @@ This message is purely for your information. No action is required. ", - "id": "[id-8]", - "name": "[random-8]", + "id": "[id-9]", + "name": "[random-9]", "text": "Olet saanut paikan jonosta tapahtumaan Testitapahtuma - Nimi: Teppo Testinen @@ -2976,8 +3304,8 @@ You can update or delete your registration via this link: http://localhost:5678/ ", - "id": "[id-9]", - "name": "[random-9]", + "id": "[id-10]", + "name": "[random-10]", "text": "Please confirm your email by clicking the link below. Verification code: diff --git a/@app/server/__tests__/queries/paymentByUpdateToken.test.ts b/@app/server/__tests__/queries/paymentByUpdateToken.test.ts new file mode 100644 index 000000000..4df5fe3e2 --- /dev/null +++ b/@app/server/__tests__/queries/paymentByUpdateToken.test.ts @@ -0,0 +1,264 @@ +import * as registrationPayment from "../../src/payments/registrationPayment" +import { + deleteTestData, + poolFromUrl, + runGraphQLQuery, + setFeatureFlag, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" +import { + configureStripeForEachTest, + createPaidEvent, + insertPayment, + unconfigureStripe, +} from "../payments" + +jest.mock("stripe", () => require("../stripeMock").mockStripeModule()) + +beforeEach(deleteTestData) +beforeAll(setup) +afterAll(teardown) +configureStripeForEachTest() + +const pool = () => poolFromUrl(TEST_DATABASE_URL) + +beforeEach(() => setFeatureFlag(pool(), "payments", "on")) + +type PaidEventOptions = Parameters[0] +type PaidEvent = Awaited> + +const PaymentByUpdateTokenQuery = ` + query PaymentByUpdateToken($updateToken: String!) { + paymentByUpdateToken(updateToken: $updateToken) { + eventId + eventSlug + eventName + eventStartTime + eventEndTime + registrationEndTime + quotaTitle + firstName + lastName + queueStatus + queuePosition + status + priceCents + serviceFeeCents + totalCents + paidManually + paidTotalCents + paidAt + blockedReason + } + } +` + +async function paymentByUpdateToken(updateToken: string) { + const result = await runGraphQLQuery( + PaymentByUpdateTokenQuery, + { updateToken }, + {}, + () => {}, + true, + false + ) + expect(result.errors).toBeFalsy() + return result.data!.paymentByUpdateToken +} + +describe("paymentByUpdateToken", () => { + it("describes an unpaid registration", async () => { + const { event, registrations, tokens } = await createPaidEvent() + const [registration] = registrations + + expect(await paymentByUpdateToken(tokens[0])).toEqual({ + eventId: event.id, + eventSlug: event.slug, + eventName: event.name, + eventStartTime: new Date(event.event_start_time).toISOString(), + eventEndTime: new Date(event.event_end_time).toISOString(), + registrationEndTime: new Date(event.registration_end_time).toISOString(), + quotaTitle: { fi: "Kiintiö 0", en: "Quota 0" }, + firstName: registration.first_name, + lastName: registration.last_name, + queueStatus: "IN_QUOTA", + queuePosition: 1, + status: "UNPAID", + priceCents: 1800, + serviceFeeCents: 25, + totalCents: 1825, + paidManually: false, + paidTotalCents: null, + paidAt: null, + blockedReason: null, + }) + }) + + it("still shows the payment while the payments flag is off, with Pay blocked", async () => { + const { registrations, tokens } = await createPaidEvent() + await insertPayment(pool(), registrations[0]) + await setFeatureFlag(pool(), "payments", "off") + + expect(await paymentByUpdateToken(tokens[0])).toMatchObject({ + status: "PAID", + paidTotalCents: 1825, + blockedReason: "PAYMENTS_DISABLED", + }) + }) + + it.each< + [ + string, + PaidEventOptions, + ( + data: PaidEvent + ) => Promise<{ token: string; expected: Record }>, + ] + >([ + [ + "a card payment", + {}, + async ({ registrations, tokens }) => { + const payment = await insertPayment(pool(), registrations[0]) + return { + token: tokens[0], + expected: { + status: "PAID", + paidManually: false, + paidTotalCents: 1825, + paidAt: payment.paid_at.toISOString(), + blockedReason: "ALREADY_PAID", + }, + } + }, + ], + [ + "a manual payment", + {}, + async ({ registrations, tokens }) => { + await insertPayment(pool(), registrations[0], { method: "MANUAL" }) + return { + token: tokens[0], + expected: { + status: "PAID_MANUALLY", + paidManually: true, + paidTotalCents: 1800, + blockedReason: "ALREADY_PAID", + }, + } + }, + ], + [ + "a card payment as paid after the price has changed", + {}, + async ({ quota, registrations, tokens }) => { + await insertPayment(pool(), registrations[0]) + await pool().query( + "update app_public.quotas set price_cents = 2200 where id = $1", + [quota.id] + ) + return { + token: tokens[0], + expected: { + status: "PAID", + priceCents: 2200, + paidTotalCents: 1825, + blockedReason: "ALREADY_PAID", + }, + } + }, + ], + [ + "a free registration with zero amounts", + { priceCents: 0 }, + async ({ tokens }) => ({ + token: tokens[0], + expected: { + status: "NOT_REQUIRED", + priceCents: 0, + serviceFeeCents: 0, + totalCents: 0, + blockedReason: "PAYMENT_NOT_REQUIRED", + }, + }), + ], + [ + "that payment opens when registration closes", + { signupClosed: false }, + async ({ tokens }) => ({ + token: tokens[0], + expected: { + status: "UNPAID", + blockedReason: "PAYMENT_NOT_OPEN", + }, + }), + ], + [ + "the queue position", + { quotaSize: 1, registrationCount: 3 }, + async ({ registrations, tokens }) => { + const { rows } = await pool().query( + `select id, status, position from app_hidden.registrations_status_and_position + where id = any($1) and status = 'IN_QUEUE' order by position`, + [registrations.map((r) => r.id)] + ) + const last = rows[rows.length - 1] + return { + token: tokens[registrations.findIndex((r) => r.id === last.id)], + expected: { + queueStatus: "IN_QUEUE", + queuePosition: 2, + status: "UNPAID", + blockedReason: "IN_QUEUE", + }, + } + }, + ], + ])("shows %s", async (_name, options, arrange) => { + const { token, expected } = await arrange(await createPaidEvent(options)) + expect(await paymentByUpdateToken(token)).toMatchObject(expected) + }) + + it("hides database error text behind PAYMENT_LOOKUP_FAILED", async () => { + const { tokens } = await createPaidEvent() + const spy = jest + .spyOn(registrationPayment, "loadPaidPayment") + .mockRejectedValueOnce( + new Error('relation "app_private.secret_table" does not exist') + ) + try { + const result = await runGraphQLQuery( + PaymentByUpdateTokenQuery, + { updateToken: tokens[0] }, + {}, + () => {}, + true, + false + ) + expect(result.errors).toHaveLength(1) + const [error] = result.errors! + expect(error.extensions!.exception).toMatchObject({ + code: "PAYMENT_LOOKUP_FAILED", + }) + expect(JSON.stringify(error)).not.toMatch(/secret_table/) + } finally { + spy.mockRestore() + } + }) + + it.each<[string, (data: PaidEvent) => string]>([ + ["for an unknown token", () => "not-a-token"], + [ + "while Stripe is not configured", + ({ tokens }) => { + unconfigureStripe() + return tokens[0] + }, + ], + ])("is null %s", async (_name, tokenOf) => { + const token = tokenOf(await createPaidEvent()) + expect(await paymentByUpdateToken(token)).toBeNull() + }) +}) diff --git a/@app/server/__tests__/queries/renderEmailTemplates.test.ts b/@app/server/__tests__/queries/renderEmailTemplates.test.ts index 2fd83e934..0d4d6194b 100644 --- a/@app/server/__tests__/queries/renderEmailTemplates.test.ts +++ b/@app/server/__tests__/queries/renderEmailTemplates.test.ts @@ -1,6 +1,14 @@ import { RenderEmailTemplatesDocument } from "@app/graphql" -import { deleteTestData, runGraphQLQuery, setup, teardown } from "../helpers" +import { + deleteTestData, + poolFromUrl, + runGraphQLQuery, + setFeatureFlag, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" beforeEach(deleteTestData) beforeAll(setup) @@ -22,10 +30,63 @@ test("render email templates query", async () => { expect(json.errors).toBeFalsy() expect(json.data).toBeTruthy() const templates = json.data!.renderEmailTemplates.templates + const reminder = templates.find((t) => t.name === "registration reminder") + expect(reminder?.text).toContain("Registration opens soon: Test event") + expect(reminder?.text).toContain("1 January 2021 at 12:00") + expect(reminder?.text).not.toContain("[object Object]") templates.forEach((t) => { expect(t.html).toBeTruthy() expect(t.text).toBeTruthy() }) + // The payments flag is off: no payment emails, no payment blocks + const names = templates.map((t) => t.name) + expect(names.some((name) => name.startsWith("payment"))).toBe(false) + templates.forEach((t) => { + expect(t.text).not.toContain("palvelumaksu") + }) } ) }) + +describe("with the payments flag on", () => { + beforeEach(() => + setFeatureFlag(poolFromUrl(TEST_DATABASE_URL), "payments", "on") + ) + + test("lists the payment emails, rendered with example payments", async () => { + await runGraphQLQuery( + RenderEmailTemplatesDocument, + {}, + {}, + async (json) => { + expect(json.errors).toBeFalsy() + const templates = json.data!.renderEmailTemplates.templates + const names = templates.map((t) => t.name) + // Partials such as payment_macros.njk are not emails + expect(names).toEqual( + expect.arrayContaining([ + "event registration", + "spot from queue", + "payment received", + "payment reminder", + ]) + ) + expect(names.some((name) => name.includes("macros"))).toBe(false) + + const textOf = (name: string) => + templates.find((t) => t.name === name)!.text + expect(textOf("event registration")).toContain( + "Lippu 18,00 € + palvelumaksu 0,25 € = 18,25 €" + ) + expect(textOf("spot from queue")).toContain("Maksa 18,25 €") + expect(textOf("payment reminder")).toContain( + "Lippu 18,00 € + palvelumaksu 0,25 € = 18,25 €" + ) + expect(textOf("payment received")).toContain("18,25 €") + expect(names).not.toContain("payment refund") + }, + true, + false + ) + }) +}) diff --git a/@app/server/__tests__/stripeMock.ts b/@app/server/__tests__/stripeMock.ts new file mode 100644 index 000000000..f3b09bd20 --- /dev/null +++ b/@app/server/__tests__/stripeMock.ts @@ -0,0 +1,29 @@ +/* + * Kept free of imports: it runs inside jest.mock("stripe", ...) factories, + * before the modules that use the Stripe client are loaded. + */ + +/** + * Factory for `jest.mock("stripe", ...)`: the Stripe constructor returns one + * shared fake client whose Checkout methods are jest mocks, while + * `webhooks` is the real implementation, so signatures are really checked + * (it needs no network). + */ +export function mockStripeModule() { + const ActualStripe = jest.requireActual("stripe") + const real = new ActualStripe("sk_test_123") + const client = { + checkout: { + sessions: { + create: jest.fn(), + expire: jest.fn(), + retrieve: jest.fn(), + }, + }, + webhooks: real.webhooks, + } + return { + __esModule: true, + default: jest.fn(() => client), + } +} diff --git a/@app/server/__tests__/stripeWebhook.test.ts b/@app/server/__tests__/stripeWebhook.test.ts new file mode 100644 index 000000000..cb0ee6951 --- /dev/null +++ b/@app/server/__tests__/stripeWebhook.test.ts @@ -0,0 +1,457 @@ +import { fastify, FastifyInstance } from "fastify" +import { Pool } from "pg" + +import installCSRFProtection from "../src/middleware/installCSRFProtection" +import installExternalRoutes from "../src/middleware/installExternalRoutes" +import installSession from "../src/middleware/installSession" +import { STRIPE_WEBHOOK_PATH, stripeWebhook } from "../src/stripeWebhook" + +import { deleteTestData } from "./helpers" +import { + configureStripeForEachTest, + createPaidEvent, + insertPayment, + jobsOf, + paymentsOfEvent, + STRIPE_WEBHOOK_SECRET, +} from "./payments" + +jest.mock("stripe", () => require("./stripeMock").mockStripeModule()) + +// The `payments` flag stays off in this file: the webhook is never gated, +// so payments started before the switch still settle. +configureStripeForEachTest() + +/** The webhook as the external route installer registers it. */ +const installStripeWebhook = (instance: FastifyInstance) => + instance.register(installExternalRoutes, { + externalRoutes: [stripeWebhook], + }) + +let pool: Pool +let app: FastifyInstance + +beforeAll(() => { + pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }) +}) + +afterAll(async () => { + await pool.end() +}) + +beforeEach(async () => { + await deleteTestData() + app = fastify() + app.decorate("rootPgPool", pool) + installStripeWebhook(app) + // An ordinary JSON route next to the webhook: the raw-body parser must not + // leak out of the webhook plugin. + app.post("/json", async (request) => ({ body: request.body })) + await app.ready() +}) + +afterEach(async () => { + await app.close() +}) + +let eventCounter = 0 + +function stripeEvent(type: string, object: Record) { + eventCounter++ + return { + id: `evt_test_${eventCounter}_${Date.now()}`, + object: "event", + type, + data: { object }, + } +} + +// The real webhooks helper, usable whatever the environment +const ActualStripe = jest.requireActual("stripe") +const { webhooks } = new ActualStripe("sk_test_123") + +function sign(payload: string, secret = STRIPE_WEBHOOK_SECRET): string { + return webhooks.generateTestHeaderString({ payload, secret }) +} + +async function post( + event: object, + { signature }: { signature?: string | null } = {} +) { + const payload = JSON.stringify(event) + const headers: Record = { + "content-type": "application/json; charset=utf-8", + } + if (signature !== null) { + headers["stripe-signature"] = signature ?? sign(payload) + } + return app.inject({ + method: "POST", + url: STRIPE_WEBHOOK_PATH, + headers, + payload, + }) +} + +async function processedEvents() { + const { rows } = await pool.query( + "select id, type from app_private.stripe_events order by processed_at" + ) + return rows +} + +function completedSession( + sessionId: string, + extra: Record = {} +) { + return stripeEvent("checkout.session.completed", { + id: sessionId, + object: "checkout.session", + payment_status: "paid", + status: "complete", + payment_intent: `pi_for_${sessionId}`, + // What insertPayment's defaults charge: 1800 ticket + 25 service fee + amount_total: 1825, + currency: "eur", + metadata: {}, + ...extra, + }) +} + +async function paymentById(id: string) { + const { + rows: [payment], + } = await pool.query("select * from app_public.payments where id = $1", [id]) + return payment +} + +describe("signature", () => { + it.each<[string, (payload: string) => string | null]>([ + ["without a signature", () => null], + ["with a bad signature", (payload) => sign(payload, "whsec_wrong")], + ])("rejects a request %s", async (_name, signatureOf) => { + const event = completedSession("cs_test_badsig") + const res = await post(event, { + signature: signatureOf(JSON.stringify(event)), + }) + expect(res.statusCode).toBe(400) + expect(await processedEvents()).toEqual([]) + }) + + it("keeps JSON parsing for other routes", async () => { + const res = await app.inject({ + method: "POST", + url: "/json", + payload: { hello: "world" }, + }) + expect(res.json()).toEqual({ body: { hello: "world" } }) + }) +}) + +describe("checkout.session.completed", () => { + it("marks the payment paid and queues the payment received email", async () => { + const { event, registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_paid", + }) + + const stripeEventPayload = completedSession("cs_test_paid") + const res = await post(stripeEventPayload) + expect(res.statusCode).toBe(200) + + expect(await paymentById(payment.id)).toMatchObject({ + status: "PAID", + registration_id: registrations[0].id, + stripe_payment_intent_id: "pi_for_cs_test_paid", + paid_at: expect.any(Date), + }) + expect(await jobsOf(pool)).toEqual([{ paymentId: payment.id }]) + expect(await jobsOf(pool, "payment__send_received_email")).toEqual([ + { paymentId: payment.id }, + ]) + expect(await processedEvents()).toEqual([ + { id: stripeEventPayload.id, type: "checkout.session.completed" }, + ]) + expect((await paymentsOfEvent(pool, event.id)).length).toBe(1) + }) + + it("ignores a redelivered event", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_twice", + }) + const stripeEventPayload = completedSession("cs_test_twice") + + expect((await post(stripeEventPayload)).statusCode).toBe(200) + // Undo the effect: a reprocessed event would mark it paid again + await pool.query( + "update app_public.payments set status = 'PENDING' where id = $1", + [payment.id] + ) + expect((await post(stripeEventPayload)).statusCode).toBe(200) + + expect((await paymentById(payment.id)).status).toBe("PENDING") + expect(await jobsOf(pool, "payment__send_received_email")).toHaveLength(1) + }) + + it("ignores a second, different event for an already paid session", async () => { + const { registrations } = await createPaidEvent() + await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_again", + }) + await post(completedSession("cs_test_again")) + expect((await post(completedSession("cs_test_again"))).statusCode).toBe(200) + expect(await jobsOf(pool, "payment__send_received_email")).toHaveLength(1) + }) + + it("keeps the payment, detached and unrefunded, when the registration was deleted meanwhile", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_deleted", + }) + await pool.query("delete from app_public.registrations where id = $1", [ + registrations[0].id, + ]) + + expect((await post(completedSession("cs_test_deleted"))).statusCode).toBe( + 200 + ) + expect(await paymentById(payment.id)).toMatchObject({ + status: "PAID", + registration_id: null, + stripe_payment_intent_id: "pi_for_cs_test_deleted", + }) + expect(await jobsOf(pool)).toEqual([]) + }) + + it("keeps a second payment for an already paid registration, detached and unrefunded", async () => { + const { registrations } = await createPaidEvent() + const manual = await insertPayment(pool, registrations[0], { + method: "MANUAL", + }) + const second = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_second", + }) + + expect((await post(completedSession("cs_test_second"))).statusCode).toBe( + 200 + ) + expect(await paymentById(second.id)).toMatchObject({ + status: "PAID", + // Detached: a registration can have only one PAID payment + registration_id: null, + stripe_payment_intent_id: "pi_for_cs_test_second", + }) + expect(await paymentById(manual.id)).toMatchObject({ + status: "PAID", + registration_id: registrations[0].id, + }) + expect(await jobsOf(pool)).toEqual([]) + }) + + it("finds the payment by its metadata when the session id was not stored", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + }) + + const res = await post( + completedSession("cs_test_metadata", { + metadata: { payment_id: payment.id }, + }) + ) + expect(res.statusCode).toBe(200) + expect(await paymentById(payment.id)).toMatchObject({ + status: "PAID", + stripe_checkout_session_id: "cs_test_metadata", + }) + }) + + it.each([ + ["amount", { amount_total: 1700 }], + ["currency", { currency: "usd" }], + ])( + "keeps a session whose %s differs from the payment row, detached and unrefunded", + async (_name, extra) => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_mismatch", + }) + + expect( + (await post(completedSession("cs_test_mismatch", extra))).statusCode + ).toBe(200) + expect(await paymentById(payment.id)).toMatchObject({ + status: "PAID", + registration_id: null, + stripe_payment_intent_id: "pi_for_cs_test_mismatch", + }) + expect(await jobsOf(pool)).toEqual([]) + } + ) + + it("records and refunds nothing for a paid session without a payment row", async () => { + const res = await post( + completedSession("cs_test_orphan", { + metadata: { payment_id: "00000000-0000-4000-8000-000000000000" }, + }) + ) + expect(res.statusCode).toBe(200) + const { rows } = await pool.query( + "select count(*)::int as count from app_public.payments" + ) + expect(rows).toEqual([{ count: 0 }]) + expect(await jobsOf(pool)).toEqual([]) + }) + + it("does nothing for an unpaid session", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_unpaid", + }) + + expect( + ( + await post( + completedSession("cs_test_unpaid", { payment_status: "unpaid" }) + ) + ).statusCode + ).toBe(200) + expect((await paymentById(payment.id)).status).toBe("PENDING") + }) + + it("answers 500 and records nothing when the database fails, so Stripe retries", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_dberror", + }) + // A pool whose clients fail on the payment update + const failingPool = new Pool({ + connectionString: process.env.TEST_DATABASE_URL, + }) + const failingApp = fastify() + failingApp.decorate("rootPgPool", { + connect: async () => { + const client = await failingPool.connect() + const query = client.query.bind(client) + return Object.assign(Object.create(client), { + query: (text: unknown, ...rest: unknown[]) => + typeof text === "string" && text.includes("status = 'PAID'") + ? Promise.reject(new Error("database is down")) + : (query as any)(text, ...rest), + release: () => client.release(true), + }) + }, + } as unknown as Pool) + installStripeWebhook(failingApp) + try { + const event = completedSession("cs_test_dberror") + const payload = JSON.stringify(event) + const res = await failingApp.inject({ + method: "POST", + url: STRIPE_WEBHOOK_PATH, + headers: { + "content-type": "application/json", + "stripe-signature": sign(payload), + }, + payload, + }) + expect(res.statusCode).toBe(500) + expect(await processedEvents()).toEqual([]) + expect((await paymentById(payment.id)).status).toBe("PENDING") + + // Stripe's retry goes through once the database is back + expect((await post(event)).statusCode).toBe(200) + expect((await paymentById(payment.id)).status).toBe("PAID") + } finally { + await failingApp.close() + await failingPool.end() + } + }) +}) + +describe("checkout.session.expired", () => { + it("expires the pending payment, never a paid one", async () => { + const { registrations } = await createPaidEvent() + const pending = await insertPayment(pool, registrations[0], { + status: "PENDING", + sessionId: "cs_test_expired", + }) + const paid = await insertPayment(pool, registrations[0], { + sessionId: "cs_test_paid_then_expired", + }) + + const res = await post( + stripeEvent("checkout.session.expired", { + id: "cs_test_expired", + object: "checkout.session", + status: "expired", + payment_status: "unpaid", + }) + ) + expect(res.statusCode).toBe(200) + expect((await paymentById(pending.id)).status).toBe("EXPIRED") + + await post( + stripeEvent("checkout.session.expired", { + id: "cs_test_paid_then_expired", + object: "checkout.session", + }) + ) + expect((await paymentById(paid.id)).status).toBe("PAID") + }) +}) + +describe("CSRF", () => { + let csrfApp: FastifyInstance + + beforeEach(async () => { + csrfApp = fastify() + csrfApp.decorate("rootPgPool", pool) + await csrfApp.register(installSession) + await csrfApp.register(installCSRFProtection) + await installStripeWebhook(csrfApp) + csrfApp.post(`${STRIPE_WEBHOOK_PATH}/other`, async () => ({ ok: true })) + await csrfApp.ready() + }) + + afterEach(async () => { + await csrfApp.close() + }) + + async function postWithoutCsrfToken(url: string) { + const payload = JSON.stringify(stripeEvent("customer.created", {})) + return csrfApp.inject({ + method: "POST", + url, + headers: { + "content-type": "application/json", + "stripe-signature": sign(payload), + }, + payload, + }) + } + + it("exempts the webhook, ignoring a query string as routing does", async () => { + expect((await postWithoutCsrfToken(STRIPE_WEBHOOK_PATH)).statusCode).toBe( + 200 + ) + expect( + (await postWithoutCsrfToken(`${STRIPE_WEBHOOK_PATH}?x=1`)).statusCode + ).toBe(200) + }) + + it("still protects a sub-path", async () => { + expect( + (await postWithoutCsrfToken(`${STRIPE_WEBHOOK_PATH}/other`)).statusCode + ).toBe(403) + }) +}) diff --git a/@app/server/__tests__/telegramPolling.test.ts b/@app/server/__tests__/telegramPolling.test.ts new file mode 100644 index 000000000..64f08c08b --- /dev/null +++ b/@app/server/__tests__/telegramPolling.test.ts @@ -0,0 +1,111 @@ +import { telegramRequest } from "@app/lib/dist/cjs/telegram" + +import { startTelegramPolling } from "../src/telegram" + +jest.mock("@app/lib/dist/cjs/telegram", () => ({ + ...jest.requireActual("@app/lib/dist/cjs/telegram"), + telegramRequest: jest.fn(), +})) + +const on = async () => true +const flush = () => new Promise((resolve) => setImmediate(resolve)) +function database() { + const client = { + query: jest.fn(async (sql: string) => ({ + rows: sql.includes("pg_try_advisory_lock") + ? [{ acquired: true }] + : [{ next_offset: 0 }], + })), + release: jest.fn(), + } + return { client, pool: { connect: jest.fn(async () => client) } } +} +beforeEach(() => { + jest.useFakeTimers({ doNotFake: ["setImmediate", "nextTick"] }) + jest.clearAllMocks() + jest.spyOn(console, "error").mockImplementation(() => {}) + jest.spyOn(console, "log").mockImplementation(() => {}) +}) +afterEach(() => { + jest.useRealTimers() + jest.restoreAllMocks() +}) +it("retries a failed initial connection and starts polling after network recovery", async () => { + const db = database() + let finishPoll!: (value: unknown) => void + jest + .mocked(telegramRequest) + .mockImplementation(async (method) => { + if (method === "getUpdates") + return new Promise((resolve) => { + finishPoll = resolve + }) as any + return { url: "" } as any + }) + .mockRejectedValueOnce(new Error("Telegram connection failed")) + const stop = startTelegramPolling(db.pool as any, { isEnabled: on }) + await flush() + expect(telegramRequest).toHaveBeenCalledTimes(1) + await jest.advanceTimersByTimeAsync(5000) + await flush() + expect(telegramRequest).toHaveBeenCalledWith( + "getUpdates", + expect.objectContaining({ offset: 0 }) + ) + const stopping = stop() + finishPoll([]) + await stopping + expect(db.client.release).toHaveBeenCalledTimes(1) + expect(db.client.query).toHaveBeenCalledWith( + "select pg_advisory_unlock(478433, 1)" + ) +}) +it("stops promptly while waiting to retry a failed startup", async () => { + const db = database() + jest + .mocked(telegramRequest) + .mockRejectedValue(new Error("Telegram connection failed")) + const stop = startTelegramPolling(db.pool as any, { isEnabled: on }) + await flush() + await stop() + expect(telegramRequest).toHaveBeenCalledTimes(1) + expect(db.client.release).toHaveBeenCalledTimes(1) +}) +it("does not poll when a webhook is active", async () => { + const db = database() + jest + .mocked(telegramRequest) + .mockResolvedValue({ url: "https://example.com/telegram/webhook" }) + const stop = startTelegramPolling(db.pool as any, { isEnabled: on }) + await flush() + await stop() + expect(telegramRequest).toHaveBeenCalledTimes(1) + expect(db.client.release).toHaveBeenCalledTimes(1) +}) + +it("leaves updates with Telegram while telegram_reminders is off", async () => { + const db = database() + let enabled = false + const isEnabled = jest.fn(async () => enabled) + jest.mocked(telegramRequest).mockImplementation(async (method) => { + if (method === "getUpdates") return new Promise(() => {}) as any + return { url: "" } as any + }) + const stop = startTelegramPolling(db.pool as any, { isEnabled }) + await flush() + expect(isEnabled).toHaveBeenCalledTimes(1) + expect(telegramRequest).not.toHaveBeenCalled() + await jest.advanceTimersByTimeAsync(30000) + await flush() + expect(isEnabled).toHaveBeenCalledTimes(2) + expect(telegramRequest).not.toHaveBeenCalled() + enabled = true + await jest.advanceTimersByTimeAsync(30000) + await flush() + expect(telegramRequest).toHaveBeenCalledWith( + "getUpdates", + expect.objectContaining({ offset: 0 }) + ) + // getUpdates never settles here; stop without waiting for it. + void stop() +}) diff --git a/@app/server/__tests__/telegramWebhook.test.ts b/@app/server/__tests__/telegramWebhook.test.ts new file mode 100644 index 000000000..25c295caf --- /dev/null +++ b/@app/server/__tests__/telegramWebhook.test.ts @@ -0,0 +1,175 @@ +import Fastify from "fastify" + +import { csrfExemptions } from "../src/externalRoutes" +import installExternalRoutes from "../src/middleware/installExternalRoutes" +import installTelegramPolling from "../src/middleware/installTelegramPolling" +import { handleTelegramUpdate } from "../src/telegram" +import { telegramWebhook } from "../src/telegramWebhook" + +jest.mock("../src/telegram", () => ({ + handleTelegramUpdate: jest.fn(), + startTelegramPolling: jest.fn(() => async () => {}), +})) + +const original = { + NODE_ENV: process.env.NODE_ENV, + TELEGRAM_BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN, + TELEGRAM_UPDATE_MODE: process.env.TELEGRAM_UPDATE_MODE, + TELEGRAM_WEBHOOK_SECRET: process.env.TELEGRAM_WEBHOOK_SECRET, +} +beforeEach(() => { + jest.clearAllMocks() + Object.assign(process.env, { NODE_ENV: "production" }) + process.env.TELEGRAM_BOT_TOKEN = "test-token" + process.env.TELEGRAM_UPDATE_MODE = "webhook" + process.env.TELEGRAM_WEBHOOK_SECRET = "test-webhook-secret" +}) +afterEach(() => { + for (const [key, value] of Object.entries(original)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } +}) + +async function makeApp(isFeatureEnabled = async () => true) { + const app = Fastify() + app.decorate("rootPgPool", {} as any) + await app.register(installExternalRoutes, { + externalRoutes: [telegramWebhook], + isFeatureEnabled, + }) + return app +} + +const post = ( + app: Awaited>, + payload: object, + secret?: string +) => + app.inject({ + method: "POST", + url: "/telegram/webhook", + payload, + headers: secret ? { "x-telegram-bot-api-secret-token": secret } : {}, + }) + +it.each([undefined, "wrong-secret"])( + "rejects unauthenticated webhook requests", + async (secret) => { + const app = await makeApp() + try { + const response = await post(app, { update_id: 123 }, secret) + expect(response.statusCode).toBe(403) + expect(handleTelegramUpdate).not.toHaveBeenCalled() + } finally { + await app.close() + } + } +) + +it("passes authenticated valid updates even when the local app uses NODE_ENV=test", async () => { + Object.assign(process.env, { NODE_ENV: "test" }) + const app = await makeApp() + try { + const response = await post(app, { update_id: 123 }, "test-webhook-secret") + expect(response.statusCode).toBe(200) + expect(handleTelegramUpdate).toHaveBeenCalledWith(app.rootPgPool, { + update_id: 123, + }) + } finally { + await app.close() + } +}) + +it("rejects malformed authenticated updates", async () => { + const app = await makeApp() + try { + const response = await post(app, {}, "test-webhook-secret") + expect(response.statusCode).toBe(400) + expect(handleTelegramUpdate).not.toHaveBeenCalled() + } finally { + await app.close() + } +}) + +describe("configuration", () => { + it("is configured only in webhook mode with the token and the secret", () => { + expect(telegramWebhook.configured()).toBe(true) + expect(csrfExemptions([telegramWebhook])).toEqual([ + { method: "POST", path: "/telegram/webhook" }, + ]) + + delete process.env.TELEGRAM_WEBHOOK_SECRET + expect(telegramWebhook.configured()).toBe(false) + process.env.TELEGRAM_WEBHOOK_SECRET = "test-webhook-secret" + + delete process.env.TELEGRAM_BOT_TOKEN + expect(telegramWebhook.configured()).toBe(false) + process.env.TELEGRAM_BOT_TOKEN = "test-token" + + process.env.TELEGRAM_UPDATE_MODE = "polling" + expect(telegramWebhook.configured()).toBe(false) + expect(csrfExemptions([telegramWebhook])).toEqual([]) + + delete process.env.TELEGRAM_UPDATE_MODE + Object.assign(process.env, { NODE_ENV: "development" }) + expect(telegramWebhook.configured()).toBe(false) + Object.assign(process.env, { NODE_ENV: "production" }) + expect(telegramWebhook.configured()).toBe(true) + }) + + it("does not register the webhook without its secret", async () => { + delete process.env.TELEGRAM_WEBHOOK_SECRET + const app = await makeApp() + try { + const response = await post( + app, + { update_id: 123 }, + "test-webhook-secret" + ) + expect(response.statusCode).toBe(404) + expect(handleTelegramUpdate).not.toHaveBeenCalled() + } finally { + await app.close() + } + }) +}) + +describe("polling", () => { + const { startTelegramPolling } = jest.requireMock("../src/telegram") + const env = { + IN_TESTS: process.env.IN_TESTS, + JEST_WORKER_ID: process.env.JEST_WORKER_ID, + } + afterEach(() => { + for (const [key, value] of Object.entries(env)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + }) + + async function register() { + const app = Fastify() + app.decorate("rootPgPool", {} as any) + app.decorate("shutdownActions", []) + await app.register(installTelegramPolling) + await app.ready() + await app.close() + } + + it("never polls inside an automated test run", async () => { + process.env.TELEGRAM_UPDATE_MODE = "polling" + await register() + expect(startTelegramPolling).not.toHaveBeenCalled() + }) + + it("polls in polling mode and not in webhook mode", async () => { + delete process.env.IN_TESTS + delete process.env.JEST_WORKER_ID + await register() + expect(startTelegramPolling).not.toHaveBeenCalled() + process.env.TELEGRAM_UPDATE_MODE = "polling" + await register() + expect(startTelegramPolling).toHaveBeenCalledTimes(1) + }) +}) diff --git a/@app/server/__tests__/utils/calendar.test.ts b/@app/server/__tests__/utils/calendar.test.ts new file mode 100644 index 000000000..7d4964c41 --- /dev/null +++ b/@app/server/__tests__/utils/calendar.test.ts @@ -0,0 +1,98 @@ +import { + calendarDescription, + createCalendarLinks, + createEventCalendar, +} from "../../../lib/src/calendar" + +const event = { + id: "event-123", + name: "Sitsit, syksy; 🎉", + description: "Line one\nLine two\\three", + location: "Otaniemi", + start: "2026-10-24T18:00:00+03:00", + end: "2026-10-24T22:00:00+03:00", + url: "http://192.168.1.42:5678/event/test", +} + +it("prefills Google Calendar with encoded text and UTC event times", () => { + const url = new URL(createCalendarLinks(event).google) + expect(url.origin).toBe("https://www.google.com") + expect(url.pathname).toBe("/calendar/render") + expect(url.searchParams.get("action")).toBe("TEMPLATE") + expect(url.searchParams.get("text")).toBe(event.name) + expect(url.searchParams.get("dates")).toBe( + "20261024T150000Z/20261024T190000Z" + ) + expect(url.searchParams.get("details")).toBe( + `${event.description}\n\n${event.url}` + ) + expect(url.searchParams.get("location")).toBe(event.location) +}) + +it("prefills both Outlook account types without letting text add URL parameters", () => { + const name = "Dinner & location=wrong # åäö 🎉" + const links = createCalendarLinks({ ...event, name }) + for (const [key, origin] of [ + ["outlook", "https://outlook.live.com"], + ["microsoft365", "https://outlook.office.com"], + ] as const) { + const url = new URL(links[key]) + expect(url.origin).toBe(origin) + expect(url.searchParams.get("subject")).toBe(name) + expect(url.searchParams.getAll("location")).toEqual([event.location]) + expect(url.searchParams.get("startdt")).toBe("2026-10-24T15:00:00.000Z") + expect(url.searchParams.get("enddt")).toBe("2026-10-24T19:00:00.000Z") + expect(url.searchParams.get("body")).toBe( + `${event.description}\n\n${event.url}` + ) + } +}) + +it("exports the actual event times in UTC and a stable UID", () => { + const calendar = createEventCalendar(event, new Date("2026-10-17T10:00:00Z")) + expect(calendar).toContain("DTSTART:20261024T150000Z\r\n") + expect(calendar).toContain("DTEND:20261024T190000Z\r\n") + expect(calendar).toContain("DTSTAMP:20261017T100000Z\r\n") + expect(calendar).toContain("UID:event-123@ilmo\r\n") + expect(calendar).toContain("URL:http://192.168.1.42:5678/event/test\r\n") + expect(calendar).toMatch(/END:VEVENT\r\nEND:VCALENDAR\r\n$/) +}) + +it("escapes text and prevents injected calendar properties", () => { + const calendar = createEventCalendar({ + ...event, + location: "Hall\r\nEND:VEVENT", + }) + expect(calendar).toContain("SUMMARY:Sitsit\\, syksy\\; 🎉\r\n") + expect(calendar).toContain("LOCATION:Hall\\nEND:VEVENT\r\n") + expect(calendar).toContain("Line one\\nLine two\\\\three") + expect(calendar.match(/^END:VEVENT$/gm)).toHaveLength(1) +}) + +it("folds long UTF-8 lines without splitting characters", () => { + const name = "🎉ä".repeat(100) + const calendar = createEventCalendar({ ...event, name }) + for (const line of calendar.split("\r\n")) { + expect(Buffer.byteLength(line, "utf8")).toBeLessThanOrEqual(75) + } + expect(calendar.replace(/\r\n /g, "")).toContain(`SUMMARY:${name}\r\n`) +}) + +it("converts Slate paragraphs, inline formatting and lists to plain text", () => { + expect( + calendarDescription([ + { + type: "paragraph", + children: [{ text: "Hello " }, { text: "world", bold: true }], + }, + { + type: "bulleted-list", + children: [ + { type: "list-item", children: [{ text: "One" }] }, + { type: "list-item", children: [{ text: "Two" }] }, + ], + }, + ]) + ).toBe("Hello world\nOne\nTwo") + expect(calendarDescription(null)).toBe("") +}) diff --git a/@app/server/__tests__/utils/featureFlags.test.ts b/@app/server/__tests__/utils/featureFlags.test.ts new file mode 100644 index 000000000..d6e3bf4fe --- /dev/null +++ b/@app/server/__tests__/utils/featureFlags.test.ts @@ -0,0 +1,243 @@ +import { FeatureKey } from "@app/lib" +import { Pool } from "pg" + +import { + createFeatureFlagReader, + FEATURE_FLAG_CACHE_TTL_MS, + syncFeatureAvailability, +} from "../../src/utils/featureFlags" + +// The registry has no keys yet; these tests use their own rows. +const key = (name: string) => name as FeatureKey + +type Row = { key: string; enabled: boolean; admins_only: boolean } + +function fakePool(rows: Row[]) { + const pool = { + rows, + query: jest.fn(async () => ({ rows: pool.rows })), + } + return pool +} + +describe("createFeatureFlagReader", () => { + it("reads enabled flags and treats unknown keys as off", async () => { + const pool = fakePool([ + { key: "a", enabled: true, admins_only: false }, + { key: "b", enabled: false, admins_only: false }, + ]) + const reader = createFeatureFlagReader(pool as any) + expect(await reader.isFeatureEnabled(key("a"))).toBe(true) + expect(await reader.isFeatureEnabled(key("b"))).toBe(false) + expect(await reader.isFeatureEnabled(key("missing"))).toBe(false) + }) + + it("counts admins_only as on only for callers that pass asAdmin", async () => { + const pool = fakePool([{ key: "a", enabled: false, admins_only: true }]) + const reader = createFeatureFlagReader(pool as any) + expect(await reader.isFeatureEnabled(key("a"))).toBe(false) + expect(await reader.isFeatureEnabled(key("a"), { asAdmin: false })).toBe( + false + ) + expect(await reader.isFeatureEnabled(key("a"), { asAdmin: true })).toBe( + true + ) + }) + + it("serves reads from the cache until the TTL has passed", async () => { + let time = 1000 + const pool = fakePool([{ key: "a", enabled: false, admins_only: false }]) + const reader = createFeatureFlagReader(pool as any, { now: () => time }) + + expect(await reader.isFeatureEnabled(key("a"))).toBe(false) + pool.rows = [{ key: "a", enabled: true, admins_only: false }] + + time += FEATURE_FLAG_CACHE_TTL_MS - 1 + expect(await reader.isFeatureEnabled(key("a"))).toBe(false) + expect(pool.query).toHaveBeenCalledTimes(1) + + time += 1 + expect(await reader.isFeatureEnabled(key("a"))).toBe(true) + expect(pool.query).toHaveBeenCalledTimes(2) + }) + + it("reads the database again after invalidate()", async () => { + const pool = fakePool([{ key: "a", enabled: false, admins_only: false }]) + const reader = createFeatureFlagReader(pool as any) + expect(await reader.isFeatureEnabled(key("a"))).toBe(false) + pool.rows = [{ key: "a", enabled: true, admins_only: false }] + reader.invalidate() + expect(await reader.isFeatureEnabled(key("a"))).toBe(true) + expect(pool.query).toHaveBeenCalledTimes(2) + }) + + it("shares one query between concurrent reads", async () => { + const pool = fakePool([{ key: "a", enabled: true, admins_only: false }]) + const reader = createFeatureFlagReader(pool as any) + const results = await Promise.all([ + reader.isFeatureEnabled(key("a")), + reader.isFeatureEnabled(key("a")), + reader.isFeatureEnabled(key("b")), + ]) + expect(results).toEqual([true, true, false]) + expect(pool.query).toHaveBeenCalledTimes(1) + }) + + it("does not cache a load that started before invalidate()", async () => { + let release: (value: { rows: Row[] }) => void = () => {} + const pool = { + query: jest + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + .mockResolvedValue({ + rows: [{ key: "a", enabled: true, admins_only: false }], + }), + } + const reader = createFeatureFlagReader(pool as any) + const stale = reader.isFeatureEnabled(key("a")) + reader.invalidate() + release({ rows: [{ key: "a", enabled: false, admins_only: false }] }) + expect(await stale).toBe(false) + expect(await reader.isFeatureEnabled(key("a"))).toBe(true) + expect(pool.query).toHaveBeenCalledTimes(2) + }) + + it("lets a failed read fail the caller and retries on the next read", async () => { + const pool = { + query: jest + .fn() + .mockRejectedValueOnce(new Error("connection refused")) + .mockResolvedValue({ + rows: [{ key: "a", enabled: true, admins_only: false }], + }), + } + const reader = createFeatureFlagReader(pool as any) + await expect(reader.isFeatureEnabled(key("a"))).rejects.toThrow( + "connection refused" + ) + expect(await reader.isFeatureEnabled(key("a"))).toBe(true) + }) +}) + +describe("against the database", () => { + let pool: Pool + const KEYS = ["server_test_on", "server_test_preview", "server_test_off"] + + beforeAll(() => { + pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }) + }) + + afterEach(async () => { + await pool.query( + "delete from app_public.feature_flags where key like 'server_test_%'" + ) + }) + + afterAll(() => pool.end()) + + const insertFlag = ( + flagKey: string, + state: string, + { available = true, retired = false } = {} + ) => + pool.query( + `insert into app_public.feature_flags (key, state, available, description, retired_at) + values ($1, $2, $3, 'Test flag', case when $4::boolean then now() end)`, + [flagKey, state, available, retired] + ) + + it("follows app_public.feature_enabled for a caller without a session", async () => { + await insertFlag(KEYS[0], "on") + await insertFlag(KEYS[1], "admins_only") + await insertFlag(KEYS[2], "off") + await insertFlag("server_test_unavailable", "on", { available: false }) + await insertFlag("server_test_retired", "off", { retired: true }) + const reader = createFeatureFlagReader(pool) + + const read = (name: string, asAdmin = false) => + reader.isFeatureEnabled(key(name), { asAdmin }) + + expect(await read("server_test_on")).toBe(true) + expect(await read("server_test_preview")).toBe(false) + expect(await read("server_test_preview", true)).toBe(true) + expect(await read("server_test_off", true)).toBe(false) + expect(await read("server_test_unavailable", true)).toBe(false) + expect(await read("server_test_retired")).toBe(true) + expect(await read("server_test_missing", true)).toBe(false) + }) + + describe("syncFeatureAvailability", () => { + const features = { + server_test_integration: { + description: "Needs two secrets", + requiresEnv: ["SERVER_TEST_SECRET_A", "SERVER_TEST_SECRET_B"], + }, + server_test_plain: { description: "Needs nothing" }, + } + + const availability = async () => { + const { rows } = await pool.query( + "select key, available from app_public.feature_flags where key like 'server_test_%' order by key" + ) + return Object.fromEntries(rows.map((row) => [row.key, row.available])) + } + + beforeEach(async () => { + await insertFlag("server_test_integration", "on") + await insertFlag("server_test_plain", "on", { available: false }) + }) + + it("marks an integration unavailable when a variable is missing or empty", async () => { + const result = await syncFeatureAvailability(pool, { + features, + env: { SERVER_TEST_SECRET_A: "x", SERVER_TEST_SECRET_B: "" }, + }) + expect(result).toEqual({ + available: { server_test_integration: false }, + missing: [], + }) + // Flags without requirements are left as they are. + expect(await availability()).toEqual({ + server_test_integration: false, + server_test_plain: false, + }) + const reader = createFeatureFlagReader(pool) + expect( + await reader.isFeatureEnabled(key("server_test_integration")) + ).toBe(false) + }) + + it("marks an integration available again once every variable is set", async () => { + await pool.query( + "update app_public.feature_flags set available = false where key = 'server_test_integration'" + ) + const result = await syncFeatureAvailability(pool, { + features, + env: { SERVER_TEST_SECRET_A: "x", SERVER_TEST_SECRET_B: "y" }, + }) + expect(result.available).toEqual({ server_test_integration: true }) + expect((await availability()).server_test_integration).toBe(true) + }) + + it("reports registry keys that have no row", async () => { + const result = await syncFeatureAvailability(pool, { + features: { + server_test_unmigrated: { + description: "No row", + requiresEnv: ["SERVER_TEST_SECRET_A"], + }, + }, + env: {}, + }) + expect(result).toEqual({ + available: {}, + missing: ["server_test_unmigrated"], + }) + }) + }) +}) diff --git a/@app/server/__tests__/utils/handleErrors.test.ts b/@app/server/__tests__/utils/handleErrors.test.ts new file mode 100644 index 000000000..dd813f406 --- /dev/null +++ b/@app/server/__tests__/utils/handleErrors.test.ts @@ -0,0 +1,62 @@ +import { GraphQLError } from "graphql" + +import handleErrors from "../../src/utils/handleErrors" + +const graphQLError = (originalError?: Error) => + new GraphQLError( + originalError ? originalError.message : "Syntax Error", + undefined, + undefined, + undefined, + ["currentUser"], + originalError + ) + +const withCode = (message: string, code: string) => + Object.assign(new Error(message), { code }) + +describe("handleErrors", () => { + let consoleError: jest.SpyInstance + + beforeEach(() => { + consoleError = jest.spyOn(console, "error").mockImplementation(() => {}) + }) + + afterEach(() => { + consoleError.mockRestore() + }) + + it.each([ + "timeout exceeded when trying to connect", + "Connection terminated due to connection timeout", + ])("logs an error without a code: %s", (message) => { + const originalError = new Error(message) + + const [result] = handleErrors([graphQLError(originalError)]) + + expect(result.message).toEqual(message) + expect(consoleError).toHaveBeenCalledTimes(1) + expect(consoleError).toHaveBeenCalledWith(expect.any(String), originalError) + }) + + it.each([ + ["a database error", withCode("duplicate key value", "23505")], + ["an application error", withCode("Incorrect username/password", "CREDS")], + [ + "a mutation that matched no row", + new Error( + "No values were deleted in collection 'events' because no values you can delete were found matching these criteria." + ), + ], + ])("does not log %s", (_, originalError) => { + handleErrors([graphQLError(originalError)]) + + expect(consoleError).not.toHaveBeenCalled() + }) + + it("does not log an error from the GraphQL request itself", () => { + handleErrors([graphQLError()]) + + expect(consoleError).not.toHaveBeenCalled() + }) +}) diff --git a/@app/server/__tests__/utils/keycloak.test.ts b/@app/server/__tests__/utils/keycloak.test.ts index ae474ad79..4304d3a0c 100644 --- a/@app/server/__tests__/utils/keycloak.test.ts +++ b/@app/server/__tests__/utils/keycloak.test.ts @@ -9,6 +9,8 @@ const baseClaims = { email: "matti.meikalainen@example.com", email_verified: true, name: "Matti Meikäläinen", + given_name: "Matti", + family_name: "Meikäläinen", locale: "fi", realm_access: { roles: ["membership", "ilmo-admin"] }, } @@ -20,9 +22,36 @@ describe("mapKeycloakClaims", () => { email: "matti.meikalainen@example.com", emailVerified: true, name: "Matti Meikäläinen", + givenName: "Matti", + familyName: "Meikäläinen", usernameSuggestion: "matti.meikalainen", locale: "fi", isAdmin: true, + isDeveloper: false, + }) + }) + + it("is a developer with the ilmo-developer role", () => { + const claims = { + ...baseClaims, + realm_access: { roles: ["membership", "ilmo-admin", "ilmo-developer"] }, + } + expect(mapKeycloakClaims(claims)).toMatchObject({ + isAdmin: true, + isDeveloper: true, + }) + }) + + it("maps the developer role independently of the admin role", () => { + // The database requires both for developer rights; the mapping reports + // each role as the token states it. + const claims = { + ...baseClaims, + realm_access: { roles: ["membership", "ilmo-developer"] }, + } + expect(mapKeycloakClaims(claims)).toMatchObject({ + isAdmin: false, + isDeveloper: true, }) }) @@ -36,6 +65,7 @@ describe("mapKeycloakClaims", () => { // null is what lets the callback skip the re-stamp instead of demoting. const { realm_access: _dropped, ...claims } = baseClaims expect(mapKeycloakClaims(claims).isAdmin).toBeNull() + expect(mapKeycloakClaims(claims).isDeveloper).toBeNull() }) it("maps admin status to unknown when roles is not an array", () => { @@ -48,6 +78,9 @@ describe("mapKeycloakClaims", () => { realm_access: { roles: "ilmo-admin" }, }).isAdmin ).toBeNull() + expect( + mapKeycloakClaims({ ...baseClaims, realm_access: {} }).isDeveloper + ).toBeNull() }) it("warns when the realm_access claim is missing entirely", () => { @@ -108,6 +141,25 @@ describe("mapKeycloakClaims", () => { expect(mapKeycloakClaims(claims).name).toBe("matti.meikalainen") }) + it("keeps multi-word given and family names intact", () => { + const claims = { + ...baseClaims, + name: "Anna Maria von Wright", + given_name: " Anna Maria ", + family_name: "von Wright", + } + const profile = mapKeycloakClaims(claims) + expect(profile.givenName).toBe("Anna Maria") + expect(profile.familyName).toBe("von Wright") + }) + + it("maps missing or blank given and family names to null", () => { + const { given_name: _dropped, ...claims } = baseClaims + const profile = mapKeycloakClaims({ ...claims, family_name: " " }) + expect(profile.givenName).toBeNull() + expect(profile.familyName).toBeNull() + }) + it("throws KCCLM naming the missing claims", () => { const { email: _dropped, ...noEmail } = baseClaims const { sub: _dropped2, ...noSub } = baseClaims diff --git a/@app/server/__tests__/utils/poolConfig.test.ts b/@app/server/__tests__/utils/poolConfig.test.ts new file mode 100644 index 000000000..c0d456468 --- /dev/null +++ b/@app/server/__tests__/utils/poolConfig.test.ts @@ -0,0 +1,75 @@ +import { Pool } from "pg" + +import { TEST_DATABASE_URL } from "../../../__tests__/helpers" +import { poolConfig } from "../../src/utils/poolConfig" + +const ENV_VARS = [ + "DATABASE_POOL_MAX_ROOT", + "DATABASE_POOL_MAX_AUTH", + "DATABASE_POOL_ACQUIRE_TIMEOUT_MS", +] + +describe("poolConfig", () => { + const saved: Record = {} + + beforeEach(() => { + for (const name of ENV_VARS) { + saved[name] = process.env[name] + delete process.env[name] + } + }) + + afterEach(() => { + for (const name of ENV_VARS) { + if (saved[name] === undefined) { + delete process.env[name] + } else { + process.env[name] = saved[name] + } + } + }) + + it("defaults the auth pool to 5 connections and a 5 s acquire timeout", () => { + expect(poolConfig("auth")).toEqual({ + max: 5, + connectionTimeoutMillis: 5000, + }) + }) + + it("defaults the root pool to 2 connections", () => { + expect(poolConfig("root").max).toEqual(2) + }) + + it("reads the pool size from the environment", () => { + process.env.DATABASE_POOL_MAX_AUTH = "7" + expect(poolConfig("auth").max).toEqual(7) + }) + + it("reads the acquire timeout from the environment", () => { + process.env.DATABASE_POOL_ACQUIRE_TIMEOUT_MS = "250" + expect(poolConfig("root").connectionTimeoutMillis).toEqual(250) + }) + + it("rejects a non-numeric value, naming the variable", () => { + process.env.DATABASE_POOL_MAX_ROOT = "lots" + expect(() => poolConfig("root")).toThrow(/DATABASE_POOL_MAX_ROOT/) + }) + + it("fails to acquire from an exhausted pool within the timeout", async () => { + const pool = new Pool({ + ...poolConfig("root"), + connectionString: TEST_DATABASE_URL, + max: 1, + connectionTimeoutMillis: 200, + }) + const client = await pool.connect() + try { + const start = Date.now() + await expect(pool.connect()).rejects.toThrow(/timeout/i) + expect(Date.now() - start).toBeLessThan(1000) + } finally { + client.release() + await pool.end() + } + }) +}) diff --git a/@app/server/__tests__/utils/stripe.test.ts b/@app/server/__tests__/utils/stripe.test.ts new file mode 100644 index 000000000..ad79fba40 --- /dev/null +++ b/@app/server/__tests__/utils/stripe.test.ts @@ -0,0 +1,45 @@ +import Stripe from "stripe" + +import { getStripe, resetStripeClient } from "../../src/utils/stripe" + +jest.mock("stripe", () => ({ + __esModule: true, + default: jest.fn().mockImplementation((key: string) => ({ key })), +})) + +const StripeMock = Stripe as unknown as jest.Mock + +const KEYS = ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"] as const +const saved: Record = {} + +beforeEach(() => { + StripeMock.mockClear() + resetStripeClient() + for (const key of KEYS) { + saved[key] = process.env[key] + delete process.env[key] + } +}) + +afterEach(() => { + for (const key of KEYS) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + resetStripeClient() +}) + +describe("getStripe", () => { + it("throws while Stripe is not configured, never building a client, and again once a secret is removed", () => { + expect(() => getStripe()).toThrow(/not configured/) + process.env.STRIPE_SECRET_KEY = "sk_test_123" + expect(() => getStripe()).toThrow(/not configured/) + expect(StripeMock).not.toHaveBeenCalled() + + process.env.STRIPE_WEBHOOK_SECRET = "whsec_123" + getStripe() + expect(StripeMock).toHaveBeenCalledTimes(1) + delete process.env.STRIPE_WEBHOOK_SECRET + expect(() => getStripe()).toThrow(/not configured/) + }) +}) diff --git a/@app/server/__tests__/utils/throttleTopic.test.ts b/@app/server/__tests__/utils/throttleTopic.test.ts new file mode 100644 index 000000000..1695529f1 --- /dev/null +++ b/@app/server/__tests__/utils/throttleTopic.test.ts @@ -0,0 +1,189 @@ +import { PubSub } from "graphql-subscriptions" + +import { throttledTopic } from "../../src/utils/throttleTopic" + +const SOURCE = "graphql:eventRegistrations:6c568ce8-2ee9-442a-b5d3-83454279e308" + +describe("throttledTopic", () => { + let pubsub: PubSub + let received: unknown[] + + beforeEach(async () => { + jest.useFakeTimers() + pubsub = new PubSub() + received = [] + const topic = throttledTopic(pubsub, SOURCE, 1000) + await pubsub.subscribe(topic, (payload) => received.push(payload)) + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it("delivers the first message at once and the last one at the end of the window", () => { + for (let i = 1; i <= 50; i++) { + pubsub.publish(SOURCE, { event: "registrationUpdated", subject: i }) + jest.advanceTimersByTime(2) + } + expect(received).toEqual([{ event: "registrationUpdated", subject: 1 }]) + + jest.advanceTimersByTime(1000) + expect(received).toEqual([ + { event: "registrationUpdated", subject: 1 }, + { event: "registrationUpdated", subject: 50 }, + ]) + + jest.advanceTimersByTime(5000) + expect(received).toHaveLength(2) + }) + + it("delivers a message after a quiet period at once", () => { + pubsub.publish(SOURCE, { subject: "first" }) + jest.advanceTimersByTime(1500) + pubsub.publish(SOURCE, { subject: "second" }) + + expect(received).toEqual([{ subject: "first" }, { subject: "second" }]) + }) + + it("delivers again after the window that flushed the last message", () => { + pubsub.publish(SOURCE, { subject: "first" }) + pubsub.publish(SOURCE, { subject: "trailing" }) + jest.advanceTimersByTime(1000) + expect(received).toEqual([{ subject: "first" }, { subject: "trailing" }]) + + jest.advanceTimersByTime(1000) + pubsub.publish(SOURCE, { subject: "next" }) + expect(received).toEqual([ + { subject: "first" }, + { subject: "trailing" }, + { subject: "next" }, + ]) + }) + + it("delivers a steady stream once per interval, ending with the last message", () => { + let i = 0 + for (let t = 0; t < 3500; t += 100) { + pubsub.publish(SOURCE, { subject: ++i }) + jest.advanceTimersByTime(100) + } + jest.advanceTimersByTime(1000) + + // Immediately at 0 ms, at the ends of the windows at 1000, 2000 and + // 3000 ms, and the trailing message at 4000 ms. + expect(received).toHaveLength(5) + expect(received[received.length - 1]).toEqual({ subject: i }) + }) + + it("throttles each source topic independently", async () => { + const other = "graphql:eventRegistrations:other" + const receivedOther: unknown[] = [] + await pubsub.subscribe(throttledTopic(pubsub, other, 1000), (payload) => + receivedOther.push(payload) + ) + + pubsub.publish(SOURCE, { subject: "a1" }) + pubsub.publish(other, { subject: "b1" }) + pubsub.publish(SOURCE, { subject: "a2" }) + expect(received).toEqual([{ subject: "a1" }]) + expect(receivedOther).toEqual([{ subject: "b1" }]) + + jest.advanceTimersByTime(1000) + expect(received).toEqual([{ subject: "a1" }, { subject: "a2" }]) + expect(receivedOther).toEqual([{ subject: "b1" }]) + }) + + describe("when publishing fails", () => { + let consoleError: jest.SpyInstance + + beforeEach(() => { + consoleError = jest.spyOn(console, "error").mockImplementation(() => {}) + }) + + afterEach(() => { + consoleError.mockRestore() + }) + + it("keeps relaying after a listener throws", async () => { + const source = "graphql:eventRegistrations:throwing" + const delivered: unknown[] = [] + let calls = 0 + await pubsub.subscribe( + throttledTopic(pubsub, source, 1000), + (payload) => { + calls++ + if (calls === 1) { + throw new Error("listener failed") + } + delivered.push(payload) + } + ) + + pubsub.publish(source, { subject: "first" }) + pubsub.publish(source, { subject: "trailing" }) + jest.advanceTimersByTime(1000) + jest.advanceTimersByTime(1000) + pubsub.publish(source, { subject: "next" }) + + expect(delivered).toEqual([{ subject: "trailing" }, { subject: "next" }]) + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining(source), + expect.objectContaining({ message: "listener failed" }) + ) + }) + + it("keeps relaying after a publish rejects", async () => { + const source = "graphql:eventRegistrations:rejecting" + const listeners = new Map void>() + const published: unknown[] = [] + const failingPubSub = { + publish(topic: string, payload: unknown) { + if (topic === source) { + listeners.get(source)(payload) + return Promise.resolve() + } + published.push(payload) + return Promise.reject(new Error("publish failed")) + }, + subscribe(topic: string, onMessage: (payload: unknown) => void) { + listeners.set(topic, onMessage) + }, + } + throttledTopic(failingPubSub, source, 1000) + + failingPubSub.publish(source, { subject: "first" }) + failingPubSub.publish(source, { subject: "trailing" }) + jest.advanceTimersByTime(2000) + failingPubSub.publish(source, { subject: "next" }) + await Promise.resolve() + + expect(published).toEqual([ + { subject: "first" }, + { subject: "trailing" }, + { subject: "next" }, + ]) + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining(source), + expect.objectContaining({ message: "publish failed" }) + ) + }) + }) + + it("relays each source topic once", () => { + const listeners = () => + ( + pubsub as unknown as { ee: { listenerCount(n: string): number } } + ).ee.listenerCount(SOURCE) + + expect(listeners()).toEqual(1) + expect(throttledTopic(pubsub, SOURCE, 1000)).toEqual( + throttledTopic(pubsub, SOURCE, 1000) + ) + expect(listeners()).toEqual(1) + }) + + it("names the throttled topic within Postgres' 63 character channel limit", () => { + const topic = throttledTopic(pubsub, SOURCE, 1000) + expect(topic).not.toEqual(SOURCE) + expect(topic.length).toBeLessThanOrEqual(63) + }) +}) diff --git a/@app/server/package.json b/@app/server/package.json index ca28ad3d7..7b0b9b2c1 100644 --- a/@app/server/package.json +++ b/@app/server/package.json @@ -27,7 +27,7 @@ "@graphile-contrib/pg-simplify-inflector": "^6.1.0", "@graphile/persisted-operations": "^0.1.1", "@graphile/pg-pubsub": "^4.12.3", - "@graphile/subscriptions-lds": "^4.12.3", + "@modelcontextprotocol/sdk": "^1.32.1", "@types/graphql-upload": "^8.0.11", "@zxcvbn-ts/core": "^2.0.4", "@zxcvbn-ts/language-common": "^2.0.1", @@ -48,6 +48,7 @@ "helmet": "^8.0.0", "html-to-text": "^8.2.1", "ioredis": "^5.2.2", + "jose": "^5.10.0", "lodash": "^4.17.21", "mjml": "^4.13.0", "mock-req": "^0.2.0", @@ -62,8 +63,10 @@ "sharp": "^0.30.7", "slugify": "^1.6.5", "source-map-support": "^0.5.21", + "stripe": "^23.0.0", "tslib": "^2.6.0", - "uuid": "^8.3.2" + "uuid": "^8.3.2", + "zod": "^4.6.7" }, "devDependencies": { "@faker-js/faker": "^9.3.0", @@ -71,6 +74,7 @@ "@types/node": "^18.6.5", "@types/nunjucks": "^3.2.1", "@types/pg": "^8.11.10", + "graphql-subscriptions": "^1.2.1", "jest": "^29.7.0", "mock-req": "^0.2.0", "slugify": "^1.6.5", diff --git a/@app/server/postgraphile.tags.jsonc b/@app/server/postgraphile.tags.jsonc index 7a2313ec8..dc71ad9db 100644 --- a/@app/server/postgraphile.tags.jsonc +++ b/@app/server/postgraphile.tags.jsonc @@ -147,6 +147,21 @@ "tags": { "omit": "create,update,delete" } + }, + // A registration profile is read through `User.registrationProfile` and + // written with the `setRegistrationProfile` mutation. + "app_public.registration_profiles": { + "tags": { + "omit": "create,update,delete,all" + }, + "constraint": { + // user_id is the primary key, so a user has at most one profile + "registration_profiles_user_id_fkey": { + "tags": { + "omit": "many" + } + } + } } }, "procedure": { diff --git a/@app/server/src/app.ts b/@app/server/src/app.ts index fc236c61c..c3a79304e 100644 --- a/@app/server/src/app.ts +++ b/@app/server/src/app.ts @@ -95,6 +95,7 @@ export async function makeApp({ await app.register(middleware.installHealth) await app.register(middleware.installDatabasePools) + await app.register(middleware.installFeatureFlags) await app.register(middleware.installRedis) await app.register(middleware.installWorkerUtils) await app.register(middleware.installHelmet) @@ -103,6 +104,10 @@ export async function makeApp({ await app.register(middleware.installCSRFProtection) await app.register(middleware.installPassport) await app.register(middleware.installKeycloak) + // Webhooks and other routes called from outside; see externalRoutes.ts + await app.register(middleware.installExternalRoutes) + // Telegram bot updates by polling; webhook mode is an external route + await app.register(middleware.installTelegramPolling) await app.register(middleware.installStaticUploads) if (isTest || isDev) { // Loaded dynamically so the production bundle never imports diff --git a/@app/server/src/externalRoutes.ts b/@app/server/src/externalRoutes.ts new file mode 100644 index 000000000..83d518d58 --- /dev/null +++ b/@app/server/src/externalRoutes.ts @@ -0,0 +1,102 @@ +import { mcpRoutes } from "./mcp/routes" +import { stripeWebhook } from "./stripeWebhook" +import { telegramWebhook } from "./telegramWebhook" + +import type { FeatureKey } from "@app/lib" +import type { FastifyPluginAsync } from "fastify" + +/** + * Routes that are called from outside the web client: webhooks, API + * endpoints for other programs and similar. Every such route is declared + * here, in `externalRoutes`, and nowhere else: + * + * - `installExternalRoutes` registers the modules that are configured and + * refuses any route a module registers without declaring it. + * - `installCSRFProtection` exempts the declared `csrfExempt` paths of the + * configured modules, and only those, from the CSRF token check. + * + * GraphQL, the SSR pages and the login routes are not external routes. + */ + +export type ExternalRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" + +export interface ExternalRoutePath { + method: ExternalRouteMethod + /** + * The exact URL path the module registers, without a query string or + * route parameters. + */ + path: string + /** + * Skips the CSRF token check for this method and path. Only for routes + * that never read the session cookie and authenticate the caller some + * other way: a signature, a bearer token or a shared secret. + */ + csrfExempt?: boolean +} + +export interface ExternalRouteModule { + /** Shown in logs and errors. */ + name: string + /** Every route the module registers. */ + paths: readonly ExternalRoutePath[] + /** + * Whether the server has the settings this module needs. A module that is + * not configured has no routes and no CSRF exemptions. + */ + configured: () => boolean + /** + * Key of the feature flag that controls this module's routes. + * `installExternalRoutes` answers 404 on them, per request, while the flag + * is off (unless `gateWhenOff` is false). + */ + feature?: FeatureKey + /** + * Whether the flag gate applies to the routes. Defaults to true; false + * keeps the routes answering while the flag is off, for callers that must + * always get through. + */ + gateWhenOff?: boolean + /** Registers the routes. Runs only when `configured()` is true. */ + register: FastifyPluginAsync +} + +/** The registry. Add a module here; do not edit app.ts or the CSRF plugin. */ +export const externalRoutes: readonly ExternalRouteModule[] = [ + telegramWebhook, + mcpRoutes, + stripeWebhook, +] + +export interface CsrfExemption { + method: ExternalRouteMethod + path: string +} + +/** The CSRF-exempt paths of the configured modules. */ +export function csrfExemptions( + modules: readonly ExternalRouteModule[] = externalRoutes +): CsrfExemption[] { + return modules + .filter((module) => module.configured()) + .flatMap((module) => module.paths) + .filter((path) => path.csrfExempt) + .map(({ method, path }) => ({ method, path })) +} + +/** + * Whether a request is to an exempt method and path. The path must match + * exactly; the query string is ignored, as it is when Fastify routes the + * request. + */ +export function isCsrfExempt( + exemptions: readonly CsrfExemption[], + method: string, + url: string +): boolean { + const queryStart = url.indexOf("?") + const path = queryStart === -1 ? url : url.slice(0, queryStart) + return exemptions.some( + (exemption) => exemption.method === method && exemption.path === path + ) +} diff --git a/@app/server/src/mcp/auth.ts b/@app/server/src/mcp/auth.ts new file mode 100644 index 000000000..ac0295763 --- /dev/null +++ b/@app/server/src/mcp/auth.ts @@ -0,0 +1,206 @@ +import { createRemoteJWKSet, JWTPayload, jwtVerify } from "jose" +import { Pool, PoolClient } from "pg" + +import { + BREAK_GLASS_USERNAMES, + ILMO_ADMIN_ROLE, + mapKeycloakClaims, + RequestLogger, +} from "../utils/keycloak" + +export class McpAuthError extends Error { + constructor( + message: string, + readonly oauthError: + | "invalid_token" + | "insufficient_scope" = "invalid_token" + ) { + super(message) + } +} + +export function mcpResourceUrl() { + return `${process.env.ROOT_URL}/mcp` +} + +export function mcpEnabled() { + return !!process.env.KEYCLOAK_ISSUER +} + +/** + * Admin tools require the realm role in the token itself, so revoking it in + * Keycloak takes effect on the next request. The database's own is_admin + * check still applies on top. MCP never writes is_admin: ilmo-mcp does not + * have full scope, so a missing role scope mapping would otherwise demote + * every admin. + */ +export function tokenGrantsAdmin(claims: JWTPayload) { + const roles = (claims.realm_access as { roles?: unknown } | undefined)?.roles + return Array.isArray(roles) && roles.includes(ILMO_ADMIN_ROLE) +} + +type Jwks = ReturnType +let jwksPromise: Promise | null = null + +/** + * Lazy, memoized discovery like getKeycloakConfig: a Keycloak outage must not + * stop the server from booting, and a failed attempt is retried on the next + * request. The web login's discovery is not reused because it needs the web + * client's credentials, which /mcp has no business depending on. + */ +function getJwks(): Promise { + if (!jwksPromise) { + const issuer = process.env.KEYCLOAK_ISSUER! + jwksPromise = fetch(`${issuer}/.well-known/openid-configuration`) + .then(async (res) => { + if (!res.ok) { + throw new Error(`keycloak discovery failed with HTTP ${res.status}`) + } + const metadata = (await res.json()) as { + issuer?: string + jwks_uri?: string + } + if (metadata.issuer !== issuer || !metadata.jwks_uri) { + throw new Error("keycloak discovery document does not match issuer") + } + return createRemoteJWKSet(new URL(metadata.jwks_uri)) + }) + .catch((e) => { + jwksPromise = null + throw e + }) + } + return jwksPromise +} + +export async function verifyAccessToken(token: string): Promise { + const jwks = await getJwks() + let payload: JWTPayload + try { + ;({ payload } = await jwtVerify(token, jwks, { + issuer: process.env.KEYCLOAK_ISSUER!, + audience: mcpResourceUrl(), + })) + } catch { + throw new McpAuthError("The access token is invalid or expired.") + } + // Keycloak marks access tokens with typ Bearer; an ID token or refresh token + // that somehow carried our audience must still not authenticate. + if (payload.typ !== "Bearer") { + throw new McpAuthError("The token is not an access token.") + } + return payload +} + +async function resolveUserId( + client: PoolClient, + claims: JWTPayload, + logger: RequestLogger +): Promise { + const sub = claims.sub! + const { + rows: [linked], + } = await client.query<{ user_id: string }>( + `select user_id from app_public.user_authentications + where service = 'keycloak' and identifier = $1`, + [sub] + ) + // An already linked identity must not go through link_or_register_user: + // that function overwrites the stored auth secrets, which hold the web + // login's id token used as the Keycloak logout hint. + if (linked) return linked.user_id + + let profile + try { + profile = mapKeycloakClaims(claims as Record, logger) + } catch { + throw new McpAuthError( + "The access token is missing the email claim; check the ilmo-mcp client scopes." + ) + } + if (!profile.emailVerified) { + throw new McpAuthError( + "Your Prodeko account email address is not verified." + ) + } + const { + rows: [user], + } = await client.query<{ id: string }>( + `select id from app_private.link_or_register_user($1, $2, $3, $4, $5)`, + [ + null, + "keycloak", + sub, + JSON.stringify({ + username: profile.usernameSuggestion, + email: profile.email, + name: profile.name, + }), + JSON.stringify({}), + ] + ) + return user.id +} + +/** + * Maps a verified access token to an app_private.sessions row, creating the + * user on first use exactly like the web SSO callback would. The session id + * never leaves the server. + */ +export async function resolveMcpSession( + rootPgPool: Pool, + claims: JWTPayload, + logger: RequestLogger +): Promise { + const sid = typeof claims.sid === "string" ? claims.sid : null + if (!claims.sub || !sid) { + throw new McpAuthError("The access token has no sub or sid claim.") + } + + const client = await rootPgPool.connect() + let rollbackFailed = false + try { + await client.query("begin") + const userId = await resolveUserId(client, claims, logger) + + const { + rows: [user], + } = await client.query<{ username: string }>( + "select username from app_public.users where id = $1", + [userId] + ) + if (BREAK_GLASS_USERNAMES.includes(String(user.username).toLowerCase())) { + logger.error( + { userId, sub: claims.sub }, + "mcp: refusing a keycloak identity that resolves to a break-glass account" + ) + throw new McpAuthError("This account cannot use the MCP server.") + } + + const { + rows: [session], + } = await client.query<{ uuid: string; user_id: string }>( + `insert into app_private.sessions (user_id, kind, oauth_sid) + values ($1, 'mcp', $2) + on conflict (oauth_sid) where kind = 'mcp' + do update set last_active = now() + returning uuid, user_id`, + [userId, sid] + ) + if (session.user_id !== userId) { + throw new McpAuthError("The Keycloak session belongs to another user.") + } + await client.query("commit") + return session.uuid + } catch (e) { + try { + await client.query("rollback") + } catch (rollbackError) { + rollbackFailed = true + logger.error({ err: rollbackError }, "mcp: session rollback failed") + } + throw e + } finally { + client.release(rollbackFailed) + } +} diff --git a/@app/server/src/mcp/events.ts b/@app/server/src/mcp/events.ts new file mode 100644 index 000000000..678aa63eb --- /dev/null +++ b/@app/server/src/mcp/events.ts @@ -0,0 +1,152 @@ +import { + CreateEventInput, + McpEventOptionsQuery, + QuestionType, +} from "@app/graphql" +import slugify from "slugify" + +export interface Translated { + fi: string + en?: string +} + +export interface NewEvent { + organizationId: string + categoryId: string + name: Translated + description: { fi?: string; en?: string } + location: string + eventStartTime: string + eventEndTime: string + registrationStartTime: string + registrationEndTime: string + openQuotaSize: number + isHighlighted: boolean + quotas: { title: Translated; size: number }[] + questions: { + type: QuestionType + label: Translated + required: boolean + options?: Translated[] + }[] +} + +function translated(value: Translated) { + return value.en ? { fi: value.fi, en: value.en } : { fi: value.fi } +} + +/** Plain text to the editor's Slate document: blank lines separate paragraphs. */ +export function plainToRichText(text: string) { + return text + .split(/\n\s*\n/) + .map((p) => p.replace(/\s*\n\s*/g, " ").trim()) + .filter(Boolean) + .map((p) => ({ type: "paragraph", children: [{ text: p }] })) +} + +/** + * Same shape as the admin form's slug (getEventSlug in @app/components): the + * start date as YYYY-M-D in Finnish time, then the Finnish name. + */ +export function eventSlug(name: Translated, eventStartTime: string) { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: "Europe/Helsinki", + year: "numeric", + month: "numeric", + day: "numeric", + }).formatToParts(new Date(eventStartTime)) + const part = (type: string) => + Number(parts.find((p) => p.type === type)!.value) + const day = `${part("year")}-${part("month")}-${part("day")}` + return slugify(`${day}-${name.fi}`, { lower: true }) +} + +type Options = NonNullable + +export function validateNewEvent(event: NewEvent, options: Options): string[] { + const errors: string[] = [] + const time = (field: keyof NewEvent) => + new Date(event[field] as string).getTime() + + if ( + !options.organizations?.nodes.some((o) => o.id === event.organizationId) + ) { + errors.push("organizationId is not an organization.") + } + const category = options.eventCategories?.nodes.find( + (c) => c.id === event.categoryId + ) + if (!category) { + errors.push("categoryId is not an event category.") + } else if (category.ownerOrganization?.id !== event.organizationId) { + errors.push("The category belongs to another organization.") + } + + if (!event.description.fi?.trim() && !event.description.en?.trim()) { + errors.push("A description in Finnish or English is required.") + } + if (time("eventStartTime") >= time("eventEndTime")) { + errors.push("The event must end after it starts.") + } + if (time("registrationStartTime") >= time("registrationEndTime")) { + errors.push("Registration must close after it opens.") + } + if (time("registrationEndTime") >= time("eventStartTime")) { + errors.push("Registration must close before the event starts.") + } + if (event.quotas.length === 0 && event.openQuotaSize < 1) { + errors.push("Give at least one quota or an open quota size above zero.") + } + + event.questions.forEach((q, i) => { + const options = q.options ?? [] + if (q.type === QuestionType.Text && options.length > 0) { + errors.push(`Question ${i + 1}: TEXT questions take no options.`) + } + if (q.type !== QuestionType.Text && options.length === 0) { + errors.push(`Question ${i + 1}: ${q.type} questions need options.`) + } + }) + + return errors +} + +export function createEventInput(event: NewEvent): CreateEventInput { + const description: Record> = {} + if (event.description.fi?.trim()) { + description.fi = plainToRichText(event.description.fi) + } + if (event.description.en?.trim()) { + description.en = plainToRichText(event.description.en) + } + + return { + event: { + slug: eventSlug(event.name, event.eventStartTime), + name: translated(event.name), + description, + location: event.location, + eventStartTime: event.eventStartTime, + eventEndTime: event.eventEndTime, + registrationStartTime: event.registrationStartTime, + registrationEndTime: event.registrationEndTime, + isHighlighted: event.isHighlighted, + isDraft: true, + openQuotaSize: event.openQuotaSize, + ownerOrganizationId: event.organizationId, + categoryId: event.categoryId, + }, + quotas: event.quotas.map((q, position) => ({ + position, + title: translated(q.title), + size: q.size, + })), + questions: event.questions.map((q, position) => ({ + position, + type: q.type, + label: translated(q.label), + isRequired: q.required, + data: q.type === QuestionType.Text ? null : q.options!.map(translated), + })), + } +} diff --git a/@app/server/src/mcp/operations.graphql b/@app/server/src/mcp/operations.graphql new file mode 100644 index 000000000..a388ad5fd --- /dev/null +++ b/@app/server/src/mcp/operations.graphql @@ -0,0 +1,87 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + } + category { + name + } +} + +query McpEvents { + signupOpenEvents: events( + filter: { signupOpen: { equalTo: true }, isDraft: { equalTo: false } } + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC] + ) { + nodes { + ...McpEventSummary + } + } + signupUpcomingEvents: events( + filter: { signupUpcoming: { equalTo: true }, isDraft: { equalTo: false } } + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC] + ) { + nodes { + ...McpEventSummary + } + } +} + +query McpEventOptions { + organizations { + nodes { + id + name + } + } + eventCategories(orderBy: NAME_ASC) { + nodes { + id + name + ownerOrganization { + id + } + } + } +} + +query McpEvent($slug: String!) { + currentUser { + name + primaryEmail + } + eventBySlug(slug: $slug) { + ...McpEventSummary + description + isDraft + openQuotaSize + quotas(orderBy: POSITION_ASC) { + nodes { + id + title + size + registrations { + totalCount + } + } + } + eventQuestions(orderBy: POSITION_ASC) { + nodes { + id + type + label + isRequired + data + } + } + } +} diff --git a/@app/server/src/mcp/registration.ts b/@app/server/src/mcp/registration.ts new file mode 100644 index 000000000..fb3fcdbcc --- /dev/null +++ b/@app/server/src/mcp/registration.ts @@ -0,0 +1,117 @@ +import { McpEventQuery, QuestionType } from "@app/graphql" + +type McpEvent = NonNullable + +export type AnswerValue = string | string[] + +export interface RegistrationInput { + quotaId: string + firstName: string + lastName: string + email: string + answers: Record +} + +function optionLabels(data: McpEvent["eventQuestions"]["nodes"][0]["data"]) { + const labels = new Set() + for (const option of data ?? []) { + if (option?.fi) labels.add(option.fi) + if (option?.en) labels.add(option.en) + } + return labels +} + +/** + * Mirrors the database checks so that a doomed request is answered before + * claimRegistrationToken spends one of the requester's rate-limited attempts. + * It is stricter than the database in one respect: radio and checkbox answers + * must be one of the question's options, as they always are on the web form. + */ +export function validateRegistration( + event: McpEvent, + input: RegistrationInput +): string[] { + const errors: string[] = [] + + if (!event.signupOpen) { + errors.push("Registration for this event is not open.") + } + if (!event.quotas.nodes.some((q) => q.id === input.quotaId)) { + errors.push("quotaId is not one of this event's quotas.") + } + for (const [field, value] of [ + ["firstName", input.firstName], + ["lastName", input.lastName], + ] as const) { + if (!value) errors.push(`${field} is required.`) + else if (/\s/.test(value)) errors.push(`${field} must not contain spaces.`) + } + + const questions = new Map(event.eventQuestions.nodes.map((q) => [q.id, q])) + for (const questionId of Object.keys(input.answers)) { + if (!questions.has(questionId)) { + errors.push( + `Answer ${questionId} does not match a question of this event.` + ) + } + } + + for (const question of event.eventQuestions.nodes) { + const label = question.label.en || question.label.fi + const answer = input.answers[question.id] + if (answer === undefined) { + if (question.isRequired) errors.push(`"${label}" is required.`) + continue + } + const options = optionLabels(question.data) + switch (question.type) { + case QuestionType.Text: + if (typeof answer !== "string") { + errors.push(`"${label}" expects a string.`) + } else if (question.isRequired && !answer.trim()) { + errors.push(`"${label}" is required.`) + } + break + case QuestionType.Radio: + if (typeof answer !== "string" || !options.has(answer)) { + errors.push( + `"${label}" expects exactly one of: ${[...options].join(", ")}.` + ) + } + break + case QuestionType.Checkbox: + if ( + !Array.isArray(answer) || + answer.some((a) => typeof a !== "string" || !options.has(a)) + ) { + errors.push( + `"${label}" expects a list of options from: ${[...options].join(", ")}.` + ) + } else if (question.isRequired && answer.length === 0) { + errors.push(`"${label}" requires at least one option.`) + } + break + } + } + + return errors +} + +interface RichTextNode { + text?: string + children?: RichTextNode[] +} + +function nodeText(node: RichTextNode): string { + if (typeof node.text === "string") return node.text + return (node.children ?? []).map(nodeText).join("") +} + +/** Flattens the editor's Slate document into paragraphs of plain text. */ +export function richTextToPlain(nodes: unknown): string { + if (!Array.isArray(nodes)) return "" + return nodes + .map((n) => nodeText(n as RichTextNode)) + .filter(Boolean) + .join("\n\n") +} diff --git a/@app/server/src/mcp/routes.ts b/@app/server/src/mcp/routes.ts new file mode 100644 index 000000000..ce43343f4 --- /dev/null +++ b/@app/server/src/mcp/routes.ts @@ -0,0 +1,185 @@ +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js" +import { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify" +import { graphql, print } from "graphql" +import { PoolClient } from "pg" +import { withPostGraphileContext } from "postgraphile" + +import { OurGraphQLContext } from "../middleware/installPostGraphile" + +import { + McpAuthError, + mcpEnabled, + mcpResourceUrl, + resolveMcpSession, + tokenGrantsAdmin, + verifyAccessToken, +} from "./auth" +import { createMcpServer, GraphQLRunner, RunGraphQL, ToolError } from "./server" + +import type { ExternalRouteModule } from "../externalRoutes" + +const MCP_PATH = "/mcp" +const PROTECTED_RESOURCE_METADATA_PATH = + "/.well-known/oauth-protected-resource/mcp" +const PROTECTED_RESOURCE_METADATA_ROOT_PATH = + "/.well-known/oauth-protected-resource" + +function unauthorized(reply: FastifyReply, error?: McpAuthError) { + const params = [ + `resource_metadata="${process.env.ROOT_URL}${PROTECTED_RESOURCE_METADATA_PATH}"`, + ] + if (error) { + params.push( + `error="${error.oauthError}"`, + `error_description="${error.message.replace(/"/g, "'")}"` + ) + } + return reply + .code(401) + .header("WWW-Authenticate", `Bearer ${params.join(", ")}`) + .send({ error: error?.oauthError ?? "unauthorized" }) +} + +const registerMcpRoutes: FastifyPluginAsync = async (app) => { + // RFC 9728: tells the MCP client which authorization server issues tokens + // for this resource. The root path serves the same document for clients + // that do not insert the resource path. + const protectedResourceMetadata = async () => ({ + resource: mcpResourceUrl(), + authorization_servers: [process.env.KEYCLOAK_ISSUER], + scopes_supported: ["openid", "profile", "email"], + bearer_methods_supported: ["header"], + }) + app.get(PROTECTED_RESOURCE_METADATA_PATH, protectedResourceMetadata) + app.get(PROTECTED_RESOURCE_METADATA_ROOT_PATH, protectedResourceMetadata) + + const handler = async (request: FastifyRequest, reply: FastifyReply) => { + const header = request.headers.authorization + const token = header?.startsWith("Bearer ") ? header.slice(7) : null + if (!token) return unauthorized(reply) + + let sessionId: string + let isAdmin: boolean + try { + const claims = await verifyAccessToken(token) + sessionId = await resolveMcpSession(app.rootPgPool, claims, request.log) + isAdmin = tokenGrantsAdmin(claims) + } catch (e) { + if (e instanceof McpAuthError) return unauthorized(reply, e) + request.log.error({ err: e }, "mcp: authentication failed") + return reply.code(503).send({ error: "temporarily_unavailable" }) + } + + const schema = await app.postgraphile.getGraphQLSchema() + const context: Omit = { + sessionId, + ipAddress: request.ip, + rootPgPool: app.rootPgPool, + redisClient: app.redis, + workerUtils: app.workerUtils, + login: async () => { + throw new Error("login is not available over MCP") + }, + logout: async () => { + throw new Error("logout is not available over MCP") + }, + isSsoSession: () => false, + logger: request.log, + } + + const runner: GraphQLRunner = { + // withPostGraphileContext is typed for a GraphQL result but resolves to + // whatever its callback returns. + transaction: (fn: (run: RunGraphQL) => Promise) => + withPostGraphileContext( + { + pgPool: app.authPgPool, + pgSettings: { + role: process.env.DATABASE_VISITOR, + "jwt.claims.session_id": sessionId, + }, + }, + async (pgContext) => { + // withPostGraphileContext commits even when the callback throws, + // so a failed registration would keep the spot it just claimed. + // Rolling back to this savepoint leaves the commit nothing to do. + const { pgClient } = pgContext as { pgClient: PoolClient } + await pgClient.query("savepoint mcp_transaction") + try { + return (await fn(async (document, variables) => { + const result = await graphql({ + schema, + source: print(document), + contextValue: { ...pgContext, ...context }, + variableValues: variables, + }) + if (result.errors?.length) { + // Database and plugin errors carry the user-facing message + // the web form shows; anything else stays in the log. + const [error] = result.errors + request.log.warn({ err: error }, "mcp: graphql error") + throw new ToolError(error.message) + } + return result.data as any + })) as any + } catch (e) { + await pgClient.query("rollback to savepoint mcp_transaction") + throw e + } + } + ) as Promise, + } + + const server = createMcpServer(runner, { isAdmin }) + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }) + reply.raw.on("close", () => { + transport.close() + server.close() + }) + reply.hijack() + await server.connect(transport) + await transport.handleRequest(request.raw, reply.raw, request.body) + } + + app.post(MCP_PATH, handler) + + // The server is stateless: there is no standalone SSE stream to open and no + // session to delete. Handing GET to the transport left the request hanging + // without a status line, which clients such as claude.ai report as an error. + const methodNotAllowed = async (_: FastifyRequest, reply: FastifyReply) => + reply + .code(405) + .header("Allow", "POST") + .send({ + jsonrpc: "2.0", + error: { code: -32000, message: "Method not allowed." }, + id: null, + }) + app.get(MCP_PATH, methodNotAllowed) + app.delete(MCP_PATH, methodNotAllowed) +} + +/** + * The MCP endpoint and its OAuth protected resource metadata. Registered by + * installExternalRoutes when Keycloak is configured; the routes answer 404 + * while the `mcp_server` flag is off. + */ +export const mcpRoutes: ExternalRouteModule = { + name: "mcp", + paths: [ + // Authenticates with a Keycloak bearer token and never reads the session + // cookie, so there is no ambient credential for a cross-site request to + // ride on. + { method: "POST", path: MCP_PATH, csrfExempt: true }, + { method: "GET", path: MCP_PATH }, + { method: "DELETE", path: MCP_PATH }, + { method: "GET", path: PROTECTED_RESOURCE_METADATA_PATH }, + { method: "GET", path: PROTECTED_RESOURCE_METADATA_ROOT_PATH }, + ], + configured: mcpEnabled, + feature: "mcp_server", + register: registerMcpRoutes, +} diff --git a/@app/server/src/mcp/server.ts b/@app/server/src/mcp/server.ts new file mode 100644 index 000000000..a34fa93f7 --- /dev/null +++ b/@app/server/src/mcp/server.ts @@ -0,0 +1,364 @@ +import { + ClaimRegistrationTokenDocument, + ClaimRegistrationTokenMutation, + CreateEventDocument, + CreateEventMutation, + CreateEventRegistrationDocument, + CreateEventRegistrationMutation, + McpEventDocument, + McpEventOptionsDocument, + McpEventOptionsQuery, + McpEventQuery, + McpEventsDocument, + McpEventsQuery, + McpEventSummaryFragment, + QuestionType, +} from "@app/graphql" +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" +import { CallToolResult } from "@modelcontextprotocol/sdk/types.js" +import { DocumentNode } from "graphql" +import { z } from "zod" + +import { createEventInput, validateNewEvent } from "./events" +import { richTextToPlain, validateRegistration } from "./registration" + +/** + * Runs one GraphQL operation as the MCP user. Every call passed to + * `transaction` shares a single database transaction, which is rolled back + * when the callback throws. + */ +export type RunGraphQL = ( + document: DocumentNode, + variables?: Record +) => Promise + +export interface GraphQLRunner { + transaction(fn: (run: RunGraphQL) => Promise): Promise +} + +export class ToolError extends Error {} + +function json(value: unknown): CallToolResult { + return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] } +} + +function toolError(message: string): CallToolResult { + return { isError: true, content: [{ type: "text", text: message }] } +} + +async function withToolErrors( + fn: () => Promise +): Promise { + try { + return await fn() + } catch (e) { + if (e instanceof ToolError) return toolError(e.message) + throw e + } +} + +function summary(event: McpEventSummaryFragment) { + return { + slug: event.slug, + name: event.name, + organizer: event.ownerOrganization?.name ?? null, + category: event.category?.name ?? null, + location: event.location, + eventStartTime: event.eventStartTime, + eventEndTime: event.eventEndTime, + registrationStartTime: event.registrationStartTime, + registrationEndTime: event.registrationEndTime, + signupOpen: !!event.signupOpen, + } +} + +async function fetchEvent(runner: GraphQLRunner, slug: string) { + const data = await runner.transaction((run) => + run(McpEventDocument, { slug }) + ) + if (!data.eventBySlug) { + throw new ToolError(`No published event with slug "${slug}".`) + } + return { event: data.eventBySlug, currentUser: data.currentUser } +} + +export function createMcpServer( + runner: GraphQLRunner, + { isAdmin }: { isAdmin: boolean } +) { + const server = new McpServer({ name: "ilmo", version: "1.0.0" }) + + server.registerTool( + "list_events", + { + title: "List events", + description: + "Lists published Prodeko events whose registration is open now or opens later. Names are given in Finnish (fi) and English (en); times are ISO 8601.", + annotations: { readOnlyHint: true }, + }, + () => + withToolErrors(async () => { + const data = await runner.transaction((run) => + run(McpEventsDocument) + ) + return json({ + registrationOpen: data.signupOpenEvents?.nodes.map(summary) ?? [], + registrationUpcoming: + data.signupUpcomingEvents?.nodes.map(summary) ?? [], + }) + }) + ) + + server.registerTool( + "get_event", + { + title: "Get event", + description: + "Returns one event with its description, quotas (with how many have registered) and the registration questions. Call this before register_to_event: it lists the quota ids, the question ids and the allowed answer options.", + inputSchema: { slug: z.string().describe("Event slug from list_events") }, + annotations: { readOnlyHint: true }, + }, + ({ slug }) => + withToolErrors(async () => { + const { event, currentUser } = await fetchEvent(runner, slug) + return json({ + ...summary(event), + description: { + fi: richTextToPlain(event.description?.fi), + en: richTextToPlain(event.description?.en), + }, + quotas: event.quotas.nodes.map((q) => ({ + id: q.id, + title: q.title, + size: q.size, + registered: q.registrations.totalCount, + })), + openQuotaSize: event.openQuotaSize, + questions: event.eventQuestions.nodes.map((q) => ({ + id: q.id, + type: q.type, + label: q.label, + required: q.isRequired, + options: q.data?.filter(Boolean) ?? null, + })), + answerFormat: + "answers maps question id to a string for TEXT and RADIO questions and to a list of strings for CHECKBOX questions. RADIO and CHECKBOX answers must be option labels, in either language.", + you: { + name: currentUser?.name ?? null, + email: currentUser?.primaryEmail ?? null, + }, + }) + }) + ) + + server.registerTool( + "register_to_event", + { + title: "Register to event", + description: + "Registers a person to an event quota. Registrations are first come, first served: when the quota is full the person is placed in the open quota or the queue, and the result says which. A confirmation email with a link for editing or cancelling the registration is sent to the given email address. Confirm the details with the user before calling this.", + inputSchema: { + slug: z.string().describe("Event slug"), + quotaId: z.string().describe("Quota id from get_event"), + firstName: z.string().describe("First name, no spaces"), + lastName: z.string().describe("Last name, no spaces"), + email: z + .string() + .email() + .optional() + .describe("Defaults to the signed-in user's primary email"), + answers: z + .record(z.string(), z.union([z.string(), z.array(z.string())])) + .optional() + .describe("Question id to answer, see get_event"), + }, + annotations: { readOnlyHint: false, destructiveHint: false }, + }, + (args) => + withToolErrors(async () => { + const { event, currentUser } = await fetchEvent(runner, args.slug) + const email = args.email ?? currentUser?.primaryEmail + if (!email) { + throw new ToolError( + "No email given and the signed-in user has no primary email." + ) + } + const input = { + quotaId: args.quotaId, + firstName: args.firstName, + lastName: args.lastName, + email, + answers: args.answers ?? {}, + } + const errors = validateRegistration(event, input) + if (errors.length > 0) { + throw new ToolError( + `Registration not sent:\n- ${errors.join("\n- ")}` + ) + } + + const registration = await runner.transaction(async (run) => { + const claim = await run( + ClaimRegistrationTokenDocument, + { input: { eventId: event.id, quotaId: input.quotaId } } + ) + const registrationToken = + claim.claimRegistrationToken?.claimRegistrationTokenOutput + ?.registrationToken + if (!registrationToken) { + throw new ToolError("Claiming a registration spot failed.") + } + const created = await run( + CreateEventRegistrationDocument, + { + input: { + ...input, + eventId: event.id, + registrationToken, + }, + } + ) + return created.createRegistration?.registration + }) + if (!registration) { + throw new ToolError("Registration failed.") + } + + return json({ + registered: true, + event: event.name, + quota: registration.quota?.title ?? null, + status: registration.status, + position: registration.position, + email, + note: "IN_QUOTA means a confirmed spot, IN_OPEN_QUOTA a spot in the shared open quota, IN_QUEUE a place in the waiting list. A confirmation email was sent.", + }) + }) + ) + + if (isAdmin) registerAdminTools(server, runner) + + return server +} + +const translatedSchema = z.object({ + fi: z.string().min(1), + en: z.string().min(1).optional(), +}) + +const datetimeSchema = z.iso + .datetime({ offset: true }) + .describe("ISO 8601 with a UTC offset, e.g. 2026-11-07T10:00:00+02:00") + +function registerAdminTools(server: McpServer, runner: GraphQLRunner) { + server.registerTool( + "list_event_options", + { + title: "List organizers and categories", + description: + "Admin only. Lists the organizations that can organize events and the event categories of each, with the ids create_event needs.", + annotations: { readOnlyHint: true }, + }, + () => + withToolErrors(async () => { + const data = await runner.transaction((run) => + run(McpEventOptionsDocument) + ) + const categories = data.eventCategories?.nodes ?? [] + const organizations = [...(data.organizations?.nodes ?? [])].sort( + (a, b) => a.name.localeCompare(b.name, "fi") + ) + return json( + organizations.map((o) => ({ + id: o.id, + name: o.name, + categories: categories + .filter((c) => c.ownerOrganization?.id === o.id) + .map((c) => ({ id: c.id, name: c.name })), + })) + ) + }) + ) + + server.registerTool( + "create_event", + { + title: "Create event (draft)", + description: + "Admin only. Creates an event as an unpublished draft with its quotas and registration questions. An admin reviews and publishes it in the ilmo admin UI; the result links there. Confirm the details with the user before calling this. Finnish texts are required, English ones optional.", + inputSchema: { + organizationId: z.string().describe("From list_event_options"), + categoryId: z + .string() + .describe("A category of that organization, from list_event_options"), + name: translatedSchema, + description: z + .object({ fi: z.string().optional(), en: z.string().optional() }) + .describe("Plain text; separate paragraphs with a blank line"), + location: z.string().min(1), + eventStartTime: datetimeSchema, + eventEndTime: datetimeSchema, + registrationStartTime: datetimeSchema, + registrationEndTime: datetimeSchema.describe( + "Must be before eventStartTime" + ), + openQuotaSize: z + .number() + .int() + .min(0) + .default(0) + .describe( + "Extra spots shared by all quotas once a quota is full; 0 for none" + ), + isHighlighted: z.boolean().default(false), + quotas: z + .array( + z.object({ title: translatedSchema, size: z.number().int().min(1) }) + ) + .default([]), + questions: z + .array( + z.object({ + type: z.enum(QuestionType), + label: translatedSchema, + required: z.boolean().default(false), + options: z + .array(translatedSchema) + .optional() + .describe("Answer options for RADIO and CHECKBOX questions"), + }) + ) + .default([]), + }, + annotations: { readOnlyHint: false, destructiveHint: false }, + }, + (args) => + withToolErrors(async () => { + const options = await runner.transaction((run) => + run(McpEventOptionsDocument) + ) + const errors = validateNewEvent(args, options) + if (errors.length > 0) { + throw new ToolError(`Event not created:\n- ${errors.join("\n- ")}`) + } + + const data = await runner.transaction((run) => + run(CreateEventDocument, { + input: createEventInput(args), + }) + ) + const event = data.createEvent?.event + if (!event) throw new ToolError("Creating the event failed.") + + return json({ + created: true, + isDraft: true, + id: event.id, + slug: event.slug, + name: event.name, + editUrl: `${process.env.ROOT_URL}/admin/event/update/${event.id}`, + note: "The event is a draft and not visible to members. Review it at editUrl and publish it there.", + }) + }) + ) +} diff --git a/@app/server/src/middleware/index.ts b/@app/server/src/middleware/index.ts index a62aa6bfd..7bfc3b5cb 100644 --- a/@app/server/src/middleware/index.ts +++ b/@app/server/src/middleware/index.ts @@ -1,6 +1,8 @@ import installCSRFProtection from "./installCSRFProtection" import installDatabasePools from "./installDatabasePools" import installErrorHandler from "./installErrorHandler" +import installExternalRoutes from "./installExternalRoutes" +import installFeatureFlags from "./installFeatureFlags" import installFileUpload from "./installFileUpload" import installHealth from "./installHealth" import installHelmet from "./installHelmet" @@ -12,12 +14,15 @@ import installSameOrigin from "./installSameOrigin" import installSession from "./installSession" import installSSR from "./installSSR" import installStaticUploads from "./installStaticUploads" +import installTelegramPolling from "./installTelegramPolling" import installWorkerUtils from "./installWorkerUtils" export { installCSRFProtection, installDatabasePools, installErrorHandler, + installExternalRoutes, + installFeatureFlags, installFileUpload, installHealth, installHelmet, @@ -29,5 +34,6 @@ export { installSession, installSSR, installStaticUploads, + installTelegramPolling, installWorkerUtils, } diff --git a/@app/server/src/middleware/installCSRFProtection.ts b/@app/server/src/middleware/installCSRFProtection.ts index 137cce20e..5ec79fd4a 100644 --- a/@app/server/src/middleware/installCSRFProtection.ts +++ b/@app/server/src/middleware/installCSRFProtection.ts @@ -2,6 +2,13 @@ import fastifyCSRF from "@fastify/csrf-protection" import { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify" import fp from "fastify-plugin" +import { + csrfExemptions, + ExternalRouteModule, + externalRoutes, + isCsrfExempt, +} from "../externalRoutes" + import { cookieOptions as sessionCookieOptions, handleSessionCookie, @@ -46,7 +53,19 @@ async function handleCsrfToken(request: FastifyRequest, reply: FastifyReply) { } } -const CSRFProtection: FastifyPluginAsync = async (app) => { +export interface CSRFProtectionOptions { + /** Defaults to the registry in externalRoutes.ts. */ + externalRoutes?: readonly ExternalRouteModule[] +} + +const CSRFProtection: FastifyPluginAsync = async ( + app, + options +) => { + // External routes authenticate without the session cookie; their exempt + // paths come from the registry, never from a list kept here. + const exemptions = csrfExemptions(options.externalRoutes ?? externalRoutes) + await app.register(fastifyCSRF, { sessionPlugin: "@fastify/secure-session", }) @@ -65,6 +84,8 @@ const CSRFProtection: FastifyPluginAsync = async (app) => { ) { // Bypass CSRF for GraphiQL in dev done() + } else if (isCsrfExempt(exemptions, request.method, request.url)) { + done() } else if (request.method === "POST") { // Add CSRF protection to POST requests app.csrfProtection(request, reply, done) diff --git a/@app/server/src/middleware/installCypressServerCommand.ts b/@app/server/src/middleware/installCypressServerCommand.ts index 5d4d66c41..6a5f78a1f 100644 --- a/@app/server/src/middleware/installCypressServerCommand.ts +++ b/@app/server/src/middleware/installCypressServerCommand.ts @@ -1,3 +1,4 @@ +import { randomBytes } from "crypto" import { IncomingMessage, Server, ServerResponse } from "http" import { ParsedUrlQuery } from "querystring" @@ -10,10 +11,17 @@ import { Registration, User, } from "@app/graphql" -import { RegistrationSecret, Session } from "@app/lib" +import { + FEATURE_FLAG_STATES, + FeatureFlagState, + RegistrationSecret, + SERVICE_FEE_CENTS, + Session, +} from "@app/lib" import { faker } from "@faker-js/faker" import dayjs from "dayjs" import { + FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest, @@ -23,6 +31,10 @@ import fp from "fastify-plugin" import { Pool, PoolClient } from "pg" import slugify from "slugify" +import { STRIPE_WEBHOOK_PATH } from "../stripeWebhook" +import { invalidateFeatureFlags } from "../utils/featureFlags" +import { getStripe, paymentsConfigured } from "../utils/stripe" + import type { RouteGenericInterface } from "fastify/types/route" import type { SnakeCasedProperties } from "type-fest" @@ -85,7 +97,14 @@ const CypressServerCommands: FastifyPluginAsync = async (app) => { const payload = rawPayload ? JSON.parse(String(rawPayload)) : {} // Now run the actual command: - const result = await runCommand(req, res, rootPgPool, command, payload) + const result = await runCommand( + app, + req, + res, + rootPgPool, + command, + payload + ) if (result === null || command === "login") { /* @@ -122,6 +141,7 @@ const CypressServerCommands: FastifyPluginAsync = async (app) => { } async function runCommand( + app: FastifyInstance, req: FastifyRequest, res: FastifyReply, rootPgPool: Pool, @@ -150,9 +170,18 @@ async function runCommand( delete from app_public.organizations; -- Delete graphile worker jobs (storage moved to _private_jobs in 0.16) - delete from graphile_worker._private_jobs;` + delete from graphile_worker._private_jobs; + + update app_public.feature_flags set state = 'off' where state <> 'off';` ) + invalidateFeatureFlags() return { success: true } + } else if (command === "setFeatureFlags") { + return setFeatureFlags(rootPgPool, payload) + } else if (command === "createTestFeatureFlag") { + return createTestFeatureFlag(rootPgPool, payload) + } else if (command === "deleteTestFeatureFlags") { + return deleteTestFeatureFlags(rootPgPool) } else if (command === "createUser") { if (!payload) { throw new Error("Payload required") @@ -166,6 +195,7 @@ async function runCommand( password = "TestUserPassword", verified = false, isAdmin = false, + isDeveloper = false, } = payload if (!username.startsWith("testuser")) { @@ -180,6 +210,7 @@ async function runCommand( password, verified, isAdmin, + isDeveloper, }) let verificationToken: string | null = null @@ -201,17 +232,16 @@ async function runCommand( orgs = [], verified = false, isAdmin = false, + isDeveloper = false, existingUser = false, } = payload - const client = await rootPgPool.connect() - let user: SnakeCasedProperties, otherUser: SnakeCasedProperties, session: any, otherSession: any if (existingUser) { - const { rows } = await client.query( + const { rows } = await rootPgPool.query( "select * from app_private.login($1, $2)", [username, password] ) @@ -225,6 +255,7 @@ async function runCommand( password, verified, isAdmin, + isDeveloper, }) otherUser = await reallyCreateUser(rootPgPool, { username: "testuser_other", @@ -238,6 +269,7 @@ async function runCommand( otherSession = await createSession(rootPgPool, otherUser.id) } + const client = await rootPgPool.connect() try { await client.query("begin") try { @@ -289,14 +321,23 @@ async function runCommand( } else if (command === "createRegistrations") { const { eventId, quotaId, count = 1 } = payload const client = await rootPgPool.connect() - const registrations = await createRegistrations( - client, - count, - eventId, - quotaId, - [] + try { + return await createRegistrations(client, count, eventId, quotaId, []) + } finally { + client.release() + } + } else if (command === "closeEventRegistration") { + // Ends the event's registration a moment ago, as if it had closed + const { eventId } = payload + await rootPgPool.query( + `update app_public.events + set registration_end_time = now() - interval '1 second' + where id = $1`, + [eventId] ) - return registrations + return { success: true } + } else if (command === "completeStripeCheckout") { + return completeStripeCheckout(app, rootPgPool, payload) } else { throw new Error(`Command '${command}' not understood.`) } @@ -318,6 +359,7 @@ async function reallyCreateUser( password, verified, isAdmin, + isDeveloper = false, }: { username?: string email?: string @@ -326,6 +368,7 @@ async function reallyCreateUser( password?: string verified?: boolean isAdmin?: boolean + isDeveloper?: boolean } ): Promise> { const { @@ -342,9 +385,130 @@ async function reallyCreateUser( )`, [username, email, name, avatarUrl, password, verified, isAdmin] ) + if (isDeveloper) { + // Developer rights come from Keycloak or a direct update only. + const { + rows: [developer], + } = await rootPgPool.query( + "update app_public.users set is_developer = true where id = $1 returning *", + [user.id] + ) + return developer + } return user } +/** + * Sets feature flag states, `{ key: state }`, bypassing the developer check + * and the audit log. Every key must have a row; clearTestEventData switches + * all flags back off. + */ +/** Keys of flag rows that e2e tests may create and delete. */ +const TEST_FEATURE_FLAG_PREFIX = "test_e2e_" + +/** + * Creates (or resets) a flag row that no feature uses, for tests of the + * Features page. Its change history is cleared. deleteTestFeatureFlags + * removes it again. + */ +async function createTestFeatureFlag( + rootPgPool: Pool, + payload: { [key: string]: unknown } | undefined +) { + const { + key, + state = "off", + available = true, + description = "Feature flag created by an e2e test", + } = (payload ?? {}) as { + key?: unknown + state?: unknown + available?: unknown + description?: unknown + } + if (typeof key !== "string" || !key.startsWith(TEST_FEATURE_FLAG_PREFIX)) { + throw new Error( + `Test feature flag keys must start with "${TEST_FEATURE_FLAG_PREFIX}"` + ) + } + if (!FEATURE_FLAG_STATES.includes(state as FeatureFlagState)) { + throw new Error( + `Invalid state ${JSON.stringify(state)} for feature flag "${key}"` + ) + } + await rootPgPool.query( + `with deleted_events as ( + delete from app_private.feature_flag_events where key = $1 + ) + insert into app_public.feature_flags (key, state, available, description) + values ($1, $2, $3, $4) + on conflict (key) do update + set + state = excluded.state, + available = excluded.available, + description = excluded.description, + updated_at = now(), + updated_by = null, + retired_at = null`, + [key, state, Boolean(available), String(description)] + ) + invalidateFeatureFlags() + return { success: true } +} + +/** Deletes the flag rows and history created by createTestFeatureFlag. */ +async function deleteTestFeatureFlags(rootPgPool: Pool) { + const pattern = `${TEST_FEATURE_FLAG_PREFIX.replace(/_/g, "\\_")}%` + await rootPgPool.query( + `with deleted_events as ( + delete from app_private.feature_flag_events where key like $1 + ) + delete from app_public.feature_flags where key like $1`, + [pattern] + ) + invalidateFeatureFlags() + return { success: true } +} + +async function setFeatureFlags( + rootPgPool: Pool, + payload: { [key: string]: unknown } +) { + const entries = Object.entries(payload) + for (const [key, state] of entries) { + if (!FEATURE_FLAG_STATES.includes(state as FeatureFlagState)) { + throw new Error( + `Invalid state ${JSON.stringify(state)} for feature flag "${key}"` + ) + } + } + const client = await rootPgPool.connect() + try { + await client.query("begin") + try { + for (const [key, state] of entries) { + const { rowCount } = await client.query( + "update app_public.feature_flags set state = $2 where key = $1", + [key, state] + ) + if (!rowCount) { + throw new Error( + `Feature flag "${key}" has no row in app_public.feature_flags` + ) + } + } + await client.query("commit") + } catch (e) { + await client.query("rollback") + throw e + } + } finally { + client.release() + } + invalidateFeatureFlags() + return { success: true } +} + async function createEventData( rootPgPool: Pool, payload: { [key: string]: any } @@ -356,6 +520,8 @@ async function createEventData( userIsAdmin = false, openQuotaSize = 0, quotaSize = 5, + // Payments: the quota's ticket price + priceCents = 0, } = payload try { @@ -388,7 +554,15 @@ async function createEventData( eventSignupClosed, openQuotaSize ) - const [quota] = await createQuotas(client, 1, event.id, quotaSize) + let [quota] = await createQuotas(client, 1, event.id, quotaSize) + if (priceCents) { + ;({ + rows: [quota], + } = await client.query( + "update app_public.quotas set price_cents = $2 where id = $1 returning *", + [quota.id, priceCents] + )) + } const [question] = await createQuestions(client, 1, event.id, false) let registration, registrationSecret if (!eventSignupClosed && !eventSignupUpcoming) { @@ -794,4 +968,159 @@ async function getUserEmailSecrets(rootPgPool: Pool, email: string) { return userEmailSecrets } +/******************************************************************************/ +// Payments + +const randomId = () => randomBytes(12).toString("hex") + +/** + * Pays for the registration behind `updateToken` as if the participant had + * completed Stripe Checkout: makes sure the registration has a PENDING card + * payment with a Checkout Session id (the e2e tests stub the real + * createCheckoutSession, so there usually is none yet) and then posts a + * `checkout.session.completed` event, signed with STRIPE_WEBHOOK_SECRET, to + * the real webhook route. Stripe itself is never contacted. + */ +async function completeStripeCheckout( + app: FastifyInstance, + rootPgPool: Pool, + payload: { [key: string]: any } +) { + if (!paymentsConfigured()) { + throw new Error("completeStripeCheckout requires Stripe to be configured") + } + if (!/^(sk|rk)_test_/.test(process.env.STRIPE_SECRET_KEY || "")) { + throw new Error("completeStripeCheckout requires a Stripe test-mode key") + } + const { updateToken } = payload + if (!updateToken) { + throw new Error("updateToken required") + } + + const client = await rootPgPool.connect() + let payment: { + id: string + registration_id: string + event_id: string + quota_id: string + stripe_checkout_session_id: string + total_cents: number + } + try { + await client.query("begin") + const { + rows: [registration], + } = await client.query( + `select r.id, q.price_cents + from app_private.registration_secrets as rs + join app_public.registrations as r on r.id = rs.registration_id + join app_public.quotas as q on q.id = r.quota_id + where rs.update_token = $1 + for update of r`, + [updateToken] + ) + if (!registration?.price_cents) { + throw new Error("No paid registration found for the update token") + } + + const sessionId = `cs_test_cypress_${randomId()}` + const { + rows: [pending], + } = await client.query( + `update app_public.payments + set stripe_checkout_session_id = coalesce(stripe_checkout_session_id, $2) + where id = ( + select id from app_public.payments + where registration_id = $1 and method = 'STRIPE' and status = 'PENDING' + order by created_at desc + limit 1 + ) + returning id, registration_id, event_id, quota_id, + stripe_checkout_session_id, + ticket_amount_cents + service_fee_cents as total_cents`, + [registration.id, sessionId] + ) + if (pending) { + payment = pending + } else { + const { + rows: [inserted], + } = await client.query( + `insert into app_public.payments( + registration_id, event_id, quota_id, event_name, quota_title, + method, status, ticket_amount_cents, service_fee_cents, currency, + stripe_checkout_session_id + ) + select r.id, r.event_id, r.quota_id, e.name, q.title, + 'STRIPE', 'PENDING', q.price_cents, $2, 'eur', $3 + from app_public.registrations as r + join app_public.events as e on e.id = r.event_id + join app_public.quotas as q on q.id = r.quota_id + where r.id = $1 + returning id, registration_id, event_id, quota_id, + stripe_checkout_session_id, + ticket_amount_cents + service_fee_cents as total_cents`, + [registration.id, SERVICE_FEE_CENTS, sessionId] + ) + payment = inserted + } + await client.query("commit") + } catch (e) { + await client.query("rollback") + throw e + } finally { + client.release() + } + + const metadata = { + registration_id: payment.registration_id, + event_id: payment.event_id, + quota_id: payment.quota_id, + payment_id: payment.id, + } + const event = { + id: `evt_test_cypress_${randomId()}`, + object: "event", + type: "checkout.session.completed", + created: Math.floor(Date.now() / 1000), + livemode: false, + data: { + object: { + id: payment.stripe_checkout_session_id, + object: "checkout.session", + mode: "payment", + status: "complete", + payment_status: "paid", + payment_intent: `pi_test_cypress_${randomId()}`, + amount_total: payment.total_cents, + currency: "eur", + metadata, + }, + }, + } + const body = JSON.stringify(event) + const signature = getStripe().webhooks.generateTestHeaderString({ + payload: body, + secret: process.env.STRIPE_WEBHOOK_SECRET!, + }) + const response = await app.inject({ + method: "POST", + url: STRIPE_WEBHOOK_PATH, + headers: { + "content-type": "application/json; charset=utf-8", + "stripe-signature": signature, + }, + payload: body, + }) + if (response.statusCode !== 200) { + throw new Error( + `Stripe webhook answered ${response.statusCode}: ${response.body}` + ) + } + return { + paymentId: payment.id, + sessionId: payment.stripe_checkout_session_id, + } +} + export default fp(CypressServerCommands) diff --git a/@app/server/src/middleware/installDatabasePools.ts b/@app/server/src/middleware/installDatabasePools.ts index b85c7d758..94e8f2b63 100644 --- a/@app/server/src/middleware/installDatabasePools.ts +++ b/@app/server/src/middleware/installDatabasePools.ts @@ -2,6 +2,8 @@ import { FastifyPluginAsync } from "fastify" import fp from "fastify-plugin" import { Pool } from "pg" +import { poolConfig } from "../utils/poolConfig" + declare module "fastify" { export interface FastifyInstance { authPgPool: Pool @@ -24,13 +26,16 @@ function swallowPoolError(_error: Error) { const DatabasePools: FastifyPluginAsync = async (app) => { // This pool runs as the database owner, so it can do anything. const rootPgPool = new Pool({ + ...poolConfig("root"), connectionString: process.env.DATABASE_URL, }) rootPgPool.on("error", swallowPoolError) app.decorate("rootPgPool", rootPgPool) // This pool runs as the unprivileged user, it's what PostGraphile uses. + // @graphile/pg-pubsub holds one of its connections for LISTEN. const authPgPool = new Pool({ + ...poolConfig("auth"), connectionString: process.env.AUTH_DATABASE_URL, }) authPgPool.on("error", swallowPoolError) diff --git a/@app/server/src/middleware/installExternalRoutes.ts b/@app/server/src/middleware/installExternalRoutes.ts new file mode 100644 index 000000000..bdf898dfa --- /dev/null +++ b/@app/server/src/middleware/installExternalRoutes.ts @@ -0,0 +1,72 @@ +import { FastifyPluginAsync, RouteOptions } from "fastify" +import fp from "fastify-plugin" + +import { + ExternalRouteModule, + externalRoutes as registry, +} from "../externalRoutes" +import { isFeatureEnabled as readFeatureFlag } from "../utils/featureFlags" + +import type { FeatureKey } from "@app/lib" + +export interface ExternalRoutesOptions { + /** Defaults to the registry in externalRoutes.ts. */ + externalRoutes?: readonly ExternalRouteModule[] + /** Defaults to the server's `isFeatureEnabled`. */ + isFeatureEnabled?: (key: FeatureKey) => Promise +} + +function isDeclared(module: ExternalRouteModule, method: string, url: string) { + return module.paths.some( + (declared) => + declared.path === url && + // Fastify adds a HEAD route for every GET route + (declared.method === method || + (method === "HEAD" && declared.method === "GET")) + ) +} + +function assertDeclared(module: ExternalRouteModule, route: RouteOptions) { + const methods = Array.isArray(route.method) ? route.method : [route.method] + for (const method of methods) { + if (!isDeclared(module, method, route.url)) { + throw new Error( + `External route module '${module.name}' registered ${method} ${route.url}, which is not in its paths` + ) + } + } +} + +/** + * Registers the routes of every configured module in the external route + * registry. Each module gets its own encapsulated context, in which any + * route it did not declare is an error, and in which the routes answer 404 + * while the module's feature flag is off (checked per request; the CSRF + * check of a non-exempt route still runs first). + */ +const ExternalRoutes: FastifyPluginAsync = async ( + app, + { externalRoutes = registry, isFeatureEnabled = readFeatureFlag } +) => { + for (const module of externalRoutes) { + if (!module.configured()) { + app.log.info(`${module.name}: not configured, routes not registered`) + continue + } + await app.register(async (scope) => { + scope.addHook("onRoute", (route) => assertDeclared(module, route)) + const { feature } = module + if (feature && module.gateWhenOff !== false) { + scope.addHook("onRequest", async (_request, reply) => { + if (!(await isFeatureEnabled(feature))) { + reply.callNotFound() + return reply + } + }) + } + await scope.register(module.register) + }) + } +} + +export default fp(ExternalRoutes) diff --git a/@app/server/src/middleware/installFeatureFlags.ts b/@app/server/src/middleware/installFeatureFlags.ts new file mode 100644 index 000000000..91712af3e --- /dev/null +++ b/@app/server/src/middleware/installFeatureFlags.ts @@ -0,0 +1,44 @@ +import { FastifyPluginAsync } from "fastify" +import fp from "fastify-plugin" + +import { + configureFeatureFlags, + syncFeatureAvailability, +} from "../utils/featureFlags" + +/** + * Makes `isFeatureEnabled` read through the root pool, and records at boot + * which integration-backed features this server is configured for. Must be + * registered after installDatabasePools. + */ +const FeatureFlags: FastifyPluginAsync = async (app) => { + configureFeatureFlags(app.rootPgPool) + + try { + const { available, missing } = await syncFeatureAvailability(app.rootPgPool) + for (const [key, isAvailable] of Object.entries(available)) { + if (!isAvailable) { + app.log.warn( + { feature: key }, + "feature is not configured on this server and stays off until its environment variables are set" + ) + } + } + if (missing.length > 0) { + app.log.error( + { features: missing }, + "feature flags in the registry have no row in app_public.feature_flags; have all migrations run?" + ) + } + } catch (e) { + // The server starts even when the database is not reachable yet (see + // retryOnInitFail); the flags then keep the availability recorded by the + // previous boot. + app.log.error( + { err: e }, + "could not record feature availability in the database" + ) + } +} + +export default fp(FeatureFlags) diff --git a/@app/server/src/middleware/installKeycloak.ts b/@app/server/src/middleware/installKeycloak.ts index 064a98f42..6198c7662 100644 --- a/@app/server/src/middleware/installKeycloak.ts +++ b/@app/server/src/middleware/installKeycloak.ts @@ -385,7 +385,7 @@ const InstallKeycloak: FastifyPluginAsync = async (app) => { return loginErrorRedirect(reply, "email_not_verified") } - // Registering the identity, the break-glass veto, the is_admin stamp and + // Registering the identity, the break-glass veto, the role stamps and // the session row are one decision: none of them may survive without the // others, so they share a single connection and a single transaction. const establishSession = async (): Promise< @@ -480,20 +480,30 @@ const InstallKeycloak: FastifyPluginAsync = async (app) => { return { error: "account_conflict" } } - // The registry is the source of truth for admin rights, so this both - // grants and revokes — but only when the token actually answered the - // roles question. isAdmin: null means the mapper is broken and the - // roles are unknown; stamping false here would demote every admin one - // login at a time. - if (profile.isAdmin === null) { + // The registry is the source of truth for admin and developer rights, + // so this both grants and revokes — but only when the token actually + // answered the roles question. null means the mapper is broken and + // the roles are unknown; stamping false here would demote every admin + // (and developer) one login at a time. + if (profile.isAdmin === null || profile.isDeveloper === null) { request.log.error( { sub: profile.sub, userId: user.id }, - "keycloak id token carried no usable realm_access.roles claim; leaving is_admin untouched — check the client's realm-roles mapper" + "keycloak id token carried no usable realm_access.roles claim; leaving is_admin and is_developer untouched — check the client's realm-roles mapper" ) } else { await client.query( - `update app_public.users set is_admin = $1 where id = $2`, - [profile.isAdmin, user.id] + `update app_public.users set is_admin = $1, is_developer = $2 where id = $3`, + [profile.isAdmin, profile.isDeveloper, user.id] + ) + } + + // Like admin rights, the registry owns first and last names, so they + // are refreshed on every login. Only a complete pair is written: half + // a name would prefill registrations worse than none. + if (profile.givenName && profile.familyName) { + await client.query( + `update app_public.users set first_name = $1, last_name = $2 where id = $3`, + [profile.givenName, profile.familyName, user.id] ) } diff --git a/@app/server/src/middleware/installPostGraphile.ts b/@app/server/src/middleware/installPostGraphile.ts index 594c0213b..35c377125 100644 --- a/@app/server/src/middleware/installPostGraphile.ts +++ b/@app/server/src/middleware/installPostGraphile.ts @@ -3,7 +3,6 @@ import { IncomingMessage } from "http" import { FastifyRedis } from "@fastify/redis" import PersistedOperationsPlugin from "@graphile/persisted-operations" import PgPubsub from "@graphile/pg-pubsub" -import PgSubscriptionsLds from "@graphile/subscriptions-lds" import PgSimplifyInflectorPlugin from "@graphile-contrib/pg-simplify-inflector" import { parse } from "cookie" import { FastifyInstance, FastifyPluginAsync, FastifyRequest } from "fastify" @@ -14,6 +13,7 @@ import { resolve } from "node:path" import { Pool, PoolClient } from "pg" import { enhanceHttpServerWithSubscriptions, + HttpRequestHandler, makePluginHook, Middleware, postgraphile, @@ -26,14 +26,17 @@ import { convertHandler } from "../app" import { EmailsPlugin, EventRegistrationPlugin, + FeatureFlagsPlugin, OrdersPlugin, PassportLoginPlugin, PasswordStrengthPlugin, + PaymentsPlugin, PrimaryKeyMutationsOnlyPlugin, RateLimitPlugin, RemoveOwnershipInfoForeignKeyConnections, RemoveQueryQueryPlugin, SubscriptionsPlugin, + TelegramSettingsPlugin, TranslatePlugin, UploadsPlugin, ValidateRichTextFields, @@ -45,6 +48,12 @@ import { RequestLogger } from "./installKeycloak" const PostGraphileUploadFieldPlugin = require("postgraphile-plugin-upload-field") +declare module "fastify" { + export interface FastifyInstance { + postgraphile: HttpRequestHandler + } +} + export interface OurGraphQLContext { pgClient: PoolClient sessionId: string | null @@ -127,8 +136,8 @@ export function getPostGraphileOptions({ // This is for PostGraphile server plugins: https://www.graphile.org/postgraphile/plugins/ pluginHook, - // This is so that PostGraphile installs the watch fixtures, it's also needed to enable live queries - ownerConnectionString: process.env.DATABASE_URL, + // This is so that PostGraphile installs the watch fixtures in watch mode + ownerConnectionString: isDev ? process.env.DATABASE_URL : undefined, // On production we still want to start even if the database isn't available. // On development, we want to deal nicely with issues in the database. @@ -140,8 +149,10 @@ export function getPostGraphileOptions({ websockets: ["v1"], websocketMiddlewares, - // Support for Postgraphile live queries @graphile/subscriptions-lds - live: !isJestTest, + // No live queries: Query fields are not exposed on the Subscription type. + // Clients stay fresh through the custom subscriptions in + // SubscriptionsPlugin or by refetching. + live: false, // We don't enable query batching since urql doesn't support it, and we don't really need it enableQueryBatching: false, @@ -242,6 +253,9 @@ export function getPostGraphileOptions({ // Wrap createRegistration mutation EventRegistrationPlugin, + // Clear the server's feature flag cache when a flag is switched + FeatureFlagsPlugin, + // Render email templates EmailsPlugin, @@ -255,6 +269,8 @@ export function getPostGraphileOptions({ // Adds support for our `postgraphile.tags.json5` file TagsFilePlugin, + TelegramSettingsPlugin, + // Translate text with Azure Translator API TranslatePlugin, @@ -276,6 +292,9 @@ export function getPostGraphileOptions({ // Calculate password strength with zxcvbn-ts on the server side PasswordStrengthPlugin, + // Stripe payments: the pay page query and Checkout + PaymentsPlugin, + // Remove connections based on ownership information from the schema. // For example: eventCategoriesByCreatedBy, eventCategoriesByUpdatedBy etc. RemoveOwnershipInfoForeignKeyConnections, @@ -286,11 +305,6 @@ export function getPostGraphileOptions({ // Adds realtime features to our GraphQL schema SubscriptionsPlugin, - // Support for live queries https://www.graphile.org/postgraphile/live-queries/ - // PgSubscriptionsLds pjolls for changes every 500ms, so in order for jest tests - // to cleanly exit we have to exclude this plugin when running tests. - !isJestTest ? PgSubscriptionsLds : null, - // Adds custom orders to our GraphQL schema OrdersPlugin, ].filter(Boolean), @@ -436,6 +450,8 @@ const Postgraphphile: FastifyPluginAsync = async (app) => { }) ) + app.decorate("postgraphile", middleware) + app.options( middleware.graphqlRoute, convertHandler(middleware.graphqlRouteHandler) diff --git a/@app/server/src/middleware/installTelegramPolling.ts b/@app/server/src/middleware/installTelegramPolling.ts new file mode 100644 index 000000000..6fa27b6e3 --- /dev/null +++ b/@app/server/src/middleware/installTelegramPolling.ts @@ -0,0 +1,38 @@ +import { FastifyPluginAsync } from "fastify" +import fp from "fastify-plugin" + +import { startTelegramPolling } from "../telegram" +import { telegramUpdateMode } from "../telegramWebhook" + +/** + * Receives Telegram bot updates by polling, for development and servers + * without a public HTTPS address. Webhook mode is an external route (see + * telegramWebhook.ts) and is not handled here. Never polls inside automated + * tests. The poller does nothing while `telegram_reminders` is off. + */ +const TelegramPolling: FastifyPluginAsync = async (app) => { + if ( + !process.env.TELEGRAM_BOT_TOKEN || + process.env.IN_TESTS === "1" || + process.env.JEST_WORKER_ID + ) { + return + } + const mode = telegramUpdateMode() + if (mode === "webhook") { + if (!process.env.TELEGRAM_WEBHOOK_SECRET) { + app.log.error( + "TELEGRAM_WEBHOOK_SECRET is required in Telegram webhook mode; the webhook is not registered" + ) + } + return + } + if (mode !== "polling") { + throw new Error("TELEGRAM_UPDATE_MODE must be polling or webhook") + } + const stop = startTelegramPolling(app.rootPgPool) + app.shutdownActions.push(stop) + app.addHook("onClose", stop) +} + +export default fp(TelegramPolling) diff --git a/@app/server/src/payments/checkout.ts b/@app/server/src/payments/checkout.ts new file mode 100644 index 000000000..74f2176fe --- /dev/null +++ b/@app/server/src/payments/checkout.ts @@ -0,0 +1,290 @@ +import { SERVICE_FEE_CENTS } from "@app/lib" +import { Pool } from "pg" + +import { getStripe, paymentsConfigured } from "../utils/stripe" + +import { + checkoutBlockedReason, + Language, + loadRegistrationForPayment, + PaymentError, + RegistrationForPayment, + translate, +} from "./registrationPayment" +import { INSTANCE_METADATA_KEY } from "./webhook" + +import type Stripe from "stripe" + +/** Console or a request logger. */ +type Logger = { + error(message: string): void +} + +/** Stripe Checkout locales for the client's languages. */ +const STRIPE_LOCALES: Record< + Language, + Stripe.Checkout.SessionCreateParams.Locale +> = { + fi: "fi", + en: "en", + se: "sv", +} + +/** The second line item, the same in every language. */ +export const SERVICE_FEE_LINE_ITEM_NAME = "Service fee / Palvelumaksu" + +interface PendingPayment { + id: string + stripe_checkout_session_id: string | null +} + +/** + * Expires the registration's other open Checkout Sessions so that only the + * newest one can be paid. A session that was completed meanwhile + * means the payment is being confirmed by the webhook: refuse instead of + * opening a second one (its row stays PENDING for the webhook). + * + * Runs outside any transaction. Rows are marked EXPIRED only while still + * PENDING, so a webhook that marked one PAID meanwhile wins. A pending row + * without a session id belongs to a concurrent or crashed checkout; expiring + * it makes a concurrent one give up its session (see createCheckoutSession). + */ +async function expirePendingSessions( + rootPgPool: Pool, + stripe: Stripe, + pending: PendingPayment[] +) { + for (const payment of pending) { + const sessionId = payment.stripe_checkout_session_id + if (sessionId) { + try { + await stripe.checkout.sessions.expire(sessionId) + } catch (e) { + // Only open sessions can be expired; find out what happened to it + const session = await stripe.checkout.sessions.retrieve(sessionId) + if (session.status === "complete") { + throw new PaymentError("ALREADY_PAID") + } + if (session.status !== "expired") { + throw e + } + } + } + await rootPgPool.query( + `update app_public.payments set status = 'EXPIRED' + where id = $1 and status = 'PENDING'`, + [payment.id] + ) + } +} + +/** + * The parameters of the Checkout Session for a registration. Card payments + * only: Apple Pay and Google Pay come with cards, and nothing else enabled in + * the Stripe dashboard (MobilePay) is offered. + */ +export function checkoutSessionParams({ + registration, + paymentId, + updateToken, + language, +}: { + registration: RegistrationForPayment + paymentId: string + updateToken: string + language: Language +}): Stripe.Checkout.SessionCreateParams { + const { ROOT_URL } = process.env + const payUrl = `${ROOT_URL}/${language}/pay/${encodeURIComponent(updateToken)}` + const metadata = { + registration_id: registration.id, + event_id: registration.event_id, + quota_id: registration.quota_id, + payment_id: paymentId, + event_slug: registration.event_slug, + [INSTANCE_METADATA_KEY]: ROOT_URL ?? "", + } + return { + mode: "payment", + allowed_payment_method_types: ["card"], + customer_email: registration.email ?? undefined, + client_reference_id: registration.id, + locale: STRIPE_LOCALES[language], + line_items: [ + { + quantity: 1, + price_data: { + currency: "eur", + unit_amount: registration.price_cents, + product_data: { + name: `${translate(registration.event_name, language)} – ${translate( + registration.quota_title, + language + )}`, + }, + }, + }, + { + quantity: 1, + price_data: { + currency: "eur", + unit_amount: SERVICE_FEE_CENTS, + product_data: { name: SERVICE_FEE_LINE_ITEM_NAME }, + }, + }, + ], + metadata, + payment_intent_data: { metadata }, + success_url: `${payUrl}?status=success`, + cancel_url: `${payUrl}?status=cancelled`, + } +} + +/** + * Starts Stripe Checkout for the registration behind `updateToken` and + * returns the URL to redirect to. + * + * No transaction or row lock is held while Stripe is called, so slow Stripe + * calls can't tie up database connections: + * 1. In a short transaction holding the registration's row lock: check that + * it can be paid, list its pending payments and insert a new PENDING + * payment row (its id goes into the session metadata). + * 2. Expire the older pending sessions, then create the session. + * 3. Store the session id on the row, but only while it is still PENDING. A + * second click meanwhile has expired it; then this session is expired + * again and the call fails, and the newer click's session is the one to + * pay. + * If anything fails, the new session is expired and the new row removed, so + * nobody can pay into a payment Ilmo doesn't know. + */ +export async function createCheckoutSession({ + rootPgPool, + updateToken, + language, + logger = console, +}: { + rootPgPool: Pool + updateToken: string + language: Language + logger?: Logger +}): Promise { + if (!paymentsConfigured()) { + throw new PaymentError("PAYMENTS_DISABLED") + } + const stripe = getStripe() + + const { registration, paymentId, pending } = await reservePayment( + rootPgPool, + updateToken + ) + + let session: Stripe.Checkout.Session | null = null + try { + await expirePendingSessions(rootPgPool, stripe, pending) + + session = await stripe.checkout.sessions.create( + checkoutSessionParams({ + registration, + paymentId, + updateToken, + language, + }), + { idempotencyKey: `checkout-session-${paymentId}` } + ) + if (!session.url) { + throw new Error(`Checkout Session ${session.id} has no URL`) + } + + const { rowCount } = await rootPgPool.query( + `update app_public.payments set stripe_checkout_session_id = $2 + where id = $1 and status = 'PENDING'`, + [paymentId, session.id] + ) + if (!rowCount) { + throw new Error( + `Payment ${paymentId} was superseded by a newer checkout before its session was stored` + ) + } + return session.url + } catch (e) { + if (session) { + const sessionId = session.id + await stripe.checkout.sessions.expire(sessionId).catch((expireError) => { + logger.error( + `Could not expire Checkout Session ${sessionId} after a failed checkout: ${expireError}` + ) + }) + } + await rootPgPool + .query( + `delete from app_public.payments + where id = $1 and status in ('PENDING', 'EXPIRED')`, + [paymentId] + ) + .catch((deleteError) => { + logger.error( + `Could not remove payment ${paymentId} after a failed checkout: ${deleteError}` + ) + }) + throw e + } +} + +/** + * Step 1 of createCheckoutSession: one short transaction holding the + * registration's row lock (the same lock order as the webhook and deletion). + */ +async function reservePayment( + rootPgPool: Pool, + updateToken: string +): Promise<{ + registration: RegistrationForPayment + paymentId: string + pending: PendingPayment[] +}> { + const client = await rootPgPool.connect() + try { + await client.query("begin") + + const registration = await loadRegistrationForPayment(client, updateToken, { + lock: true, + }) + const blockedReason = checkoutBlockedReason(registration) + if (blockedReason) { + throw new PaymentError(blockedReason) + } + + const { rows: pending } = await client.query( + `select id, stripe_checkout_session_id + from app_public.payments + where registration_id = $1 and method = 'STRIPE' and status = 'PENDING' + order by created_at`, + [registration!.id] + ) + + const { + rows: [payment], + } = await client.query<{ id: string }>( + `insert into app_public.payments( + registration_id, event_id, quota_id, event_name, quota_title, + method, status, ticket_amount_cents, service_fee_cents, currency + ) + select r.id, r.event_id, r.quota_id, e.name, q.title, + 'STRIPE', 'PENDING', $3, $2, 'eur' + from app_public.registrations as r + join app_public.events as e on e.id = r.event_id + join app_public.quotas as q on q.id = r.quota_id + where r.id = $1 + returning id`, + // The price the session is created with + [registration!.id, SERVICE_FEE_CENTS, registration!.price_cents] + ) + await client.query("commit") + return { registration: registration!, paymentId: payment.id, pending } + } catch (e) { + await client.query("rollback").catch(() => {}) + throw e + } finally { + client.release() + } +} diff --git a/@app/server/src/payments/registrationPayment.ts b/@app/server/src/payments/registrationPayment.ts new file mode 100644 index 000000000..31ffe0e27 --- /dev/null +++ b/@app/server/src/payments/registrationPayment.ts @@ -0,0 +1,221 @@ +import { Pool, PoolClient } from "pg" + +/** + * Why a registration can't be paid right now. Returned as the error `code` + * of `createCheckoutSession` and as `blockedReason` of + * `paymentByUpdateToken`, so the /pay page can map both to its states. + * Also declared as the `PaymentErrorCode` GraphQL enum. + */ +export const PAYMENT_ERROR_CODES = [ + "PAYMENTS_DISABLED", + "REGISTRATION_NOT_FOUND", + "PAYMENT_NOT_REQUIRED", + "ALREADY_PAID", + "IN_QUEUE", + "PAYMENT_NOT_OPEN", +] as const + +export type PaymentErrorCode = (typeof PAYMENT_ERROR_CODES)[number] + +const PAYMENT_ERROR_MESSAGES: Record = { + PAYMENTS_DISABLED: "Payments are not available.", + REGISTRATION_NOT_FOUND: "Registration matching token was not found.", + PAYMENT_NOT_REQUIRED: "This registration does not require payment.", + ALREADY_PAID: "This registration has already been paid.", + IN_QUEUE: "Registrations in the queue are not paid until they get a spot.", + PAYMENT_NOT_OPEN: "Payment opens when registration closes.", +} + +/** + * An error with a `PaymentErrorCode`. `handleErrors` exposes `code` as + * `extensions.exception.code`, like the database's own error codes. + */ +export class PaymentError extends Error { + code: PaymentErrorCode + + constructor(code: PaymentErrorCode) { + super(PAYMENT_ERROR_MESSAGES[code]) + this.name = "PaymentError" + this.code = code + } +} + +/** + * Any other failure while starting Checkout (Stripe, network, database). + * Its message is fixed so that no server or Stripe error text reaches the + * (usually anonymous) caller; the original is logged on the server. + */ +export class CheckoutFailedError extends Error { + code = "CHECKOUT_FAILED" as const + + constructor() { + super("Could not start the payment. Please try again later.") + this.name = "CheckoutFailedError" + } +} + +/** + * What paymentByUpdateToken returns instead of an unexpected (database) + * error, whose text must not reach the caller. + */ +export class PaymentLookupFailedError extends Error { + code = "PAYMENT_LOOKUP_FAILED" as const + + constructor() { + super("Could not load the payment. Please try again later.") + this.name = "PaymentLookupFailedError" + } +} + +export type RegistrationPaymentStatus = + | "NOT_REQUIRED" + | "UNPAID" + | "PAID" + | "PAID_MANUALLY" + +export type TranslatedField = Record + +/** A registration with everything needed to pay for it, by update token. */ +export interface RegistrationForPayment { + id: string + event_id: string + quota_id: string + first_name: string | null + last_name: string | null + email: string | null + /** The quota's current price: what Checkout charges. */ + price_cents: number + is_finished: boolean + event_name: TranslatedField + event_slug: string + event_start_time: Date + event_end_time: Date + registration_end_time: Date + quota_title: TranslatedField + queue_status: "IN_QUOTA" | "IN_OPEN_QUOTA" | "IN_QUEUE" | null + queue_position: number | null + payment_status: RegistrationPaymentStatus + signup_closed: boolean +} + +/** + * Looks a registration up by its update token, which already grants + * edit/delete rights over it, so it is also what the payment link uses. + * Runs on the root pool: registration secrets are private. With `lock`, the + * registration row is locked for update, which serializes Checkout creation + * (and deletion, and webhook handling) per registration. + */ +export async function loadRegistrationForPayment( + client: Pool | PoolClient, + updateToken: string, + { lock = false }: { lock?: boolean } = {} +): Promise { + const { + rows: [registration], + } = await client.query( + `select + r.id, + r.event_id, + r.quota_id, + r.first_name, + r.last_name, + r.email, + q.price_cents, + r.is_finished, + e.name as event_name, + e.slug as event_slug, + e.event_start_time, + e.event_end_time, + e.registration_end_time, + q.title as quota_title, + s.status as queue_status, + s.position as queue_position, + app_private.registration_payment_status(r) as payment_status, + now() > e.registration_end_time as signup_closed + from app_private.registration_secrets as rs + join app_public.registrations as r on r.id = rs.registration_id + join app_public.events as e on e.id = r.event_id + join app_public.quotas as q on q.id = r.quota_id + left join app_hidden.registrations_status_and_position as s on s.id = r.id + where rs.update_token = $1 + ${lock ? "for update of r" : ""}`, + [updateToken] + ) + return registration ?? null +} + +/** + * Why Checkout can't start for this registration right now, or null when it + * can. The order matters: it is the order the /pay page shows states in. + */ +export function checkoutBlockedReason( + registration: RegistrationForPayment | null +): PaymentErrorCode | null { + if (!registration || !registration.is_finished) { + return "REGISTRATION_NOT_FOUND" + } + switch (registration.payment_status) { + case "NOT_REQUIRED": + return "PAYMENT_NOT_REQUIRED" + case "PAID": + case "PAID_MANUALLY": + return "ALREADY_PAID" + } + // Queued registrations never pay; they get the link when they get a spot + if ( + registration.queue_status !== "IN_QUOTA" && + registration.queue_status !== "IN_OPEN_QUOTA" + ) { + return "IN_QUEUE" + } + // Payment opens when registration closes, and closes again while + // registration is reopened + if (!registration.signup_closed) { + return "PAYMENT_NOT_OPEN" + } + return null +} + +/** The paid payment of a registration, for the /pay page. */ +export interface PaidPayment { + method: "STRIPE" | "MANUAL" + ticket_amount_cents: number + service_fee_cents: number + paid_at: Date | null +} + +export async function loadPaidPayment( + client: Pool | PoolClient, + registrationId: string +): Promise { + const { + rows: [payment], + } = await client.query( + `select method, ticket_amount_cents, service_fee_cents, paid_at + from app_public.payments + where registration_id = $1 and status = 'PAID'`, + [registrationId] + ) + return payment ?? null +} + +/** Languages of the client, as in @app/client/i18n.js. */ +export const LANGUAGES = ["fi", "en", "se"] as const +export type Language = (typeof LANGUAGES)[number] + +export function normalizeLanguage( + language: string | null | undefined +): Language { + return (LANGUAGES as readonly string[]).includes(language ?? "") + ? (language as Language) + : "fi" +} + +/** + * Translated fields are stored in Finnish and English only; Swedish pages + * show English. + */ +export function translate(field: TranslatedField, language: Language): string { + const key = language === "fi" ? "fi" : "en" + return field?.[key] || field?.fi || field?.en || "" +} diff --git a/@app/server/src/payments/webhook.ts b/@app/server/src/payments/webhook.ts new file mode 100644 index 000000000..283e6b44e --- /dev/null +++ b/@app/server/src/payments/webhook.ts @@ -0,0 +1,256 @@ +import { PoolClient } from "pg" + +import type Stripe from "stripe" + +/** Console or a Fastify request logger. */ +type Logger = { + error(message: string): void + warn(message: string): void + info(message: string): void +} + +export type WebhookOutcome = "processed" | "duplicate" | "ignored" + +/** The Stripe events Ilmo handles; configure exactly these in the dashboard. */ +export const HANDLED_STRIPE_EVENTS = [ + "checkout.session.completed", + "checkout.session.expired", +] as const + +interface PaymentRow { + id: string + registration_id: string | null + status: "PENDING" | "PAID" | "EXPIRED" + ticket_amount_cents: number + service_fee_cents: number + currency: string +} + +const PAYMENT_COLUMNS = + "id, registration_id, status, ticket_amount_cents, service_fee_cents, currency" + +/** + * Metadata key naming the Ilmo instance (its ROOT_URL) that created a + * Checkout Session. Several instances (production, staging, developers) can + * share one Stripe account, so the log of an unknown paid session says + * whether this instance created it. + */ +export const INSTANCE_METADATA_KEY = "ilmo_url" + +function idOf(value: string | { id: string } | null | undefined) { + if (!value) return null + return typeof value === "string" ? value : value.id +} + +async function addJob( + client: PoolClient, + identifier: string, + payload: Record +) { + await client.query("select graphile_worker.add_job($1, $2::json)", [ + identifier, + JSON.stringify(payload), + ]) +} + +/** + * Finds the payment row of a Checkout Session: by session id, or else by the + * payment id in the session's metadata (the row is created before the + * session, so it exists even if storing the session id failed). + */ +async function findSessionPayment( + client: PoolClient, + session: Stripe.Checkout.Session +): Promise { + const { + rows: [bySession], + } = await client.query( + `select ${PAYMENT_COLUMNS} + from app_public.payments where stripe_checkout_session_id = $1`, + [session.id] + ) + if (bySession) return bySession + + const paymentId = session.metadata?.payment_id + if (!paymentId || !/^[0-9a-f-]{36}$/i.test(paymentId)) return null + const { + rows: [byMetadata], + } = await client.query( + `select ${PAYMENT_COLUMNS} + from app_public.payments + where id = $1 and method = 'STRIPE' and stripe_checkout_session_id is null`, + [paymentId] + ) + return byMetadata ?? null +} + +/** + * A paid session without a payment row. Ilmo never refunds, so this is only + * logged: an organizer can refund it by hand in Stripe. + */ +function handleUnknownPaidSession( + session: Stripe.Checkout.Session, + logger: Logger +): WebhookOutcome { + const ours = + !!process.env.ROOT_URL && + session.metadata?.[INSTANCE_METADATA_KEY] === process.env.ROOT_URL + logger.error( + `Stripe Checkout Session ${session.id} (payment intent ${idOf( + session.payment_intent + )}) was paid but has no payment row; ${ + ours ? "it was created by this Ilmo" : "it was not created by this Ilmo" + } (metadata: ${JSON.stringify(session.metadata)}). Refund it in Stripe if needed.` + ) + return "ignored" +} + +/** + * A Checkout Session was paid. The registration becomes paid only here, + * never from the success redirect. + * + * Locks the registration before the payment (the same order as Checkout + * creation and deletion) and then records the payment as PAID. Ilmo never + * refunds; a payment that can't be applied to its registration is kept as a + * PAID row without a registration and logged, and the organizers' payment + * summary counts it so that they can refund it by hand in Stripe: + * - the registration is gone (deleted while Checkout was open); + * - it already has another PAID payment (a second session, or a manual + * payment). One registration can have only one PAID row; the Stripe + * metadata of the detached row still names the registration; + * - the session's amount or currency differs from the payment row. + * Otherwise the payment received email is sent. + * + * A paid session with no payment row at all is only logged (see + * handleUnknownPaidSession). + */ +async function handleSessionCompleted( + client: PoolClient, + session: Stripe.Checkout.Session, + logger: Logger +): Promise { + if (session.payment_status !== "paid") { + return "ignored" + } + const found = await findSessionPayment(client, session) + if (!found) { + return handleUnknownPaidSession(session, logger) + } + + if (found.registration_id) { + await client.query( + "select 1 from app_public.registrations where id = $1 for update", + [found.registration_id] + ) + } + const { + rows: [payment], + } = await client.query( + `select ${PAYMENT_COLUMNS} + from app_public.payments where id = $1 for update`, + [found.id] + ) + if (payment.status === "PAID") { + // Already handled (for example through the metadata fallback) + return "ignored" + } + + // Ilmo created the session from this row, so anything else means the + // session is not what it should be: don't apply it to the registration. + const expectedCents = payment.ticket_amount_cents + payment.service_fee_cents + const chargedCents = session.amount_total + const chargedCurrency = session.currency + const amountMismatch = + chargedCents !== expectedCents || + chargedCurrency?.toLowerCase() !== payment.currency.toLowerCase() + + let duplicate = false + if (payment.registration_id && !amountMismatch) { + const { rows: otherPaid } = await client.query( + `select 1 from app_public.payments + where registration_id = $1 and status = 'PAID' and id <> $2`, + [payment.registration_id, payment.id] + ) + duplicate = otherPaid.length > 0 + } + + await client.query( + `update app_public.payments + set + status = 'PAID', + paid_at = now(), + stripe_checkout_session_id = $2, + stripe_payment_intent_id = $3, + registration_id = case when $4::boolean then null else registration_id end + where id = $1`, + [ + payment.id, + session.id, + idOf(session.payment_intent), + duplicate || amountMismatch, + ] + ) + + const refundHint = + "kept without a registration; refund it in Stripe if needed" + if (amountMismatch) { + logger.error( + `Checkout Session ${session.id} charged ${chargedCents} ${chargedCurrency}, but payment ${payment.id} expects ${expectedCents} ${payment.currency}; ${refundHint}` + ) + } else if (duplicate) { + logger.error( + `Payment ${payment.id} is a second payment for registration ${payment.registration_id}; ${refundHint}` + ) + } else if (!payment.registration_id) { + logger.error( + `Payment ${payment.id} completed for a deleted registration; ${refundHint}` + ) + } else { + await addJob(client, "payment__send_received_email", { + paymentId: payment.id, + }) + } + return "processed" +} + +async function handleSessionExpired( + client: PoolClient, + session: Stripe.Checkout.Session +): Promise { + const { rowCount } = await client.query( + `update app_public.payments set status = 'EXPIRED' + where stripe_checkout_session_id = $1 and status = 'PENDING'`, + [session.id] + ) + return rowCount ? "processed" : "ignored" +} + +/** + * Applies a verified Stripe event. The caller runs this in a transaction and + * commits it: the event id is recorded first, so a redelivered event is + * skipped, and a failure rolls the record back so that Stripe's retry is + * processed again. + */ +export async function handleStripeEvent( + client: PoolClient, + event: Stripe.Event, + logger: Logger = console +): Promise { + const { rowCount } = await client.query( + `insert into app_private.stripe_events(id, type) values ($1, $2) + on conflict (id) do nothing`, + [event.id, event.type] + ) + if (!rowCount) { + return "duplicate" + } + + switch (event.type) { + case "checkout.session.completed": + return handleSessionCompleted(client, event.data.object, logger) + case "checkout.session.expired": + return handleSessionExpired(client, event.data.object) + default: + return "ignored" + } +} diff --git a/@app/server/src/plugins/EmailsPlugin.ts b/@app/server/src/plugins/EmailsPlugin.ts index bf7910ce2..db48dae98 100644 --- a/@app/server/src/plugins/EmailsPlugin.ts +++ b/@app/server/src/plugins/EmailsPlugin.ts @@ -5,10 +5,33 @@ import path from "node:path" import { OurGraphQLContext } from "../middleware/installPostGraphile" import { loadTemplate } from "../utils/emailUtils" +import { isFeatureEnabledForSession } from "../utils/featureFlags" import { ERROR_MESSAGE_OVERRIDES } from "../utils/handleErrors" const EMAIL_SEND_TEMPLATE_ALLOWLIST = ["event_registration.mjml.njk"] +/** Emails that exist only for payments; listed only while payments are on. */ +const PAYMENT_TEMPLATE_PREFIX = "payment_" + +/** + * Example payment variables for the email previews. Amounts are cents, as in + * the worker. Used only while payments are on, so that with payments off + * every preview renders exactly as before. + */ +const PREVIEW_PAYMENT_VARIABLES = { + closed: false, + firstName: "Teppo", + isQueued: false, + paidAt: "1.1.2021 12:00", + payLink: "pay/12345", + paymentMethod: "STRIPE", + price: 1800, + registrationEndDate: "1.1.2021", + registrationEndTime: "12:00", + serviceFee: 25, + total: 1825, +} + const EmailsPlugin = makeExtendSchemaPlugin(() => ({ typeDefs: gql` """ @@ -34,6 +57,32 @@ const EmailsPlugin = makeExtendSchemaPlugin(() => ({ token: String url: String verifyLink: String + """ + Ticket price in cents (payment emails). + """ + price: Int + """ + Service fee in cents (payment emails). + """ + serviceFee: Int + """ + Ticket price plus service fee, in cents (payment emails). + """ + total: Int + paymentMethod: PaymentMethod + isQueued: Boolean + """ + The payment link relative to the language root, e.g. \`pay/\`. + """ + payLink: String + paidAt: String + registrationEndDate: String + registrationEndTime: String + firstName: String + """ + The reminder is the email sent when registration closes. + """ + closed: Boolean } """ @@ -99,6 +148,8 @@ const EmailsPlugin = makeExtendSchemaPlugin(() => ({ const text = html2text.fromString(html2textableHtml, { wordwrap: 120, tags: { img: { format: "skip" } }, + // Amount tables of the payment emails (payment_macros.njk) + tables: [".amounts"], }) // All templates end in .mjml.njk, remove the file extension const name = template.slice(0, -9).replace(/_/g, " ") @@ -131,7 +182,7 @@ const EmailsPlugin = makeExtendSchemaPlugin(() => ({ async renderEmailTemplates( _mutation, _args, - _context: OurGraphQLContext, + context: OurGraphQLContext, _resolveInfo ) { try { @@ -140,7 +191,18 @@ const EmailsPlugin = makeExtendSchemaPlugin(() => ({ "../../../worker/templates/" ) - const templateFiles = fs.readdirSync(templatesFolder) + const withPayments = await isFeatureEnabledForSession( + "payments", + context.pgClient + ) + // Only emails: the folder also holds partials (payment_macros.njk) + const templateFiles = fs + .readdirSync(templatesFolder) + .filter((filename) => filename.endsWith(".mjml.njk")) + .filter( + (filename) => + withPayments || !filename.startsWith(PAYMENT_TEMPLATE_PREFIX) + ) const ret = templateFiles.map(async (filename) => { // Dummy variables for mjml templates const variables = { @@ -158,14 +220,30 @@ const EmailsPlugin = makeExtendSchemaPlugin(() => ({ token: "12345", url: process.env.ROOT_URL, verifyLink: "", + ...(withPayments ? PREVIEW_PAYMENT_VARIABLES : {}), } const templateFn = await loadTemplate(filename) - const html = await templateFn(variables) + const html = await templateFn( + filename === "registration_reminder.mjml.njk" + ? { + ...variables, + language: "en", + eventName: variables.eventName.en, + openingTime: "1 January 2021 at 12:00", + eventUrl: new URL( + `/en/event/${variables.eventSlug}`, + process.env.ROOT_URL + ).href, + } + : variables + ) const html2textableHtml = html.replace(/(<\/?)div/g, "$1p") const text = html2text .fromString(html2textableHtml, { wordwrap: 120, tags: { img: { format: "skip" } }, + // Amount tables of the payment emails (payment_macros.njk) + tables: [".amounts"], }) .replace(/\n\s+\n/g, "\n\n") diff --git a/@app/server/src/plugins/EventRegistrationPlugin.ts b/@app/server/src/plugins/EventRegistrationPlugin.ts index 8fb42023d..23a53f37e 100644 --- a/@app/server/src/plugins/EventRegistrationPlugin.ts +++ b/@app/server/src/plugins/EventRegistrationPlugin.ts @@ -2,6 +2,8 @@ import { makeWrapResolversPlugin } from "graphile-utils" import { OurGraphQLContext } from "../middleware/installPostGraphile" +import { constructRateLimitKey, rateLimitRequester } from "./RateLimitPlugin" + const EventRegistrationPlugin = makeWrapResolversPlugin({ Mutation: { createRegistration: { @@ -22,8 +24,16 @@ const EventRegistrationPlugin = makeWrapResolversPlugin({ const result = await resolve() const workerUtils = context.workerUtils - const ipAddress = context.ipAddress const { eventId, quotaId } = args.input + const requester = await rateLimitRequester( + pgClient, + context.ipAddress + ) + const key = constructRateLimitKey( + "claimRegistrationToken", + `${eventId}:${quotaId}`, + requester + ) // After successfull registration delete the rate limit key from redis. // Awaiting here ensures the job row is committed before this resolver @@ -32,9 +42,7 @@ const EventRegistrationPlugin = makeWrapResolversPlugin({ // unawaited fire-and-forget pattern raced the test queries that // immediately read the queue. await workerUtils.addJob("registration__delete_rate_limit_key", { - eventId, - quotaId, - ipAddress, + key, }) // Return the result of our original mutation diff --git a/@app/server/src/plugins/FeatureFlagsPlugin.ts b/@app/server/src/plugins/FeatureFlagsPlugin.ts new file mode 100644 index 000000000..5cc7a7ca8 --- /dev/null +++ b/@app/server/src/plugins/FeatureFlagsPlugin.ts @@ -0,0 +1,27 @@ +import { makeWrapResolversPlugin } from "graphile-utils" + +import { invalidateFeatureFlags } from "../utils/featureFlags" + +/** + * Clears the server's feature flag cache when a flag is switched through this + * server, so that server-side gates follow the switch without waiting for the + * cache to expire. + * + * The resolver returns shortly before PostGraphile commits the request's + * transaction. A flag read by another request in that gap can still cache the + * old state, but for no longer than the cache TTL, which is the same bound as + * for a switch made outside this server. + */ +const FeatureFlagsPlugin = makeWrapResolversPlugin({ + Mutation: { + setFeatureFlag: { + async resolve(resolve: any, _source, _args, _context, _resolveInfo) { + const result = await resolve() + invalidateFeatureFlags() + return result + }, + }, + }, +}) + +export default FeatureFlagsPlugin diff --git a/@app/server/src/plugins/PaymentsPlugin.ts b/@app/server/src/plugins/PaymentsPlugin.ts new file mode 100644 index 000000000..d6c94e8ff --- /dev/null +++ b/@app/server/src/plugins/PaymentsPlugin.ts @@ -0,0 +1,256 @@ +import { SERVICE_FEE_CENTS, totalChargeCents } from "@app/lib" +import { gql, makeExtendSchemaPlugin } from "graphile-utils" +import { createHash } from "node:crypto" +import { Pool } from "pg" + +import { createCheckoutSession } from "../payments/checkout" +import { + checkoutBlockedReason, + CheckoutFailedError, + loadPaidPayment, + loadRegistrationForPayment, + normalizeLanguage, + PaymentError, + PaymentLookupFailedError, +} from "../payments/registrationPayment" +import { isFeatureEnabledForSession } from "../utils/featureFlags" +import { paymentsConfigured } from "../utils/stripe" + +import { + constructRateLimitKey, + RateLimitException, + rateLimitRequester, +} from "./RateLimitPlugin" + +import type { OurGraphQLContext } from "../middleware/installPostGraphile" + +/** + * Checkout Sessions one requester (signed-in user, else IP address) may start + * for one registration within CHECKOUT_RATE_LIMIT_MINUTES. Every attempt + * counts, also failed ones, so that a script can't create Stripe sessions in + * a loop. Keyed per registration so that participants behind one shared IP + * address don't limit each other. + */ +export const CHECKOUT_RATE_LIMIT = 10 +const CHECKOUT_RATE_LIMIT_MINUTES = 30 + +async function checkCheckoutRateLimit( + context: OurGraphQLContext, + updateToken: string +) { + const { pgClient, ipAddress, redisClient } = context + const requester = await rateLimitRequester(pgClient, ipAddress) + // The update token is a secret: only a digest of it goes into Redis + const registrationKey = createHash("sha256") + .update(updateToken) + .digest("hex") + .slice(0, 32) + const key = constructRateLimitKey( + "createCheckoutSession", + registrationKey, + requester + ) + const attempts = await redisClient.incr(key) + if (attempts === 1) { + await redisClient.expire(key, CHECKOUT_RATE_LIMIT_MINUTES * 60) + } + if (attempts > CHECKOUT_RATE_LIMIT) { + throw new RateLimitException( + `Too many requests. You have been rate-limited for ${CHECKOUT_RATE_LIMIT_MINUTES} minutes.` + ) + } +} + +/** + * The RegistrationPayment of paymentByUpdateToken, or null. While payments + * are off the page still shows a payment that exists, but Pay is blocked + * with PAYMENTS_DISABLED. + */ +async function loadPaymentByUpdateToken( + rootPgPool: Pool, + updateToken: string, + paymentsOn: boolean +) { + const registration = await loadRegistrationForPayment(rootPgPool, updateToken) + if (!registration || !registration.is_finished) { + return null + } + const paid = await loadPaidPayment(rootPgPool, registration.id) + const priceCents = registration.price_cents + const required = registration.payment_status !== "NOT_REQUIRED" + return { + eventId: registration.event_id, + eventSlug: registration.event_slug, + eventName: registration.event_name, + eventStartTime: registration.event_start_time.toISOString(), + eventEndTime: registration.event_end_time.toISOString(), + registrationEndTime: registration.registration_end_time.toISOString(), + quotaTitle: registration.quota_title, + firstName: registration.first_name, + lastName: registration.last_name, + queueStatus: registration.queue_status, + queuePosition: registration.queue_position, + status: registration.payment_status, + priceCents: required ? priceCents : 0, + serviceFeeCents: required ? SERVICE_FEE_CENTS : 0, + totalCents: required ? totalChargeCents(priceCents) : 0, + paidManually: paid?.method === "MANUAL", + paidTotalCents: paid + ? paid.ticket_amount_cents + paid.service_fee_cents + : null, + paidAt: paid?.paid_at?.toISOString() ?? null, + blockedReason: paymentsOn + ? checkoutBlockedReason(registration) + : "PAYMENTS_DISABLED", + } +} + +const PaymentsPlugin = makeExtendSchemaPlugin(() => ({ + typeDefs: gql` + """ + Why a registration can't be paid right now. The error code of + createCheckoutSession, and blockedReason of paymentByUpdateToken. + """ + enum PaymentErrorCode { + "Payments are switched off, or Stripe is not configured on this server." + PAYMENTS_DISABLED + "No finished registration has this update token." + REGISTRATION_NOT_FOUND + "The quota is free, or the event has no payments." + PAYMENT_NOT_REQUIRED + "The registration has been paid (by card or marked paid by hand)." + ALREADY_PAID + "The registration is in the queue; it is paid once it gets a spot." + IN_QUEUE + "Payment opens when registration closes; registration is open (again)." + PAYMENT_NOT_OPEN + } + + type CreateCheckoutSessionPayload { + "The Stripe Checkout page to redirect to." + url: String! + } + + """ + What the /pay page shows for a registration. Amounts are in cents. + """ + type RegistrationPayment { + eventId: UUID! + eventSlug: String! + eventName: JSON! + eventStartTime: Datetime! + eventEndTime: Datetime! + registrationEndTime: Datetime! + quotaTitle: JSON! + firstName: String + lastName: String + "Queue status; null while the registration is not yet placed." + queueStatus: RegistrationStatus + queuePosition: Int + status: RegistrationPaymentStatus! + "The quota's current ticket price, which Pay charges. 0 when free." + priceCents: Int! + "The service fee charged on top of a paid ticket. 0 when free." + serviceFeeCents: Int! + totalCents: Int! + "True when the paid payment was recorded by an organizer by hand." + paidManually: Boolean! + "What was paid, fee included (paid registrations only)." + paidTotalCents: Int + paidAt: Datetime + "Why Pay is not available right now; null when it is." + blockedReason: PaymentErrorCode + } + + extend type Query { + """ + The payment state of the registration with this update token, for the + /pay page. Null when Stripe is not configured on this server or the + token is unknown. Answers while the payments feature is off too, so + that a payment already made stays visible; Pay is then blocked. + """ + paymentByUpdateToken(updateToken: String!): RegistrationPayment + } + + extend type Mutation { + """ + Starts Stripe Checkout for the registration with this update token and + returns the Checkout URL. Expires the registration's other open + Checkout Sessions. Fails with a PaymentErrorCode as the error code when + the registration can't be paid now. language (fi, en or se, default + fi) sets the Checkout language and the /pay page Stripe returns to. + """ + createCheckoutSession( + updateToken: String! + language: String + ): CreateCheckoutSessionPayload + } + `, + resolvers: { + Query: { + async paymentByUpdateToken( + _query, + args: { updateToken: string }, + context: OurGraphQLContext + ) { + if (!paymentsConfigured()) { + return null + } + const { rootPgPool } = context + try { + const paymentsOn = await isFeatureEnabledForSession( + "payments", + context.pgClient + ) + return await loadPaymentByUpdateToken( + rootPgPool, + args.updateToken, + paymentsOn + ) + } catch (e) { + // Database errors can carry SQL details: log them, return a code + context.logger.error( + `paymentByUpdateToken failed: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}` + ) + throw new PaymentLookupFailedError() + } + }, + }, + Mutation: { + async createCheckoutSession( + _mutation, + args: { updateToken: string; language?: string | null }, + context: OurGraphQLContext + ) { + if ( + !paymentsConfigured() || + !(await isFeatureEnabledForSession("payments", context.pgClient)) + ) { + throw new PaymentError("PAYMENTS_DISABLED") + } + await checkCheckoutRateLimit(context, args.updateToken) + try { + const url = await createCheckoutSession({ + rootPgPool: context.rootPgPool, + updateToken: args.updateToken, + language: normalizeLanguage(args.language), + logger: context.logger, + }) + return { url } + } catch (e) { + if (e instanceof PaymentError) { + throw e + } + // Stripe and database errors can carry details (key prefixes, + // SQL) that must not reach the caller: log them, return a code + context.logger.error( + `createCheckoutSession failed: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}` + ) + throw new CheckoutFailedError() + } + }, + }, + }, +})) + +export default PaymentsPlugin diff --git a/@app/server/src/plugins/RateLimitPlugin.ts b/@app/server/src/plugins/RateLimitPlugin.ts index 70bf7868e..f3cef0462 100644 --- a/@app/server/src/plugins/RateLimitPlugin.ts +++ b/@app/server/src/plugins/RateLimitPlugin.ts @@ -1,4 +1,5 @@ import { makeWrapResolversPlugin } from "graphile-utils" +import { PoolClient } from "pg" import { OurGraphQLContext } from "../middleware/installPostGraphile" @@ -9,15 +10,33 @@ if (!process.env.NODE_ENV) { // 30 minutes timeout const RATE_LIMIT_TIMEOUT = 30 -function constructRateLimitKey( +/** + * Signed-in users are limited per user rather than per session: with Keycloak + * SSO a fresh session costs a single redirect, so a per-session limit could be + * reset at will. current_user_id() also proves the session still exists; a + * stale cookie falls back to the IP address like an anonymous request. + */ +export async function rateLimitRequester( + pgClient: PoolClient, + ipAddress: string +) { + const { + rows: [row], + } = await pgClient.query<{ user_id: string | null }>( + "select app_public.current_user_id() as user_id" + ) + return row?.user_id ? `user:${row.user_id}` : `ip:${ipAddress}` +} + +export function constructRateLimitKey( fieldName: string, id: string, - ipAddress: string + requester: string ) { - return `rate-limit:${fieldName}:${id}:${ipAddress}` + return `rate-limit:${fieldName}:${id}:${requester}` } -class RateLimitException extends Error { +export class RateLimitException extends Error { code: string constructor(message: string) { super(message) @@ -49,7 +68,8 @@ function rateLimitResolver( // to set a rate limit key to redis const result = await resolve() - const key = constructRateLimitKey(fieldName, rateLimitId, ipAddress) + const requester = await rateLimitRequester(pgClient, ipAddress) + const key = constructRateLimitKey(fieldName, rateLimitId, requester) const current = Number(await redisClient.get(key)) if (current >= limit) { diff --git a/@app/server/src/plugins/SubscriptionsPlugin.ts b/@app/server/src/plugins/SubscriptionsPlugin.ts index bacd11dd7..2fdc670d9 100644 --- a/@app/server/src/plugins/SubscriptionsPlugin.ts +++ b/@app/server/src/plugins/SubscriptionsPlugin.ts @@ -8,6 +8,7 @@ import { } from "graphile-utils" import { OurGraphQLContext } from "../middleware/installPostGraphile" +import { RelayPubSub, throttledTopic } from "../utils/throttleTopic" // graphile-utils doesn't export this yet import type { GraphQLResolveInfo } from "graphql" @@ -46,22 +47,33 @@ const currentUserTopicFromContext = async ( throw new Error("You're not logged in") } -const eventRegistrationsTopicFromContext = async ( - args: { eventId: string }, - context: { [key: string]: any }, - _resolveInfo: GraphQLResolveInfo -) => { - const { - rows: [event], - } = await context.pgClient.query( - "select id from app_public.events where id = $1", - [args.eventId] - ) - if (event) { - return `graphql:eventRegistrations:${event.id}` +// How often a single event's eventRegistrations subscribers are notified at +// most. Each notification makes every subscriber query the database, so a +// burst of registrations is coalesced into one notification per interval. +const EVENT_REGISTRATIONS_THROTTLE_INTERVAL = 1000 + +const makeEventRegistrationsTopicFromContext = + (pubsub: RelayPubSub | undefined) => + async ( + args: { eventId: string }, + context: { [key: string]: any }, + _resolveInfo: GraphQLResolveInfo + ) => { + const { + rows: [event], + } = await context.pgClient.query( + "select id from app_public.events where id = $1", + [args.eventId] + ) + if (event) { + const topic = `graphql:eventRegistrations:${event.id}` + // pubsub is not available in tests and one off scripts + return pubsub + ? throttledTopic(pubsub, topic, EVENT_REGISTRATIONS_THROTTLE_INTERVAL) + : topic + } + throw new Error("Invalid event ID.") } - throw new Error("Invalid event ID.") -} /* * This plugin adds a number of custom subscriptions to our schema. By making @@ -116,7 +128,7 @@ const SubscriptionsPlugin = makeExtendSchemaPlugin((build, { pubsub }) => { """Triggered when new event registrations are created or updated. Each event has its own subscription topic.""" eventRegistrations(eventId: UUID!): EventRegistrationsSubscriptionPayload! @pgSubscription(topic: ${embed( - eventRegistrationsTopicFromContext + makeEventRegistrationsTopicFromContext(pubsub) )}) """Returns the server time every second.""" diff --git a/@app/server/src/plugins/TelegramSettingsPlugin.ts b/@app/server/src/plugins/TelegramSettingsPlugin.ts new file mode 100644 index 000000000..34f6421a5 --- /dev/null +++ b/@app/server/src/plugins/TelegramSettingsPlugin.ts @@ -0,0 +1,19 @@ +import { makeExtendSchemaPlugin } from "graphile-utils" +import { gql } from "postgraphile" + +// Read runtime configuration: container builds do not have the bot secret. +export default makeExtendSchemaPlugin(() => ({ + typeDefs: gql` + extend type Query { + telegramBotUsername: String + } + `, + resolvers: { + Query: { + telegramBotUsername: () => + process.env.TELEGRAM_BOT_TOKEN + ? process.env.TELEGRAM_BOT_USERNAME || "IlmoReminderBot" + : null, + }, + }, +})) diff --git a/@app/server/src/plugins/index.ts b/@app/server/src/plugins/index.ts index 238743cb9..ba1f06d52 100644 --- a/@app/server/src/plugins/index.ts +++ b/@app/server/src/plugins/index.ts @@ -1,13 +1,16 @@ import EmailsPlugin from "./EmailsPlugin" import EventRegistrationPlugin from "./EventRegistrationPlugin" +import FeatureFlagsPlugin from "./FeatureFlagsPlugin" import OrdersPlugin from "./OrdersPlugin" import PassportLoginPlugin from "./PassportLoginPlugin" import PasswordStrengthPlugin from "./PasswordStrengthPlugin" +import PaymentsPlugin from "./PaymentsPlugin" import PrimaryKeyMutationsOnlyPlugin from "./PrimaryKeyMutationsOnlyPlugin" import RateLimitPlugin from "./RateLimitPlugin" import RemoveOwnershipInfoForeignKeyConnections from "./RemoveOwnershipInfoForeignKeyConnections" import RemoveQueryQueryPlugin from "./RemoveQueryQueryPlugin" import SubscriptionsPlugin from "./SubscriptionsPlugin" +import TelegramSettingsPlugin from "./TelegramSettingsPlugin" import TranslatePlugin from "./TranslatePlugin" import UploadsPlugin from "./UploadsPlugin" import ValidateRichTextFields from "./ValidateRichTextFields" @@ -15,14 +18,17 @@ import ValidateRichTextFields from "./ValidateRichTextFields" export { EmailsPlugin, EventRegistrationPlugin, + FeatureFlagsPlugin, OrdersPlugin, PassportLoginPlugin, PasswordStrengthPlugin, + PaymentsPlugin, PrimaryKeyMutationsOnlyPlugin, RateLimitPlugin, RemoveOwnershipInfoForeignKeyConnections, RemoveQueryQueryPlugin, SubscriptionsPlugin, + TelegramSettingsPlugin, TranslatePlugin, UploadsPlugin, ValidateRichTextFields, diff --git a/@app/server/src/stripeWebhook.ts b/@app/server/src/stripeWebhook.ts new file mode 100644 index 000000000..c4e21e403 --- /dev/null +++ b/@app/server/src/stripeWebhook.ts @@ -0,0 +1,82 @@ +import { handleStripeEvent } from "./payments/webhook" +import { getStripe, paymentsConfigured } from "./utils/stripe" + +import type { ExternalRouteModule } from "./externalRoutes" +import type { FastifyPluginAsync } from "fastify" +import type Stripe from "stripe" + +export const STRIPE_WEBHOOK_PATH = "/api/stripe/webhook" + +/** + * POST /api/stripe/webhook, registered only while Stripe is configured. + * + * Deliberately not wrapped in fastify-plugin: the raw-body content type + * parsers below must stay inside this plugin's encapsulation context, or + * they would replace JSON parsing for /graphql too. Stripe signs the exact + * bytes it sends, so the body reaches `constructEvent` as a Buffer. + * + * Responses: 400 for a missing or bad signature, 500 when the database + * fails (Stripe retries), and 200 for every verified event, including ones + * that were already handled or that Ilmo ignores. + */ +const StripeWebhook: FastifyPluginAsync = async (app) => { + app.removeAllContentTypeParsers() + app.addContentTypeParser( + "*", + { parseAs: "buffer" }, + (_request, body, done) => { + done(null, body) + } + ) + + app.post(STRIPE_WEBHOOK_PATH, async (request, reply) => { + const signature = request.headers["stripe-signature"] + if (typeof signature !== "string" || !Buffer.isBuffer(request.body)) { + return reply.code(400).send({ error: "Missing Stripe signature" }) + } + + let event: Stripe.Event + try { + event = getStripe().webhooks.constructEvent( + request.body, + signature, + process.env.STRIPE_WEBHOOK_SECRET! + ) + } catch (e) { + request.log.warn(`Rejected Stripe webhook: ${e}`) + return reply.code(400).send({ error: "Invalid Stripe signature" }) + } + + const client = await app.rootPgPool.connect() + try { + await client.query("begin") + const outcome = await handleStripeEvent(client, event, request.log) + await client.query("commit") + request.log.info(`Stripe event ${event.id} (${event.type}): ${outcome}`) + return reply.code(200).send({ received: true }) + } catch (e) { + await client.query("rollback").catch(() => {}) + request.log.error( + `Failed to handle Stripe event ${event.id} (${event.type}): ${e}` + ) + return reply.code(500).send({ error: "Webhook handling failed" }) + } finally { + client.release() + } + }) +} + +/** + * The Stripe webhook as an external route. The Stripe signature is the + * authentication, so the route is exempt from the CSRF check and needs no + * session. It keeps answering while the `payments` flag is off + * (`gateWhenOff: false`): payments started before the switch still settle. + */ +export const stripeWebhook: ExternalRouteModule = { + name: "stripe", + paths: [{ method: "POST", path: STRIPE_WEBHOOK_PATH, csrfExempt: true }], + feature: "payments", + gateWhenOff: false, + configured: () => paymentsConfigured(), + register: StripeWebhook, +} diff --git a/@app/server/src/telegram.ts b/@app/server/src/telegram.ts new file mode 100644 index 000000000..bf21e8e2b --- /dev/null +++ b/@app/server/src/telegram.ts @@ -0,0 +1,259 @@ +import { + detectedTelegramLanguage, + TelegramError, + telegramRequest, +} from "@app/lib/dist/cjs/telegram" +import { Pool, PoolClient } from "pg" + +import { isFeatureEnabled } from "./utils/featureFlags" + +/** How long the poller waits before checking again while the flag is off. */ +const POLLING_IDLE_MS = 30000 + +interface TelegramUser { + id: number + username?: string + language_code?: string + is_bot?: boolean +} + +export interface TelegramUpdate { + update_id: number + message?: { + text?: string + chat: { id: number; type: string } + from?: TelegramUser + } + callback_query?: { + id: string + from: TelegramUser + data?: string + message?: { chat: { id: number; type: string } } + } + + my_chat_member?: { + chat: { id: number; type: string } + new_chat_member: { status: string } + } +} + +// A repeated webhook or poll must not consume the code again or unlink again. +export async function processTelegramUpdate( + client: PoolClient, + update: TelegramUpdate +) { + if (!Number.isSafeInteger(update?.update_id)) return + const claimed = await client.query( + "insert into app_private.telegram_updates(update_id) values($1) on conflict do nothing returning update_id", + [update.update_id] + ) + if (!claimed.rowCount) return + await client.query( + "delete from app_private.telegram_updates where processed_at < now() - interval '7 days'" + ) + const membership = update.my_chat_member + if ( + membership?.chat.type === "private" && + membership.new_chat_member.status === "kicked" + ) { + await client.query( + "select app_private.disconnect_telegram(user_id) from app_public.telegram_accounts where chat_id = $1", + [membership.chat.id] + ) + return + } + const callback = update.callback_query + const message = update.message + const chat = callback ? callback.message?.chat : message?.chat + const from = callback ? callback.from : message?.from + // A button may only change the preferences of its private-chat owner. + if ( + !chat || + chat.type !== "private" || + !from || + from.is_bot || + !Number.isSafeInteger(chat.id) || + chat.id <= 0 || + from.id !== chat.id + ) + return + const callbackLanguage = callback?.data?.match(/^language:(en|fi|auto)$/)?.[1] + if (callback && !callbackLanguage) return + await client.query( + `insert into app_private.telegram_preferences(chat_id, detected_language) + values($1, $2) on conflict(chat_id) do update + set detected_language = case when $3 then excluded.detected_language else telegram_preferences.detected_language end`, + [ + chat.id, + detectedTelegramLanguage(from.language_code), + !!from.language_code, + ] + ) + const command = message?.text?.match( + /^\/(start|stop|language)(?:@[A-Za-z0-9_]+)?(?:\s+([^\s]+))?\s*$/ + ) + if (!command && !callbackLanguage) return + let reply: string + if (callbackLanguage || command?.[1] === "language") { + const choice = callbackLanguage || command?.[2] + if (choice && ["en", "fi", "auto"].includes(choice)) { + await client.query( + "update app_private.telegram_preferences set language = $2 where chat_id = $1", + [chat.id, choice] + ) + reply = "languageSaved" + } else reply = "languageMenu" + } else if (command?.[1] === "stop") { + await client.query( + "select app_private.disconnect_telegram(user_id) from app_public.telegram_accounts where chat_id = $1", + [chat.id] + ) + reply = "disconnected" + } else if (command?.[2]) { + const { + rows: [result], + } = await client.query( + "select app_private.connect_telegram($1, $2, $3) as connected", + [command[2], chat.id, from.username || null] + ) + reply = result.connected ? "connected" : "invalidLink" + } else reply = "welcome" + // Resolve the language in the worker, so queued replies follow later changes too. + await client.query( + "select graphile_worker.add_job('telegram__reply', $1::json, queue_name := 'telegram-reminders')", + [ + JSON.stringify({ + chatId: chat.id, + reply, + ...(callback ? { callbackQueryId: callback.id } : {}), + }), + ] + ) +} + +export async function handleTelegramUpdate(pool: Pool, update: TelegramUpdate) { + const client = await pool.connect() + try { + await client.query("begin") + await processTelegramUpdate(client, update) + await client.query("commit") + } catch (error) { + await client.query("rollback") + throw error + } finally { + client.release() + } +} + +export function startTelegramPolling( + pool: Pool, + { + isEnabled = () => isFeatureEnabled("telegram_reminders"), + }: { isEnabled?: () => Promise } = {} +) { + let stopped = false + let wake: (() => void) | undefined + const sleep = (ms: number) => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms) + wake = () => { + clearTimeout(timer) + resolve() + } + }) + const done = (async () => { + // Session advisory lock prevents two local servers from polling the same bot. + const client = await pool.connect() + try { + const { + rows: [lock], + } = await client.query( + "select pg_try_advisory_lock(478433, 1) as acquired" + ) + if (!lock.acquired) return + try { + let checkedWebhook = false + while (!stopped) { + try { + // While the feature is off, leave updates with Telegram. + if (!(await isEnabled())) { + await sleep(POLLING_IDLE_MS) + continue + } + if (!checkedWebhook) { + const info = await telegramRequest<{ url: string }>( + "getWebhookInfo", + {} + ) + if (info.url) { + console.error( + "Telegram has an active webhook; polling was not started" + ) + return + } + checkedWebhook = true + console.log( + "Telegram polling started for @" + + (process.env.TELEGRAM_BOT_USERNAME || "IlmoReminderBot") + ) + } + const { + rows: [state], + } = await client.query( + "select next_offset from app_private.telegram_poll_state where id" + ) + const updates = await telegramRequest( + "getUpdates", + { + offset: Number(state.next_offset), + timeout: 20, + allowed_updates: [ + "message", + "my_chat_member", + "callback_query", + ], + } + ) + for (const update of updates) { + if (stopped) break + await client.query("begin") + try { + await processTelegramUpdate(client, update) + await client.query( + "update app_private.telegram_poll_state set next_offset = greatest(next_offset, $1) where id", + [update.update_id + 1] + ) + await client.query("commit") + } catch (error) { + await client.query("rollback") + throw error + } + } + } catch (error) { + // Sanitized errors only; no bot tokens or linking codes. + console.error( + "Telegram polling:", + error instanceof TelegramError + ? `API ${error.code}` + : "connection or processing failed" + ) + if (!stopped) await sleep(5000) + } + } + } finally { + await client.query("select pg_advisory_unlock(478433, 1)") + } + } catch { + console.error( + "Telegram polling could not start; check bot configuration and database migrations" + ) + } finally { + client.release() + } + })() + return async () => { + stopped = true + wake?.() + await done + } +} diff --git a/@app/server/src/telegramWebhook.ts b/@app/server/src/telegramWebhook.ts new file mode 100644 index 000000000..e60e8eccc --- /dev/null +++ b/@app/server/src/telegramWebhook.ts @@ -0,0 +1,65 @@ +import { timingSafeEqual } from "node:crypto" + +import { handleTelegramUpdate, TelegramUpdate } from "./telegram" + +import type { ExternalRouteModule } from "./externalRoutes" + +export const TELEGRAM_WEBHOOK_PATH = "/telegram/webhook" + +/** + * How the server receives bot updates: "webhook" (Telegram calls + * TELEGRAM_WEBHOOK_PATH) or "polling" (the server asks Telegram, see + * installTelegramPolling). Defaults to webhook in production. + */ +export function telegramUpdateMode(env = process.env): string { + return ( + env.TELEGRAM_UPDATE_MODE || + (env.NODE_ENV === "production" ? "webhook" : "polling") + ) +} + +function secretMatches(header: unknown, secret: string) { + return ( + typeof header === "string" && + Buffer.byteLength(header) === Buffer.byteLength(secret) && + timingSafeEqual(Buffer.from(header), Buffer.from(secret)) + ) +} + +/** + * The Telegram bot webhook. Telegram authenticates each call with the + * secret token registered with the webhook, not with a browser session, so + * the route is exempt from the CSRF check. It exists only in webhook mode + * with both the bot token and the secret set; otherwise the path is neither + * registered nor exempt. + */ +export const telegramWebhook: ExternalRouteModule = { + name: "telegram", + paths: [{ method: "POST", path: TELEGRAM_WEBHOOK_PATH, csrfExempt: true }], + feature: "telegram_reminders", + configured: () => + telegramUpdateMode() === "webhook" && + Boolean(process.env.TELEGRAM_BOT_TOKEN) && + Boolean(process.env.TELEGRAM_WEBHOOK_SECRET), + register: async (app) => { + app.post( + TELEGRAM_WEBHOOK_PATH, + { bodyLimit: 65536 }, + async (req, reply) => { + const secret = process.env.TELEGRAM_WEBHOOK_SECRET + if ( + !secret || + !secretMatches(req.headers["x-telegram-bot-api-secret-token"], secret) + ) { + return reply.code(403).send({ error: "Forbidden" }) + } + const update = req.body as TelegramUpdate + if (!Number.isSafeInteger(update?.update_id)) { + return reply.code(400).send({ error: "Invalid update" }) + } + await handleTelegramUpdate(app.rootPgPool, update) + return { ok: true } + } + ) + }, +} diff --git a/@app/server/src/utils/emailUtils.ts b/@app/server/src/utils/emailUtils.ts index 93d3eab57..82d57ab44 100644 --- a/@app/server/src/utils/emailUtils.ts +++ b/@app/server/src/utils/emailUtils.ts @@ -1,4 +1,5 @@ import { emailFooterText as footerText, projectName } from "@app/config" +import { formatEuro } from "@app/lib" import mjml2html from "mjml" import nunjucks from "nunjucks" @@ -7,6 +8,8 @@ const isDev = process.env.NODE_ENV !== "production" const njk = new nunjucks.Environment( new nunjucks.FileSystemLoader(`${__dirname}/../../../worker/templates/`) ) +// Money is integer cents in template variables; `{{ total | euro }}` -> 18,25 € +njk.addFilter("euro", (cents: number) => formatEuro(cents)) // TODO: Code duplication with @app/worker/src/send_email.ts const templatePromises = {} diff --git a/@app/server/src/utils/featureFlags.ts b/@app/server/src/utils/featureFlags.ts new file mode 100644 index 000000000..5115ae84f --- /dev/null +++ b/@app/server/src/utils/featureFlags.ts @@ -0,0 +1,208 @@ +import { + featureConfigured, + FeatureDefinition, + FeatureKey, + FEATURES, +} from "@app/lib" +import { Pool } from "pg" + +/** + * Server-side reads of the feature flags in `app_public.feature_flags`. + * + * The database decides: `app_public.feature_enabled(key)` is evaluated for + * every row through the root pool, which has no user session, so the result + * is "enabled for everyone". `admins_only` is added on top only for callers + * that pass `asAdmin` because they have already established that the request + * comes from an admin. + * + * The answers are cached in-process for `FEATURE_FLAG_CACHE_TTL_MS`. There is + * deliberately no LISTEN connection: the root pool is small and one permanent + * connection would take a large share of it. Instead the cache is invalidated + * whenever the `setFeatureFlag` mutation passes through this server (see + * FeatureFlagsPlugin), so a switch made here is visible on the next request + * after it commits, and one made elsewhere within the TTL. + */ + +export const FEATURE_FLAG_CACHE_TTL_MS = 5000 + +interface FlagSnapshot { + /** `feature_enabled(key)` for a visitor without a session. */ + enabled: boolean + /** True when the flag is available, not retired and in `admins_only`. */ + adminsOnly: boolean +} + +export interface FeatureFlagReader { + isFeatureEnabled( + key: FeatureKey, + options?: { asAdmin?: boolean } + ): Promise + invalidate(): void +} + +export function createFeatureFlagReader( + pool: Pick, + { + ttlMs = FEATURE_FLAG_CACHE_TTL_MS, + now = Date.now, + }: { ttlMs?: number; now?: () => number } = {} +): FeatureFlagReader { + let snapshot: Map | null = null + let fetchedAt = 0 + // Bumped by invalidate() so that a load that started before the + // invalidation cannot store its (possibly stale) result afterwards. + let generation = 0 + let inFlight: Promise> | null = null + + const load = async (): Promise> => { + const startedGeneration = generation + const { rows } = await pool.query<{ + key: string + enabled: boolean + admins_only: boolean + }>( + `select + f.key, + app_public.feature_enabled(f.key) as enabled, + (f.retired_at is null and f.available and f.state = 'admins_only') as admins_only + from app_public.feature_flags as f` + ) + const loaded = new Map( + rows.map((row) => [ + row.key, + { enabled: row.enabled, adminsOnly: row.admins_only }, + ]) + ) + if (startedGeneration === generation) { + snapshot = loaded + fetchedAt = now() + } + return loaded + } + + const current = async () => { + if (snapshot && now() - fetchedAt < ttlMs) { + return snapshot + } + if (!inFlight) { + const loading: Promise> = load().finally(() => { + if (inFlight === loading) { + inFlight = null + } + }) + inFlight = loading + } + return inFlight + } + + return { + async isFeatureEnabled(key, { asAdmin = false } = {}) { + const flag = (await current()).get(key) + if (!flag) { + // Unknown keys read as off, as they do in the database. + return false + } + return flag.enabled || (asAdmin && flag.adminsOnly) + }, + invalidate() { + generation++ + snapshot = null + inFlight = null + }, + } +} + +let reader: FeatureFlagReader | null = null + +/** + * Points the module-level helpers at the root pool. Called once at boot by + * the installFeatureFlags middleware, and by the jest helpers. + */ +export function configureFeatureFlags(pool: Pick) { + reader = createFeatureFlagReader(pool) +} + +/** + * Whether a feature is enabled. Pass `asAdmin: true` only when the caller + * already knows the request comes from an admin; `admins_only` flags are then + * on as well. + */ +export function isFeatureEnabled( + key: FeatureKey, + options?: { asAdmin?: boolean } +): Promise { + if (!reader) { + throw new Error( + "isFeatureEnabled was called before configureFeatureFlags(rootPgPool)" + ) + } + return reader.isFeatureEnabled(key, options) +} + +/** Drops the cached flag states so that the next read goes to the database. */ +export function invalidateFeatureFlags() { + reader?.invalidate() +} + +/** + * Records in `feature_flags.available` whether this server has the + * configuration each integration-backed feature needs (see `requiresEnv` in + * the registry). Features without requirements are left alone. Returns what + * was written, and the keys whose row is missing (the migration that adds the + * feature has not run). + */ +export async function syncFeatureAvailability( + pool: Pick, + { + env = process.env, + features = FEATURES, + }: { + env?: Record + features?: Record + } = {} +): Promise<{ available: Record; missing: string[] }> { + const available: Record = {} + const missing: string[] = [] + for (const [key, definition] of Object.entries(features)) { + if (!definition.requiresEnv?.length) { + continue + } + const configured = featureConfigured(definition, env) + const { + rows: [row], + } = await pool.query<{ found: boolean }>( + "select app_private.set_feature_available($1, $2) as found", + [key, configured] + ) + if (row?.found) { + available[key] = configured + } else { + missing.push(key) + } + } + return { available, missing } +} + +/** + * Whether a feature is enabled for the user of a GraphQL request: on for + * everyone, or `admins_only` and the request's session belongs to an admin. + * `pgClient` is the request's client, which carries the session; it is + * queried only when the flag is not on for everyone. + */ +export async function isFeatureEnabledForSession( + key: FeatureKey, + pgClient: { query: Pool["query"] } +): Promise { + if (await isFeatureEnabled(key)) { + return true + } + if (!(await isFeatureEnabled(key, { asAdmin: true }))) { + return false + } + const { + rows: [row], + } = await pgClient.query<{ is_admin: boolean }>( + "select app_public.current_user_is_admin() as is_admin" + ) + return Boolean(row?.is_admin) +} diff --git a/@app/server/src/utils/handleErrors.ts b/@app/server/src/utils/handleErrors.ts index d8d390db4..4c714822a 100644 --- a/@app/server/src/utils/handleErrors.ts +++ b/@app/server/src/utils/handleErrors.ts @@ -1,7 +1,6 @@ +import { GraphQLError } from "graphql" import { camelCase } from "lodash" -import type { GraphQLError } from "graphql" - const isDev = process.env.NODE_ENV === "development" const isTest = process.env.NODE_ENV === "test" @@ -89,11 +88,41 @@ function conflictFieldsFromError(err: any) { return undefined } +/* + * PostGraphile's error for an update or delete mutation that matched no row + * the user may change. + */ +const NO_ROWS_MATCHED_MESSAGE = + /^No values were (updated|deleted) in collection/ + +/* + * Errors that carry a code (SQLSTATE or one of ours) are expected and meant for + * the user, as are errors of the GraphQL request itself, which have no + * original error, and mutations that matched no row. Anything else, such as a + * pg-pool connection timeout, is unexpected and is logged so that it shows up + * in the server logs too. + */ +function isUnexpected(originalError: Error | null | undefined): boolean { + return ( + originalError != null && + !(originalError instanceof GraphQLError) && + originalError["code"] == null && + originalError["errcode"] == null && + !NO_ROWS_MATCHED_MESSAGE.test(originalError.message) + ) +} + export default function handleErrors( errors: readonly GraphQLError[] ): Array { return errors.map((error) => { const { message: rawMessage, locations, path, originalError } = error + if (isUnexpected(originalError)) { + console.error( + `Unexpected error in GraphQL operation at ${JSON.stringify(path)}:`, + originalError + ) + } const code = originalError ? originalError["code"] : null const localPluck = ERROR_MESSAGE_OVERRIDES[code] || pluck const exception = localPluck(originalError || error) diff --git a/@app/server/src/utils/keycloak.ts b/@app/server/src/utils/keycloak.ts index c08c5675d..68709c6e1 100644 --- a/@app/server/src/utils/keycloak.ts +++ b/@app/server/src/utils/keycloak.ts @@ -14,6 +14,10 @@ export { keycloakEnabled, sanitizeNext } export type RequestLogger = Pick export const ILMO_ADMIN_ROLE = "ilmo-admin" +// Lets an admin switch feature flags. There is no in-app way to grant it: it +// comes from this realm role only (or a direct SQL update for accounts that +// never log in through SSO). +export const ILMO_DEVELOPER_ROLE = "ilmo-developer" // Local accounts kept for break-glass access; an SSO login must never link // onto (or flip is_admin on) these rows. Compared lowercase (username is citext), @@ -27,6 +31,13 @@ export interface KeycloakProfile { readonly email: string readonly emailVerified: boolean readonly name: string + /** + * The standard OIDC `given_name` / `family_name` claims, `null` when the + * token doesn't carry them. Unlike `name` they keep multi-word first and + * last names apart ("Anna Maria" / "von Wright"). + */ + readonly givenName: string | null + readonly familyName: string | null /** * The raw email localpart. It is *not* a valid app username: register_user * strips and slugifies it and appends a counter to break ties, so only the @@ -42,6 +53,8 @@ export interface KeycloakProfile { * quietly demotes every admin on their next login. */ readonly isAdmin: boolean | null + /** Same three-valued semantics as `isAdmin`, for ILMO_DEVELOPER_ROLE. */ + readonly isDeveloper: boolean | null } export function mapKeycloakClaims( @@ -64,10 +77,10 @@ export function mapKeycloakClaims( : null if (roles === null) { // "No roles claim" and "no roles" are indistinguishable in the payload, - // so the missing claim maps to isAdmin: null rather than false. + // so the missing claim maps to isAdmin/isDeveloper: null rather than false. logger?.warn( { sub }, - "keycloak id token has no usable realm_access.roles claim; admin status is unknown — check the client's realm-roles mapper" + "keycloak id token has no usable realm_access.roles claim; admin and developer status are unknown — check the client's realm-roles mapper" ) } if (claims.email_verified === undefined) { @@ -79,11 +92,15 @@ export function mapKeycloakClaims( ) } const rawLocale = typeof claims.locale === "string" ? claims.locale : null + const nameClaim = (claim: unknown) => + typeof claim === "string" && claim.trim() ? claim.trim() : null return { sub, email, emailVerified: claims.email_verified === true, name: typeof claims.name === "string" ? claims.name : localpart, + givenName: nameClaim(claims.given_name), + familyName: nameClaim(claims.family_name), usernameSuggestion: localpart, // The app ships fi/en/se; anything else has no translations to fall back // on, so the user keeps whatever locale the browser negotiated. @@ -92,5 +109,6 @@ export function mapKeycloakClaims( ? rawLocale : null, isAdmin: roles === null ? null : roles.includes(ILMO_ADMIN_ROLE), + isDeveloper: roles === null ? null : roles.includes(ILMO_DEVELOPER_ROLE), } } diff --git a/@app/server/src/utils/poolConfig.ts b/@app/server/src/utils/poolConfig.ts new file mode 100644 index 000000000..f9c2556d4 --- /dev/null +++ b/@app/server/src/utils/poolConfig.ts @@ -0,0 +1,52 @@ +export type PoolKind = "root" | "auth" + +export interface PoolConfig { + max: number + connectionTimeoutMillis: number +} + +/* + * The defaults fit the server and worker into a budget of 10 Postgres + * connections: root 2 + auth 5 (one of which is held by @graphile/pg-pubsub + * for LISTEN) + worker 2 (WORKER_POOL_MAX, which the worker's start scripts + * read from the process environment rather than from .env). + */ +const DEFAULT_MAX: Record = { + root: 2, + auth: 5, +} +const DEFAULT_ACQUIRE_TIMEOUT_MS = 5000 + +const MAX_ENV_VAR: Record = { + root: "DATABASE_POOL_MAX_ROOT", + auth: "DATABASE_POOL_MAX_AUTH", +} +const ACQUIRE_TIMEOUT_ENV_VAR = "DATABASE_POOL_ACQUIRE_TIMEOUT_MS" + +function positiveIntFromEnv(name: string, fallback: number): number { + const raw = process.env[name] + if (raw === undefined || raw === "") { + return fallback + } + const value = Number(raw) + if (!Number.isInteger(value) || value <= 0) { + throw new Error( + `process.env.${name} must be a positive integer, got '${raw}'` + ) + } + return value +} + +/** + * Size and acquire timeout for a `pg` Pool. A request that cannot get a + * connection within the timeout fails instead of waiting indefinitely. + */ +export function poolConfig(kind: PoolKind): PoolConfig { + return { + max: positiveIntFromEnv(MAX_ENV_VAR[kind], DEFAULT_MAX[kind]), + connectionTimeoutMillis: positiveIntFromEnv( + ACQUIRE_TIMEOUT_ENV_VAR, + DEFAULT_ACQUIRE_TIMEOUT_MS + ), + } +} diff --git a/@app/server/src/utils/stripe.ts b/@app/server/src/utils/stripe.ts new file mode 100644 index 000000000..a9cc50cd6 --- /dev/null +++ b/@app/server/src/utils/stripe.ts @@ -0,0 +1,37 @@ +import { paymentsConfigured } from "@app/lib" +import Stripe from "stripe" + +// Server code reads the configuration check through here. +export { paymentsConfigured } + +let client: Stripe | null = null + +/** + * The shared Stripe client, constructed on first use from + * `STRIPE_SECRET_KEY`. The API version is the one this major of the `stripe` + * package is pinned to, so upgrading the package is what moves it. + * + * Throws while Stripe is not configured: every caller sits behind a + * `paymentsConfigured()` check (and, for starting a payment, the `payments` + * flag), so reaching this unconfigured is a bug, and failing loudly beats + * talking to Stripe with a half-configured server. + */ +export function getStripe(): Stripe { + if (!paymentsConfigured()) { + throw new Error( + "Stripe client requested while Stripe is not configured (STRIPE_SECRET_KEY / STRIPE_WEBHOOK_SECRET)" + ) + } + if (!client) { + client = new Stripe(process.env.STRIPE_SECRET_KEY!, { + appInfo: { name: "Ilmo", url: "https://github.com/Prodeko/ilmo" }, + maxNetworkRetries: 2, + }) + } + return client +} + +/** Forget the cached client, so tests can change the environment. */ +export function resetStripeClient(): void { + client = null +} diff --git a/@app/server/src/utils/throttleTopic.ts b/@app/server/src/utils/throttleTopic.ts new file mode 100644 index 000000000..051230f3e --- /dev/null +++ b/@app/server/src/utils/throttleTopic.ts @@ -0,0 +1,95 @@ +import { createHash } from "node:crypto" + +/* + * The slice of a graphql-subscriptions PubSubEngine the relay uses. With + * @graphile/pg-pubsub, subscribing to a topic LISTENs on the Postgres channel + * of the same name using its single shared listening connection. + */ +export interface RelayPubSub { + publish(topic: string, payload: any): unknown + subscribe(topic: string, onMessage: (payload: any) => void): unknown +} + +const relays = new WeakMap>() + +/* + * Postgres truncates channel names to 63 characters, and @graphile/pg-pubsub + * LISTENs on every topic subscribed through it, so the throttled topic gets a + * short name of its own that cannot collide with a real channel. + */ +function throttledTopicName(sourceTopic: string): string { + const digest = createHash("sha1").update(sourceTopic).digest("hex") + return `throttled:${digest}` +} + +/** + * Relays `sourceTopic` to a throttled topic that publishes at most once per + * `intervalMs`: the first message of a burst goes out immediately and the last + * message received during the window goes out when the window ends. Returns the + * throttled topic's name. The relay is created on the first call for a source + * topic and shared by later calls. + */ +export function throttledTopic( + pubsub: RelayPubSub, + sourceTopic: string, + intervalMs: number +): string { + let topics = relays.get(pubsub) + if (!topics) { + topics = new Map() + relays.set(pubsub, topics) + } + const existing = topics.get(sourceTopic) + if (existing) { + return existing + } + + const topic = throttledTopicName(sourceTopic) + topics.set(sourceTopic, topic) + + let windowOpen = false + let hasPending = false + let pending: unknown + + const logFailure = (error: unknown) => { + console.error(`Failed to relay ${sourceTopic} to ${topic}:`, error) + } + + // The window's timer is scheduled before publishing, so a failing publish + // cannot leave the window open for good. + const publish = (payload: unknown) => { + try { + const result = pubsub.publish(topic, payload) + if (typeof (result as PromiseLike)?.then === "function") { + Promise.resolve(result).catch(logFailure) + } + } catch (error) { + logFailure(error) + } + } + + const closeWindow = () => { + if (hasPending) { + const payload = pending + hasPending = false + pending = undefined + setTimeout(closeWindow, intervalMs) + publish(payload) + } else { + windowOpen = false + } + } + + pubsub.subscribe(sourceTopic, (payload) => { + if (windowOpen) { + pending = payload + hasPending = true + return + } + windowOpen = true + setTimeout(closeWindow, intervalMs) + publish(payload) + }) + + return topic +} diff --git a/@app/worker/README.md b/@app/worker/README.md index 2b764fa24..4835f8108 100644 --- a/@app/worker/README.md +++ b/@app/worker/README.md @@ -1,5 +1,29 @@ # @app/worker +## Local delivery testing + +By default, `NODE_ENV=test` captures emails in memory and development mode uses +Ethereal, which does not deliver to real inboxes. To test actual registration +emails locally without running the app in production mode: + +1. Configure `SENDGRID_USERNAME` and `SENDGRID_API_KEY` in the local + environment. The SMTP username is normally `apikey`. The sender configured in + `@app/config/src/index.ts` must be authorized in SendGrid. +2. Copy `email.local.example.json` to `email.local.json` in this directory and + replace `allowedRecipients` with the exact email addresses you want to test. +3. Restart the worker (or `pnpm dev`) and complete a new registration using an + allowed address. Already-sent confirmations are not automatically resent. + +The local configuration is ignored by Git, production, and automated tests. +Messages to addresses outside its allowlist are skipped. Remove the file and +restart the worker to return to the normal test transport. + +Confirmed registrations and promotions from the waiting list include a calendar +invitation alongside the existing confirmation text. Waitlisted registrations do +not receive an invitation until they get a place. Calendar responses do not +change registration status in Ilmo, and later event edits/cancellations are not +currently synchronized with saved calendar entries. + It's bad practice to perform unnecessary actions during the normal request cycle as it makes our web app seem slower. It's also bad practice to have a user retry an action a few seconds later that we could handle easily on the backend for diff --git a/@app/worker/__tests__/calendarEmail.test.ts b/@app/worker/__tests__/calendarEmail.test.ts new file mode 100644 index 000000000..f5294eee7 --- /dev/null +++ b/@app/worker/__tests__/calendarEmail.test.ts @@ -0,0 +1,96 @@ +import nodemailer from "nodemailer" + +import { registrationCalendarInvitation } from "../src/calendarInvitation" +import { + getLocalEmailSettings, + localRecipientAllowed, + parseLocalEmailSettings, +} from "../src/localEmail" + +const event = { + id: "test-event", + slug: "test-event", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { + fi: [{ type: "paragraph", children: [{ text: "Tervetuloa!" }] }], + }, + location: "Otaniemi", + event_start_time: "2026-10-24T18:00:00+03:00", + event_end_time: "2026-10-24T22:00:00+03:00", +} + +it("uses a strict recipient allowlist for local delivery", () => { + const settings = parseLocalEmailSettings({ + transport: "sendgrid", + allowedRecipients: ["Tester@example.com"], + }) + expect(localRecipientAllowed("tester@example.com", settings)).toBe(true) + expect(localRecipientAllowed(" TESTER@example.com ", settings)).toBe(true) + expect( + localRecipientAllowed(["tester@example.com", "other@example.com"], settings) + ).toBe(false) + expect( + localRecipientAllowed("tester@example.com,other@example.com", settings) + ).toBe(false) + expect(localRecipientAllowed([], settings)).toBe(false) + expect(() => + parseLocalEmailSettings({ transport: "sendgrid", allowedRecipients: [] }) + ).toThrow() + expect(() => + parseLocalEmailSettings({ + transport: "sendgrid", + allowedRecipients: ["a@example.com\nb@example.com"], + }) + ).toThrow() +}) + +it("ignores the local delivery configuration during automated tests", async () => { + expect(await getLocalEmailSettings()).toBeUndefined() +}) + +it("includes a private, correctly timed invitation without registration secrets", () => { + const invitation = registrationCalendarInvitation( + event, + "tester@example.com", + "http://192.168.1.42:5678" + ) + expect(invitation.filename).toBe("event.ics") + expect(invitation.contentType).toBe("text/calendar; method=REQUEST") + expect(invitation.content).toContain("METHOD:REQUEST\r\n") + expect(invitation.content).toContain("DTSTART:20261024T150000Z\r\n") + expect(invitation.content).toContain("DTEND:20261024T190000Z\r\n") + expect(invitation.content).toContain( + "ORGANIZER:mailto:no-reply@prodeko.org\r\n" + ) + expect(invitation.content).toContain( + "ATTENDEE;RSVP=FALSE:mailto:tester@example.com\r\n" + ) + expect(invitation.content).toContain("SUMMARY:Testitapahtuma\r\n") + expect(invitation.content).toContain("DESCRIPTION:Tervetuloa!") + expect(invitation.content).not.toContain("update-registration") +}) + +it("renders a real multipart email with the confirmation body and calendar part", async () => { + const transport = nodemailer.createTransport({ + streamTransport: true, + buffer: true, + }) + const result = await transport.sendMail({ + from: "no-reply@prodeko.org", + to: "tester@example.com", + subject: "Registration confirmed", + text: "Your registration was saved.", + html: "

Your registration was saved.

", + attachments: [ + registrationCalendarInvitation( + event, + "tester@example.com", + "https://example.com" + ), + ], + }) + const message = result.message.toString() + expect(message).toContain("Your registration was saved.") + expect(message).toMatch(/Content-Type: text\/calendar;[^]*?method=REQUEST/i) + expect(message).toContain("event.ics") +}) diff --git a/@app/worker/__tests__/featureFlags.test.ts b/@app/worker/__tests__/featureFlags.test.ts new file mode 100644 index 000000000..e9163fc33 --- /dev/null +++ b/@app/worker/__tests__/featureFlags.test.ts @@ -0,0 +1,105 @@ +import { poolFromUrl, TEST_DATABASE_URL } from "../../__tests__/helpers" +import { withFeature } from "../src/featureFlags" + +import type { FeatureFlagState, FeatureKey } from "@app/lib" +import type { JobHelpers } from "graphile-worker" + +// The registry has no keys of its own here; the tests use a key that only +// exists inside their rolled-back transaction. +const KEY = "worker_test_flag" as FeatureKey + +function fakeHelpers(query: JobHelpers["query"]) { + return { + query, + logger: { info: jest.fn() }, + job: { task_identifier: "test_task" }, + } as unknown as JobHelpers & { logger: { info: jest.Mock } } +} + +describe("withFeature", () => { + it("runs the task with its payload and helpers when the feature is enabled", async () => { + const query = jest.fn(async () => ({ rows: [{ enabled: true }] })) + const helpers = fakeHelpers(query as any) + const task = jest.fn() + + await withFeature(KEY, task)({ id: 1 }, helpers) + + expect(query).toHaveBeenCalledWith( + "select app_public.feature_enabled($1) as enabled", + [KEY] + ) + expect(task).toHaveBeenCalledWith({ id: 1 }, helpers) + }) + + it("does no work when the feature is off", async () => { + const query = jest.fn(async () => ({ rows: [{ enabled: false }] })) + const helpers = fakeHelpers(query as any) + const task = jest.fn() + + await expect(withFeature(KEY, task)({}, helpers)).resolves.toBeUndefined() + + expect(task).not.toHaveBeenCalled() + expect(helpers.logger.info).toHaveBeenCalledWith( + expect.stringContaining(`feature "${KEY}" is off`) + ) + }) + + it("propagates the task's failure so the job is retried", async () => { + const query = jest.fn(async () => ({ rows: [{ enabled: true }] })) + const task = jest.fn(async () => { + throw new Error("boom") + }) + + await expect( + withFeature(KEY, task)({}, fakeHelpers(query as any)) + ).rejects.toThrow("boom") + }) + + describe("against the database", () => { + const runWithState = async ( + state: FeatureFlagState | null, + available = true + ) => { + const client = await poolFromUrl(TEST_DATABASE_URL).connect() + try { + await client.query("begin") + if (state) { + await client.query( + `insert into app_public.feature_flags (key, state, available, description) + values ($1, $2, $3, 'Test flag')`, + [KEY, state, available] + ) + } + const task = jest.fn() + await withFeature(KEY, task)( + {}, + fakeHelpers((text, values) => client.query(text, values)) + ) + return task.mock.calls.length > 0 + } finally { + await client.query("rollback") + client.release() + } + } + + it("runs when the flag is on", async () => { + expect(await runWithState("on")).toBe(true) + }) + + it("treats admins_only as off, since jobs have no session", async () => { + expect(await runWithState("admins_only")).toBe(false) + }) + + it("skips when the flag is off", async () => { + expect(await runWithState("off")).toBe(false) + }) + + it("skips when the flag is on but not available", async () => { + expect(await runWithState("on", false)).toBe(false) + }) + + it("skips for a key without a row", async () => { + expect(await runWithState(null)).toBe(false) + }) + }) +}) diff --git a/@app/worker/__tests__/helpers.ts b/@app/worker/__tests__/helpers.ts new file mode 100644 index 000000000..c7a04f08f --- /dev/null +++ b/@app/worker/__tests__/helpers.ts @@ -0,0 +1,259 @@ +import { Pool } from "pg" + +import { + createEventCategories, + createEvents, + createQuotas, + createRegistrations, + createRegistrationSecrets, + poolFromUrl, + TEST_DATABASE_URL, +} from "../../__tests__/helpers" + +import type { JobHelpers, Task } from "graphile-worker" + +export { + deleteTestData, + getEmails, + setFeatureFlag, +} from "../../__tests__/helpers" + +/* + * Shared setup for the worker task tests. Tasks are called directly with job + * helpers backed by the test database, so their queries and queued jobs are + * real. + */ + +export function testPool(): Pool { + return poolFromUrl(TEST_DATABASE_URL) +} + +/******************************************************************************/ +// Running tasks + +export type TestJobHelpers = JobHelpers & { + logger: { + info: jest.Mock + warn: jest.Mock + error: jest.Mock + debug: jest.Mock + } +} + +/** + * Job helpers like graphile-worker's: `query` and `withPgClient` use the test + * database and `addJob` really queues the job, so tests can read it back + * with `jobsOf`. + */ +export function jobHelpers(pool: Pool = testPool()): TestJobHelpers { + const logger = { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + } + const helpers = { + logger, + // What withFeature logs when it skips a job + job: { task_identifier: "test_task" }, + query: (text: string, values?: unknown[]) => pool.query(text, values), + withPgClient: async (callback) => { + const client = await pool.connect() + try { + return await callback(client) + } finally { + client.release() + } + }, + addJob: async (identifier: string, payload: unknown) => { + await pool.query("select graphile_worker.add_job($1, $2::json)", [ + identifier, + JSON.stringify(payload ?? {}), + ]) + }, + } + return helpers as unknown as TestJobHelpers +} + +export async function runTask( + task: Task, + payload: unknown, + helpers: TestJobHelpers = jobHelpers() +) { + await task(payload as any, helpers) + return helpers +} + +/** Payloads of the queued jobs of a task, oldest first. */ +export async function jobsOf(taskIdentifier: string, pool: Pool = testPool()) { + const { rows } = await pool.query( + `select jobs.payload + from graphile_worker._private_jobs as jobs + join graphile_worker._private_tasks as tasks on tasks.id = jobs.task_id + where tasks.identifier = $1 + order by jobs.id`, + [taskIdentifier] + ) + return rows.map((row) => row.payload) +} + +/******************************************************************************/ +// Data + +interface PaidEventOptions { + priceCents?: number + quotaSize?: number + registrationCount?: number + /** Move registration end into the past (signup closed). */ + signupClosed?: boolean +} + +/** + * Commits an organization, a category, an event with one quota and some + * finished registrations (with secrets), then sets the quota price. Registrations are inserted one statement at a time, so their + * created_at differ and, with `quotaSize` smaller than `registrationCount`, + * the last ones are queued. Clears the jobs the inserts queued. + */ +export async function createPaidEvent({ + priceCents = 1800, + quotaSize = 10, + registrationCount = 1, + signupClosed = false, +}: PaidEventOptions = {}) { + const pool = testPool() + const client = await pool.connect() + try { + const { + rows: [organization], + } = await client.query( + `insert into app_public.organizations(slug, name, color) + values ('worker-org-' || gen_random_uuid(), 'Worker org', '#002e7d') + returning *` + ) + const [category] = await createEventCategories(client, 1, organization.id) + const [createdEvent] = await createEvents( + client, + 1, + organization.id, + category.id, + true + ) + const [createdQuota] = await createQuotas( + client, + 1, + createdEvent.id, + quotaSize + ) + await client.query( + "update app_public.quotas set price_cents = $2 where id = $1", + [createdQuota.id, priceCents] + ) + const created = await createRegistrations( + client, + registrationCount, + createdEvent.id, + createdQuota.id, + [] + ) + const secrets = await createRegistrationSecrets( + client, + created, + createdEvent.id, + createdQuota.id + ) + if (signupClosed) { + await client.query( + `update app_public.events + set + registration_start_time = now() - interval '2 days', + registration_end_time = now() - interval '1 minute' + where id = $1`, + [createdEvent.id] + ) + } + await client.query("delete from graphile_worker._private_jobs") + + const { + rows: [event], + } = await client.query("select * from app_public.events where id = $1", [ + createdEvent.id, + ]) + const { + rows: [quota], + } = await client.query("select * from app_public.quotas where id = $1", [ + createdQuota.id, + ]) + const { rows: registrations } = await client.query( + "select * from app_public.registrations where event_id = $1 order by created_at, id", + [createdEvent.id] + ) + const tokens = registrations.map( + (r) => + secrets.find((s) => s.registration_id === r.id)!.update_token as string + ) + return { organization, event, quota, registrations, tokens } + } finally { + client.release() + } +} + +interface PaymentOptions { + method?: "STRIPE" | "MANUAL" + status?: "PENDING" | "PAID" | "EXPIRED" + ticketAmountCents?: number + /** Insert without a registration (deleted, or a detached duplicate). */ + detached?: boolean +} + +/** Inserts a payment row, as the server would. */ +export async function insertPayment( + registration: { id: string; event_id: string; quota_id: string }, + { + method = "STRIPE", + status = "PAID", + ticketAmountCents = 1800, + detached = false, + }: PaymentOptions = {} +) { + const { + rows: [payment], + } = await testPool().query( + `insert into app_public.payments( + registration_id, event_id, quota_id, event_name, quota_title, + method, status, ticket_amount_cents, service_fee_cents, paid_at + ) + values ($1, $2, $3, '{"fi": "Syyssitsit", "en": "Autumn sitsit"}', '{"fi": "Jäsenet", "en": "Members"}', + $4::app_public.payment_method, $5::app_public.payment_status, $6, + case when $4::app_public.payment_method = 'STRIPE' then 25 else 0 end, + case when $5::app_public.payment_status = 'PAID' then '2026-10-17 14:32:00'::timestamptz end) + returning *`, + [ + detached ? null : registration.id, + registration.event_id, + registration.quota_id, + method, + status, + ticketAmountCents, + ] + ) + return payment +} + +export async function paymentById(id: string) { + const { + rows: [payment], + } = await testPool().query( + "select * from app_public.payments where id = $1", + [id] + ) + return payment +} + +/** Runs queued send_email payloads through the real send_email task. */ +export async function sendQueuedEmails(sendEmail: Task) { + const payloads = await jobsOf("send_email") + for (const payload of payloads) { + await sendEmail(payload, jobHelpers()) + } + return payloads +} diff --git a/@app/worker/__tests__/localDelivery.test.ts b/@app/worker/__tests__/localDelivery.test.ts new file mode 100644 index 000000000..d1d211d09 --- /dev/null +++ b/@app/worker/__tests__/localDelivery.test.ts @@ -0,0 +1,115 @@ +import { getLocalEmailSettings } from "../src/localEmail" +import sendEmail from "../src/tasks/send_email" +import getTransport from "../src/transport" + +jest.mock("../src/transport", () => ({ __esModule: true, default: jest.fn() })) +jest.mock("../src/localEmail", () => ({ + ...jest.requireActual("../src/localEmail"), + getLocalEmailSettings: jest.fn(), +})) + +const sendMail = jest.fn().mockResolvedValue({ messageId: "test-message" }) + +beforeEach(() => { + jest.clearAllMocks() + jest.mocked(getLocalEmailSettings).mockResolvedValue({ + transport: "sendgrid", + allowedRecipients: ["tester@example.com"], + }) + jest.mocked(getTransport).mockResolvedValue({ sendMail } as any) +}) + +it("does not contact any transport for a recipient outside the local allowlist", async () => { + await sendEmail( + { + options: { to: "other@example.com", subject: "Test" }, + template: "", + variables: {}, + }, + {} as any + ) + expect(getTransport).not.toHaveBeenCalled() + expect(sendMail).not.toHaveBeenCalled() +}) + +it.each([false, true])( + "renders the registration email with waitlist status %s", + async (isWaitlisted) => { + const invitation = { + filename: "event.ics", + contentType: "text/calendar; method=REQUEST", + content: "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n", + } + await sendEmail( + { + options: { + to: "tester@example.com", + subject: "Test", + }, + attachments: [invitation], + template: "event_registration.mjml.njk", + variables: { + isWaitlisted, + eventName: { fi: "Testitapahtuma", en: "Test event" }, + registrationName: "Test User", + registrationQuota: { fi: "Testi", en: "Test" }, + url: "https://example.com", + eventSlug: "test-event", + eventLocation: "Otaniemi", + eventTime: "24.10.26 18:00", + eventRegistrationUpdateLink: "update-registration/private-token", + }, + }, + {} as any + ) + expect(sendMail).toHaveBeenCalledTimes(1) + const message = sendMail.mock.calls[0][0] + expect(message.attachments).toEqual([invitation]) + expect(message.html).toContain("Testitapahtuma") + expect(message.text).toContain("Test event") + expect(message.html).toContain("update-registration/private-token") + if (isWaitlisted) { + expect(message.text).toContain("Olet tällä hetkellä tapahtuman jonossa.") + expect(message.text).toContain("You're currently on the waiting list.") + expect(message.text).toContain("when a place becomes available for you.") + expect(message.text).not.toContain( + "Successfully registered to the event:" + ) + } else { + expect(message.text).toContain("Successfully registered to the event:") + expect(message.text).not.toContain( + "You're currently on the waiting list." + ) + } + } +) + +it.each(["fi", "en"])( + "renders a %s registration reminder", + async (language) => { + await sendEmail( + { + options: { + to: "tester@example.com", + subject: "Registration opens soon", + }, + template: "registration_reminder.mjml.njk", + variables: { + language, + eventName: "Reminder test event", + openingTime: "24.10.2026 18:00", + eventUrl: "https://example.com/event/test-event", + }, + }, + {} as any + ) + const message = sendMail.mock.calls[0][0] + expect(message.text).toContain("Reminder test event") + expect(message.html).toContain("https://example.com/event/test-event") + expect(message.text).toContain( + language === "fi" ? "Ilmoittautuminen alkaa" : "Registration opens" + ) + expect(message.text).toContain("18:00") + expect(message.attachments).toBeUndefined() + } +) diff --git a/@app/worker/__tests__/registrationEmail.test.ts b/@app/worker/__tests__/registrationEmail.test.ts new file mode 100644 index 000000000..ee8a11255 --- /dev/null +++ b/@app/worker/__tests__/registrationEmail.test.ts @@ -0,0 +1,486 @@ +import { calendarInvitationContributor } from "../src/calendarInvitation" +import { paymentEmailContributor } from "../src/paymentEmail" +import { + buildRegistrationEmail, + markRegistrationEmailSent, + registrationEmailContributors, +} from "../src/registrationEmail" +import processQueue from "../src/tasks/registration__process_queue" +import sendConfirmationEmail from "../src/tasks/registration__send_confirmation_email" + +import type { + RegistrationEmailContext, + RegistrationEmailContributor, +} from "../src/registrationEmail" + +function rows() { + return { + registration: { + id: "registration", + event_id: "event", + quota_id: "quota", + email: "tester@example.com", + first_name: "Test", + last_name: "User", + is_finished: true, + status: "IN_QUOTA", + } as any, + event: { + id: "event", + slug: "test-event", + name: { fi: "Testi", en: "Test" }, + location: "Otaniemi", + event_start_time: "2026-10-24T15:00:00Z", + event_end_time: "2026-10-24T19:00:00Z", + } as any, + quota: { id: "quota", title: { fi: "Kiintiö", en: "Quota" } } as any, + registrationSecret: { + registration_id: "registration", + update_token: "update-token", + confirmation_email_sent: false, + received_spot_from_queue_email_sent: false, + } as any, + } +} + +type Rows = ReturnType + +function fakeQuery(data: Rows) { + return jest.fn(async (sql: string, values: any[] = []) => { + const one = (row: any, key = "id") => ({ + rows: row && row[key] === values[0] ? [row] : [], + }) + if (sql.startsWith("update")) return { rows: [] } + // Every feature flag is off. + if (sql.includes("feature_enabled")) return { rows: [{ enabled: false }] } + if (sql.includes("app_private.registration_secrets")) + return one(data.registrationSecret, "registration_id") + if (sql.includes("app_public.registrations")) return one(data.registration) + if (sql.includes("app_public.events")) return one(data.event) + if (sql.includes("app_public.quotas")) return one(data.quota) + throw new Error(`Unexpected query: ${sql}`) + }) as any +} + +const { ROOT_URL } = process.env + +const baseVariables = { + url: ROOT_URL, + eventName: { fi: "Testi", en: "Test" }, + registrationName: "Test User", + registrationQuota: { fi: "Kiintiö", en: "Quota" }, + eventTime: expect.stringMatching(/^24\.10\.26 \d\d:00 - 24\.10\.26 \d\d:00$/), + eventSlug: "test-event", + eventLocation: "Otaniemi", + eventRegistrationUpdateLink: "update-registration/update-token", +} + +let consoleError: jest.SpyInstance +beforeEach(() => { + consoleError = jest.spyOn(console, "error").mockImplementation(() => {}) +}) +afterEach(() => { + consoleError.mockRestore() +}) + +it("has one contributor per email block", () => { + expect(registrationEmailContributors).toEqual([ + calendarInvitationContributor, + paymentEmailContributor, + ]) +}) + +describe("buildRegistrationEmail", () => { + it("builds the confirmation email", async () => { + const payload = await buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "confirmation", + [] + ) + expect(payload).toEqual({ + options: { + to: "tester@example.com", + subject: "Testi - Ilmoittautuminen onnistui", + }, + template: "event_registration.mjml.njk", + variables: { ...baseVariables, isWaitlisted: false }, + }) + expect(consoleError).not.toHaveBeenCalled() + }) + + it("builds the confirmation of a queued registration", async () => { + const data = rows() + data.registration.status = "IN_QUEUE" + const payload = await buildRegistrationEmail( + fakeQuery(data), + "registration", + "confirmation", + [] + ) + expect(payload!.options.subject).toBe("Testi - Ilmoittautuminen jonoon") + expect(payload!.variables.isWaitlisted).toBe(true) + data.event.name = { en: "Test" } + const english = await buildRegistrationEmail( + fakeQuery(data), + "registration", + "confirmation", + [] + ) + expect(english!.options.subject).toBe("Test - Added to waiting list") + }) + + it("reads ROOT_URL when the email is built", async () => { + const saved = process.env.ROOT_URL + process.env.ROOT_URL = "https://changed.example.com" + try { + const payload = await buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "spotFromQueue", + [] + ) + expect(payload!.variables.url).toBe("https://changed.example.com") + } finally { + process.env.ROOT_URL = saved + } + }) + + it("builds the spot from queue email", async () => { + const payload = await buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "spotFromQueue", + [] + ) + expect(payload).toEqual({ + options: { + to: "tester@example.com", + subject: "Testi - Olet saanut paikan jonosta", + }, + template: "spot_from_queue.mjml.njk", + variables: baseVariables, + }) + }) + + it("uses the English subject when the event has no Finnish name", async () => { + const data = rows() + data.event.name = { en: "Test" } + const confirmation = await buildRegistrationEmail( + fakeQuery(data), + "registration", + "confirmation", + [] + ) + const spot = await buildRegistrationEmail( + fakeQuery(data), + "registration", + "spotFromQueue", + [] + ) + expect(confirmation!.options.subject).toBe("Test - Registration successful") + expect(spot!.options.subject).toBe( + "Test - You have received a spot from the queue" + ) + }) + + it("leaves the email unchanged when contributors return {}", async () => { + const empty: RegistrationEmailContributor = async () => ({}) + const without = await buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "confirmation", + [] + ) + const withEmpty = await buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "confirmation", + [empty, empty] + ) + expect(withEmpty).toEqual(without) + expect(withEmpty).not.toHaveProperty("attachments") + }) + + it("merges contributions in list order", async () => { + const seen: RegistrationEmailContext[] = [] + const first: RegistrationEmailContributor = async (ctx) => { + seen.push(ctx) + return { + variables: { block: "first", eventSlug: "overridden" }, + attachments: [{ filename: "a.txt", content: "a" }], + } + } + const second: RegistrationEmailContributor = async () => ({ + variables: { block: "second" }, + attachments: [ + { filename: "b.ics", content: "b", contentType: "text/calendar" }, + ], + }) + const query = fakeQuery(rows()) + const payload = await buildRegistrationEmail( + query, + "registration", + "spotFromQueue", + [first, second] + ) + expect(payload!.variables).toEqual({ + ...baseVariables, + eventSlug: "overridden", + block: "second", + }) + expect(payload!.attachments).toEqual([ + { filename: "a.txt", content: "a" }, + { filename: "b.ics", content: "b", contentType: "text/calendar" }, + ]) + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + kind: "spotFromQueue", + query, + rootUrl: ROOT_URL, + registration: { id: "registration" }, + event: { id: "event" }, + quota: { id: "quota" }, + registrationSecret: { update_token: "update-token" }, + }) + }) + + it("propagates a contributor error", async () => { + const failing: RegistrationEmailContributor = async () => { + throw new Error("boom") + } + await expect( + buildRegistrationEmail( + fakeQuery(rows()), + "registration", + "confirmation", + [failing] + ) + ).rejects.toThrow("boom") + }) + + const aborts: Array< + [string, "confirmation" | "spotFromQueue", (d: Rows) => void, string] + > = [ + [ + "no registration", + "confirmation", + (d) => (d.registration = undefined), + "Registration not found; aborting", + ], + [ + "an unfinished registration", + "confirmation", + (d) => (d.registration.is_finished = false), + "Registration is not finished; aborting", + ], + [ + "no event", + "confirmation", + (d) => (d.event = undefined), + "No event found; aborting", + ], + [ + "no quota", + "confirmation", + (d) => (d.quota = undefined), + "No quota found; aborting", + ], + [ + "no secret", + "confirmation", + (d) => (d.registrationSecret = undefined), + "No registration secrets found; aborting", + ], + [ + "already sent", + "confirmation", + (d) => (d.registrationSecret.confirmation_email_sent = true), + "Confirmation email already sent; aborting", + ], + [ + "no email", + "confirmation", + (d) => (d.registration.email = null), + "No email specified; aborting", + ], + [ + "no event and no secret", + "confirmation", + (d) => { + d.event = undefined + d.registrationSecret = undefined + }, + "No event found; aborting", + ], + [ + "no secret", + "spotFromQueue", + (d) => (d.registrationSecret = undefined), + "No registration secrets found; aborting", + ], + [ + "already sent", + "spotFromQueue", + (d) => (d.registrationSecret.received_spot_from_queue_email_sent = true), + "Received spot from queue email already sent; aborting", + ], + [ + "an unfinished registration", + "spotFromQueue", + (d) => (d.registration.is_finished = false), + "Registration is not finished; aborting", + ], + [ + "no event", + "spotFromQueue", + (d) => (d.event = undefined), + "Event or quota not found; aborting", + ], + [ + "no quota", + "spotFromQueue", + (d) => (d.quota = undefined), + "Event or quota not found; aborting", + ], + [ + "no email", + "spotFromQueue", + (d) => (d.registration.email = null), + "No email specified; aborting", + ], + [ + "no event and no secret", + "spotFromQueue", + (d) => { + d.event = undefined + d.registrationSecret = undefined + }, + "No registration secrets found; aborting", + ], + ] + + it.each(aborts)("aborts on %s (%s)", async (_name, kind, mutate, message) => { + const data = rows() + mutate(data) + const contributor = jest.fn(async () => ({})) + const payload = await buildRegistrationEmail( + fakeQuery(data), + "registration", + kind, + [contributor] + ) + expect(payload).toBeNull() + expect(consoleError.mock.calls).toEqual([[message]]) + expect(contributor).not.toHaveBeenCalled() + }) + + it("ignores the other kind's sent flag", async () => { + const data = rows() + data.registrationSecret.received_spot_from_queue_email_sent = true + expect( + await buildRegistrationEmail( + fakeQuery(data), + "registration", + "confirmation", + [] + ) + ).not.toBeNull() + const other = rows() + other.registrationSecret.confirmation_email_sent = true + expect( + await buildRegistrationEmail( + fakeQuery(other), + "registration", + "spotFromQueue", + [] + ) + ).not.toBeNull() + }) + + it("fails a spot from queue job whose registration is gone", async () => { + const data = rows() + data.registration = undefined + await expect( + buildRegistrationEmail(fakeQuery(data), "registration", "spotFromQueue") + ).rejects.toThrow("Registration not found") + }) +}) + +describe("markRegistrationEmailSent", () => { + it.each([ + ["confirmation", "confirmation_email_sent"], + ["spotFromQueue", "received_spot_from_queue_email_sent"], + ] as const)("marks the %s email", async (kind, column) => { + const query = jest.fn(async () => ({ rows: [] })) + await markRegistrationEmailSent(query as any, "registration", kind) + expect(query).toHaveBeenCalledWith( + `update app_private.registration_secrets set ${column} = true where registration_id = $1`, + ["registration"] + ) + }) +}) + +describe("tasks", () => { + it.each([ + [ + "registration__send_confirmation_email", + sendConfirmationEmail, + { id: "registration" }, + "event_registration.mjml.njk", + "confirmation_email_sent", + ], + [ + "registration__process_queue", + processQueue, + { + receivedSpot: { + id: "registration", + status: "IN_QUOTA", + position: 1, + event_id: "event", + quota_id: "quota", + }, + }, + "spot_from_queue.mjml.njk", + "received_spot_from_queue_email_sent", + ], + ])( + "%s queues send_email and then marks it sent", + async (_name, task, payload, template, column) => { + const query = fakeQuery(rows()) + const addJob = jest.fn(async () => ({})) + await task(payload, { query, addJob } as any) + expect(addJob).toHaveBeenCalledTimes(1) + expect(addJob).toHaveBeenCalledWith( + "send_email", + expect.objectContaining({ template }) + ) + const update = query.mock.calls.find(([sql]: [string]) => + sql.startsWith("update") + ) + expect(update).toEqual([ + `update app_private.registration_secrets set ${column} = true where registration_id = $1`, + ["registration"], + ]) + expect(addJob.mock.invocationCallOrder[0]).toBeLessThan( + query.mock.invocationCallOrder[query.mock.calls.indexOf(update)] + ) + } + ) + + it("queues nothing when the email was already sent", async () => { + const data = rows() + data.registrationSecret.confirmation_email_sent = true + const query = fakeQuery(data) + const addJob = jest.fn() + await sendConfirmationEmail({ id: "registration" }, { + query, + addJob, + } as any) + expect(addJob).not.toHaveBeenCalled() + expect( + query.mock.calls.some(([sql]: [string]) => sql.startsWith("update")) + ).toBe(false) + }) +}) diff --git a/@app/worker/__tests__/registrationEmails.test.ts b/@app/worker/__tests__/registrationEmails.test.ts new file mode 100644 index 000000000..b14073903 --- /dev/null +++ b/@app/worker/__tests__/registrationEmails.test.ts @@ -0,0 +1,123 @@ +import { CALENDAR_INVITATION_CONTENT_TYPE } from "../src/calendarInvitation" +import promotion from "../src/tasks/registration__process_queue" +import confirmation from "../src/tasks/registration__send_confirmation_email" + +const event = { + id: "event", + slug: "event", + name: { en: "Test" }, + description: {}, + location: "Otaniemi", + event_start_time: "2026-10-24T15:00:00Z", + event_end_time: "2026-10-24T19:00:00Z", +} + +function helpers(status = "IN_QUOTA", finished = true, calendarInvites = true) { + const registration = { + id: "registration", + event_id: "event", + quota_id: "quota", + email: "tester@example.com", + first_name: "Test", + last_name: "User", + status, + is_finished: finished, + } + return { + addJob: jest.fn().mockResolvedValue(undefined), + query: jest.fn(async (sql: string) => { + if (sql.startsWith("update")) return { rows: [] } + if (sql.includes("feature_enabled")) + return { rows: [{ enabled: calendarInvites }] } + if (sql.includes("registration_secrets")) + return { + rows: [ + { + registration_id: "registration", + update_token: "private-token", + confirmation_email_sent: false, + received_spot_from_queue_email_sent: false, + }, + ], + } + if (sql.includes("app_public.registrations")) + return { rows: [registration] } + if (sql.includes("app_public.events")) return { rows: [event] } + if (sql.includes("app_public.quotas")) + return { rows: [{ id: "quota", title: { en: "Test quota" } }] } + throw new Error("Unexpected query") + }), + } +} + +const invitations = (payload: any) => + (payload.attachments ?? []).filter( + (attachment: any) => + attachment.contentType === CALENDAR_INVITATION_CONTENT_TYPE + ) + +it.each(["IN_QUOTA", "IN_OPEN_QUOTA"])( + "attaches an invitation to a %s confirmation", + async (status) => { + const context = helpers(status) + await confirmation({ id: "registration" }, context as any) + const payload = context.addJob.mock.calls[0][1] + expect(payload.template).toBe("event_registration.mjml.njk") + expect(payload.options.to).toBe("tester@example.com") + const [invitation] = invitations(payload) + expect(invitation.filename).toBe("event.ics") + expect(invitation.content).toContain("METHOD:REQUEST\r\n") + expect(payload.variables.isWaitlisted).toBe(false) + expect(payload.variables.eventRegistrationUpdateLink).toContain( + "private-token" + ) + expect(invitation.content).not.toContain("private-token") + } +) + +it("sends a waitlist confirmation without a calendar invitation", async () => { + const context = helpers("IN_QUEUE") + await confirmation({ id: "registration" }, context as any) + const payload = context.addJob.mock.calls[0][1] + expect(invitations(payload)).toEqual([]) + expect(payload.variables.isWaitlisted).toBe(true) + expect(payload.options.subject).toContain("Added to waiting list") +}) + +it("does not send a confirmation for an unfinished signup", async () => { + jest.spyOn(console, "error").mockImplementation(() => {}) + const context = helpers("IN_QUOTA", false) + await confirmation({ id: "registration" }, context as any) + expect(context.addJob).not.toHaveBeenCalled() +}) + +it("attaches an invitation when a user receives a place from the queue", async () => { + const context = helpers() + await promotion( + { receivedSpot: { id: "registration", event_id: "event" } }, + context as any + ) + const payload = context.addJob.mock.calls[0][1] + expect(payload.template).toBe("spot_from_queue.mjml.njk") + expect(invitations(payload)).toHaveLength(1) +}) + +describe("with calendar_invites off", () => { + it.each([ + ["confirmation", confirmation, { id: "registration" }], + [ + "spot from queue", + promotion, + { receivedSpot: { id: "registration", event_id: "event" } }, + ], + ])("sends the %s email without an invitation", async (_, task, payload) => { + const context = helpers("IN_QUOTA", true, false) + await task(payload as any, context as any) + const email = context.addJob.mock.calls[0][1] + expect(email).not.toHaveProperty("attachments") + expect(context.query).toHaveBeenCalledWith( + "select app_public.feature_enabled($1) as enabled", + ["calendar_invites"] + ) + }) +}) diff --git a/@app/worker/__tests__/registrationReminder.test.ts b/@app/worker/__tests__/registrationReminder.test.ts new file mode 100644 index 000000000..e1cec6b37 --- /dev/null +++ b/@app/worker/__tests__/registrationReminder.test.ts @@ -0,0 +1,112 @@ +import { sendRegistrationReminderEmail as task } from "../src/tasks/reminder__send_registration" +import sendEmail from "../src/tasks/send_email" + +jest.mock("../src/tasks/send_email", () => ({ + __esModule: true, + default: jest.fn(), +})) + +const reminder = { + id: "reminder", + language: "fi", + email: "tester@example.com", + sent_at: null, + name: { fi: "Testitapahtuma", en: "Test event" }, + slug: "test-event", + registration_start_time: "2026-10-24T15:00:00Z", + is_draft: false, + already_open: false, + too_early: false, +} + +function context(row: any = reminder) { + const client = { + query: jest.fn(async (sql: string) => ({ + rows: sql.startsWith("select r.*") ? (row ? [row] : []) : [], + })), + } + return { client, withPgClient: async (callback) => callback(client) } +} + +beforeEach(() => { + jest.clearAllMocks() + process.env.ROOT_URL = "https://example.com" + jest.mocked(sendEmail).mockResolvedValue(undefined) +}) + +it("sends the latest details in Finland time and records success", async () => { + const helpers = context() + await task({ id: reminder.id }, helpers as any) + const payload = jest.mocked(sendEmail).mock.calls[0][0] as any + expect(payload.options.to).toBe("tester@example.com") + expect(payload.variables.openingTime).toContain("18.00") + expect(payload.variables.eventName).toBe("Testitapahtuma") + expect(payload.variables.eventUrl).toBe( + "https://example.com/fi/event/test-event" + ) + expect(helpers.client.query).toHaveBeenCalledWith( + expect.stringContaining("set email_sent_at"), + [reminder.id] + ) + expect(helpers.client.query).toHaveBeenLastCalledWith("commit") +}) + +it.each([ + null, + { ...reminder, sent_at: "2026-10-24" }, + { ...reminder, is_draft: true }, + { ...reminder, already_open: true }, + { ...reminder, email: null }, +])( + "does not send cancelled, sent, hidden, expired or unverified reminders", + async (row) => { + await task({ id: reminder.id }, context(row) as any) + expect(sendEmail).not.toHaveBeenCalled() + } +) + +it("reschedules an early job after the opening time changes", async () => { + const helpers = context({ ...reminder, too_early: true }) + await task({ id: reminder.id }, helpers as any) + expect(sendEmail).not.toHaveBeenCalled() + expect(helpers.client.query).toHaveBeenCalledWith( + "select app_private.schedule_registration_reminder($1)", + [reminder.id] + ) +}) + +it("leaves the reminder unsent on delivery failure so the worker can retry", async () => { + jest.mocked(sendEmail).mockRejectedValue(new Error("SMTP unavailable")) + const helpers = context() + await expect(task({ id: reminder.id }, helpers as any)).rejects.toThrow( + "SMTP unavailable" + ) + expect(helpers.client.query).toHaveBeenLastCalledWith("rollback") + expect( + helpers.client.query.mock.calls.some(([sql]) => + sql.includes("set email_sent_at") + ) + ).toBe(false) +}) + +it("uses English content and an available event language for links", async () => { + ;(await task( + { id: reminder.id }, + context({ ...reminder, language: "en" }) as any + )) as any + const payload = jest.mocked(sendEmail).mock.calls[0][0] as any + expect(payload.options.subject).toContain("registration opens soon") + expect(payload.variables.eventUrl).toContain("/en/event/") +}) + +it("uses Helsinki winter time after the daylight saving transition", async () => { + await task( + { id: reminder.id }, + context({ + ...reminder, + registration_start_time: "2026-10-25T15:00:00Z", + }) as any + ) + const payload = jest.mocked(sendEmail).mock.calls[0][0] as any + expect(payload.variables.openingTime).toContain("17.00") +}) diff --git a/@app/worker/__tests__/reminderFeatureFlags.test.ts b/@app/worker/__tests__/reminderFeatureFlags.test.ts new file mode 100644 index 000000000..e89b6fd42 --- /dev/null +++ b/@app/worker/__tests__/reminderFeatureFlags.test.ts @@ -0,0 +1,81 @@ +import { telegramRequest } from "@app/lib/dist/cjs/telegram" + +import sendReminderEmail from "../src/tasks/reminder__send_registration" +import sendReminderTelegram from "../src/tasks/reminder__send_telegram" +import telegramReply from "../src/tasks/telegram__reply" + +import type { FeatureKey } from "@app/lib" + +jest.mock("@app/lib/dist/cjs/telegram", () => ({ + ...jest.requireActual("@app/lib/dist/cjs/telegram"), + telegramRequest: jest.fn(), +})) + +/* + * Each reminder job checks its flags when it runs. While a flag is off the + * job completes without touching the reminder (the send is not retried + * later) and without contacting Telegram. + */ + +function helpers(enabled: FeatureKey[]) { + const client = { query: jest.fn(async () => ({ rows: [] })) } + return { + job: { task_identifier: "test" }, + logger: { info: jest.fn() }, + query: jest.fn(async (_sql: string, [key]: [FeatureKey]) => ({ + rows: [{ enabled: enabled.includes(key) }], + })), + withPgClient: jest.fn(async (callback: any) => callback(client)), + client, + } +} + +beforeEach(() => { + jest.clearAllMocks() +}) + +describe("reminder__send_registration", () => { + it("does nothing while registration_reminders is off", async () => { + const context = helpers(["telegram_reminders", "calendar_invites"]) + await sendReminderEmail({ id: "reminder" }, context as any) + expect(context.query).toHaveBeenCalledWith( + "select app_public.feature_enabled($1) as enabled", + ["registration_reminders"] + ) + expect(context.withPgClient).not.toHaveBeenCalled() + }) + + it("runs while registration_reminders is on", async () => { + const context = helpers(["registration_reminders"]) + await sendReminderEmail({ id: "reminder" }, context as any) + expect(context.withPgClient).toHaveBeenCalledTimes(1) + }) +}) + +describe("reminder__send_telegram", () => { + it.each<[string, FeatureKey[]]>([ + ["both flags are off", []], + ["only registration_reminders is on", ["registration_reminders"]], + ["only telegram_reminders is on", ["telegram_reminders"]], + ])("does nothing while %s", async (_, enabled) => { + const context = helpers(enabled) + await sendReminderTelegram({ id: "reminder" }, context as any) + expect(context.withPgClient).not.toHaveBeenCalled() + expect(telegramRequest).not.toHaveBeenCalled() + }) + + it("runs while both flags are on", async () => { + const context = helpers(["registration_reminders", "telegram_reminders"]) + await sendReminderTelegram({ id: "reminder" }, context as any) + expect(context.withPgClient).toHaveBeenCalledTimes(1) + }) +}) + +describe("telegram__reply", () => { + it("does not reply while telegram_reminders is off", async () => { + const context = helpers(["registration_reminders"]) + await telegramReply({ chatId: 42, reply: "welcome" }, context as any) + expect(context.withPgClient).not.toHaveBeenCalled() + expect(telegramRequest).not.toHaveBeenCalled() + }) +}) diff --git a/@app/worker/__tests__/tasks/event__send_unpaid_on_close.test.ts b/@app/worker/__tests__/tasks/event__send_unpaid_on_close.test.ts new file mode 100644 index 000000000..1baa236e8 --- /dev/null +++ b/@app/worker/__tests__/tasks/event__send_unpaid_on_close.test.ts @@ -0,0 +1,156 @@ +import sendUnpaidOnClose from "../../src/tasks/event__send_unpaid_on_close" +import { + createPaidEvent, + deleteTestData, + insertPayment, + jobsOf, + runTask, + setFeatureFlag, + testPool, +} from "../helpers" + +beforeEach(deleteTestData) +beforeEach(async () => { + await setFeatureFlag(testPool(), "payments", "on") + await switchedOnAgo("1 day") +}) + +/** Sets when the `payments` flag was last switched, as set_feature_flag does. */ +async function switchedOnAgo(interval: string) { + await testPool().query( + "update app_public.feature_flags set updated_at = now() - $1::interval where key = 'payments'", + [interval] + ) +} + +async function closeEmailSentAt(eventId: string) { + const { + rows: [event], + } = await testPool().query( + "select unpaid_close_email_sent_at from app_public.events where id = $1", + [eventId] + ) + return event.unpaid_close_email_sent_at +} + +describe("event__send_unpaid_on_close", () => { + it("reminds every unpaid registration holding a spot, once", async () => { + // Four registrations, three spots: [paid, unpaid, unpaid, queued] + const { event, registrations } = await createPaidEvent({ + quotaSize: 3, + registrationCount: 4, + signupClosed: true, + }) + await insertPayment(registrations[0]) + + await runTask(sendUnpaidOnClose, {}) + + expect(await jobsOf("payment__send_reminder")).toEqual([ + { registrationId: registrations[1].id, closed: true }, + { registrationId: registrations[2].id, closed: true }, + ]) + expect(await closeEmailSentAt(event.id)).toBeTruthy() + + // The close email is now marked sent: the next run (a minute later) + // finds nothing to do + await runTask(sendUnpaidOnClose, {}) + expect(await jobsOf("payment__send_reminder")).toHaveLength(2) + }) + + it("sends again when registration is reopened and closes again", async () => { + const { event, registrations } = await createPaidEvent({ + quotaSize: 3, + registrationCount: 2, + signupClosed: true, + }) + await runTask(sendUnpaidOnClose, {}) + await insertPayment(registrations[0]) + + // Reopened: moving the end later clears the timestamp + await testPool().query( + `update app_public.events + set registration_end_time = now() + interval '1 day' + where id = $1`, + [event.id] + ) + expect(await closeEmailSentAt(event.id)).toBeNull() + await runTask(sendUnpaidOnClose, {}) + expect(await jobsOf("payment__send_reminder")).toHaveLength(2) + + // Closed again: only the still unpaid registration is reminded + await testPool().query( + `update app_public.events + set registration_end_time = now() - interval '1 second' + where id = $1`, + [event.id] + ) + await runTask(sendUnpaidOnClose, {}) + expect(await jobsOf("payment__send_reminder")).toEqual([ + { registrationId: registrations[0].id, closed: true }, + { registrationId: registrations[1].id, closed: true }, + { registrationId: registrations[1].id, closed: true }, + ]) + expect(await closeEmailSentAt(event.id)).toBeTruthy() + }) + + it.each([ + ["registration is still open", {}], + ["the event is free", { priceCents: 0, signupClosed: true }], + ] as const)("skips an event when %s", async (_name, options) => { + const { event } = await createPaidEvent(options) + + await runTask(sendUnpaidOnClose, {}) + + expect(await jobsOf("payment__send_reminder")).toEqual([]) + expect(await closeEmailSentAt(event.id)).toBeNull() + }) + + it("skips an event another run is handling", async () => { + const { event } = await createPaidEvent({ + signupClosed: true, + }) + // Another run holds the event's row lock (for update skip locked) + const other = await testPool().connect() + try { + await other.query("begin") + await other.query( + "select id from app_public.events where id = $1 for update", + [event.id] + ) + + await runTask(sendUnpaidOnClose, {}) + expect(await jobsOf("payment__send_reminder")).toEqual([]) + + await other.query("rollback") + } finally { + other.release() + } + await runTask(sendUnpaidOnClose, {}) + expect(await jobsOf("payment__send_reminder")).toHaveLength(1) + }) + + it("skips events that closed before the payments flag was switched on", async () => { + const { event } = await createPaidEvent({ + signupClosed: true, + }) + // Registration closed a minute ago, the flag was switched on just now + await switchedOnAgo("0 seconds") + + await runTask(sendUnpaidOnClose, {}) + + expect(await jobsOf("payment__send_reminder")).toEqual([]) + expect(await closeEmailSentAt(event.id)).toBeNull() + }) + + it("does nothing while the payments flag is off", async () => { + const { event } = await createPaidEvent({ + signupClosed: true, + }) + await setFeatureFlag(testPool(), "payments", "off") + + await runTask(sendUnpaidOnClose, {}) + + expect(await jobsOf("payment__send_reminder")).toEqual([]) + expect(await closeEmailSentAt(event.id)).toBeNull() + }) +}) diff --git a/@app/worker/__tests__/tasks/gdpr__delete_event_registrations.test.ts b/@app/worker/__tests__/tasks/gdpr__delete_event_registrations.test.ts new file mode 100644 index 000000000..c6b548d87 --- /dev/null +++ b/@app/worker/__tests__/tasks/gdpr__delete_event_registrations.test.ts @@ -0,0 +1,54 @@ +import deleteOldRegistrations from "../../src/tasks/gdpr__delete_event_registrations" +import { + createPaidEvent, + deleteTestData, + insertPayment, + paymentById, + runTask, + testPool, +} from "../helpers" + +// Never gated: this runs with the `payments` flag off, as it must. + +beforeEach(deleteTestData) + +async function moveEventEnd(eventId: string, daysAgo: number) { + await testPool().query( + `update app_public.events + set + registration_start_time = now() - interval '1 day' * ($2 + 3), + registration_end_time = now() - interval '1 day' * ($2 + 2), + event_start_time = now() - interval '1 day' * ($2 + 1), + event_end_time = now() - interval '1 day' * $2 + where id = $1`, + [eventId, daysAgo] + ) +} + +async function registrationExists(id: string) { + const { rowCount } = await testPool().query( + "select 1 from app_public.registrations where id = $1", + [id] + ) + return rowCount === 1 +} + +describe("gdpr__delete_event_registrations", () => { + it("deletes old registrations and keeps their payments", async () => { + const old = await createPaidEvent() + const recent = await createPaidEvent() + await moveEventEnd(old.event.id, 61) + await moveEventEnd(recent.event.id, 10) + const payment = await insertPayment(old.registrations[0]) + + await runTask(deleteOldRegistrations, {}) + + expect(await registrationExists(old.registrations[0].id)).toBe(false) + expect(await registrationExists(recent.registrations[0].id)).toBe(true) + // The payment is kept for bookkeeping + expect(await paymentById(payment.id)).toMatchObject({ + status: "PAID", + registration_id: null, + }) + }) +}) diff --git a/@app/worker/__tests__/tasks/payment__send_received_email.test.ts b/@app/worker/__tests__/tasks/payment__send_received_email.test.ts new file mode 100644 index 000000000..02c053627 --- /dev/null +++ b/@app/worker/__tests__/tasks/payment__send_received_email.test.ts @@ -0,0 +1,101 @@ +import dayjs from "dayjs" + +import sendReceivedEmail from "../../src/tasks/payment__send_received_email" +import sendEmail from "../../src/tasks/send_email" +import { + createPaidEvent, + deleteTestData, + getEmails, + insertPayment, + jobsOf, + runTask, + sendQueuedEmails, + testPool, +} from "../helpers" + +// Never gated: this runs with the `payments` flag off, as it must. + +beforeEach(deleteTestData) + +describe("payment__send_received_email", () => { + it("confirms a card payment with the service fee", async () => { + const { event, quota, registrations, tokens } = await createPaidEvent() + const [registration] = registrations + const payment = await insertPayment(registration) + + await runTask(sendReceivedEmail, { paymentId: payment.id }) + + const [payload] = await jobsOf("send_email") + expect(payload.options).toEqual({ + to: registration.email, + subject: `${event.name.fi} - Maksu vastaanotettu / Payment received`, + }) + expect(payload.template).toEqual("payment_received.mjml.njk") + const paidAt = dayjs(payment.paid_at).format("D.M.YYYY HH:mm") + expect(payload.variables).toMatchObject({ + eventName: event.name, + registrationName: `${registration.first_name} ${registration.last_name}`, + registrationQuota: quota.title, + eventRegistrationUpdateLink: `update-registration/${tokens[0]}`, + price: 1800, + serviceFee: 25, + total: 1825, + paidAt, + paymentMethod: "STRIPE", + }) + + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).toMatch(/^Lippu\s+18,00 €$/m) + expect(text).toMatch(/^Palvelumaksu\s+0,25 €$/m) + expect(text).toMatch(/^Yhteensä\s+18,25 €$/m) + expect(text).toMatch(new RegExp(`^Maksettu\\s+${paidAt}$`, "m")) + expect(text).toMatch(/^Service fee\s+0,25 €$/m) + expect(text).toMatch(/^Total\s+18,25 €$/m) + }) + + it("leaves the service fee out for a manual payment", async () => { + const { registrations } = await createPaidEvent() + const payment = await insertPayment(registrations[0], { method: "MANUAL" }) + + await runTask(sendReceivedEmail, { paymentId: payment.id }) + + const [payload] = await jobsOf("send_email") + expect(payload.variables).toMatchObject({ + price: 1800, + serviceFee: 0, + total: 1800, + paymentMethod: "MANUAL", + }) + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).not.toContain("Palvelumaksu") + expect(text).not.toContain("Service fee") + expect(text).toMatch(/^Yhteensä\s+18,00 €$/m) + }) + + it.each([ + [ + "deleted (undone) before the job ran", + async (registration) => { + const payment = await insertPayment(registration, { method: "MANUAL" }) + await testPool().query( + "delete from app_public.payments where id = $1", + [payment.id] + ) + return payment + }, + ], + [ + "without a registration", + (registration) => insertPayment(registration, { detached: true }), + ], + ])("skips a payment %s", async (_name, createPayment) => { + const { registrations } = await createPaidEvent() + const payment = await createPayment(registrations[0]) + + await runTask(sendReceivedEmail, { paymentId: payment.id }) + + expect(await jobsOf("send_email")).toEqual([]) + }) +}) diff --git a/@app/worker/__tests__/tasks/payment__send_reminder.test.ts b/@app/worker/__tests__/tasks/payment__send_reminder.test.ts new file mode 100644 index 000000000..a3e69228d --- /dev/null +++ b/@app/worker/__tests__/tasks/payment__send_reminder.test.ts @@ -0,0 +1,170 @@ +import sendReceivedEmail from "../../src/tasks/payment__send_received_email" +import sendReminder from "../../src/tasks/payment__send_reminder" +import sendEmail from "../../src/tasks/send_email" +import { + createPaidEvent, + deleteTestData, + getEmails, + insertPayment, + jobsOf, + runTask, + sendQueuedEmails, + setFeatureFlag, + testPool, +} from "../helpers" + +beforeEach(deleteTestData) +beforeEach(() => setFeatureFlag(testPool(), "payments", "on")) + +async function firstRegistration( + options: Parameters[0] = {} +) { + const { registrations } = await createPaidEvent(options) + return registrations[0] +} + +describe("payment__send_reminder", () => { + it("emails the payment link to an unpaid registration", async () => { + const { event, quota, registrations, tokens } = await createPaidEvent() + const [registration] = registrations + + await runTask(sendReminder, { registrationId: registration.id }) + + const [payload] = await jobsOf("send_email") + expect(payload).toEqual({ + options: { + to: registration.email, + subject: `${event.name.fi} - Maksumuistutus / Payment reminder`, + }, + template: "payment_reminder.mjml.njk", + variables: { + url: process.env.ROOT_URL, + eventName: event.name, + firstName: registration.first_name, + registrationQuota: quota.title, + price: 1800, + serviceFee: 25, + total: 1825, + payLink: `pay/${tokens[0]}`, + closed: false, + }, + }) + + await sendQueuedEmails(sendEmail) + const [email] = getEmails() + const { text } = JSON.parse(email.message) + expect(text).toContain(`Hei ${registration.first_name},`) + expect(text).toContain("Lippu 18,00 € + palvelumaksu 0,25 € = 18,25 €") + expect(text).toContain( + `Maksa 18,25 € [${process.env.ROOT_URL}/fi/pay/${tokens[0]}]` + ) + expect(text).toContain( + `Pay 18,25 € [${process.env.ROOT_URL}/en/pay/${tokens[0]}]` + ) + expect(text).not.toContain("Ilmoittautuminen on päättynyt") + }) + + it("charges the quota's current price", async () => { + const { quota, registrations } = await createPaidEvent() + await testPool().query( + "update app_public.quotas set price_cents = 2200 where id = $1", + [quota.id] + ) + + await runTask(sendReminder, { registrationId: registrations[0].id }) + + const [payload] = await jobsOf("send_email") + expect(payload.variables).toMatchObject({ price: 2200, total: 2225 }) + }) + + it("says that registration has closed in the close email", async () => { + const { registrations } = await createPaidEvent({ signupClosed: true }) + + await runTask(sendReminder, { + registrationId: registrations[0].id, + closed: true, + }) + + const [payload] = await jobsOf("send_email") + expect(payload.variables.closed).toBe(true) + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).toMatch(/^Ilmoittautuminen on päättynyt\./m) + expect(text).toMatch(/^Registration has closed\./m) + }) + + it.each([ + ["paid by card", { method: "STRIPE" as const }, 0], + ["paid by hand", { method: "MANUAL" as const }, 0], + ["whose payment attempt expired", { status: "EXPIRED" as const }, 1], + ])( + "a registration %s in the meantime gets %i reminders", + async (_name, options, reminders) => { + const registration = await firstRegistration() + await insertPayment(registration, options) + + await runTask(sendReminder, { registrationId: registration.id }) + + expect(await jobsOf("send_email")).toHaveLength(reminders) + } + ) + + it("skips a queued registration", async () => { + const { registrations } = await createPaidEvent({ + quotaSize: 1, + registrationCount: 2, + }) + + await runTask(sendReminder, { registrationId: registrations[1].id }) + + expect(await jobsOf("send_email")).toEqual([]) + }) + + it.each([ + [ + "a free quota", + async () => (await firstRegistration({ priceCents: 0 })).id, + ], + [ + "a quota made free in the meantime", + async () => { + const { quota, registrations } = await createPaidEvent() + await testPool().query( + "update app_public.quotas set price_cents = 0 where id = $1", + [quota.id] + ) + return registrations[0].id + }, + ], + [ + "a deleted registration", + async () => "00000000-0000-0000-0000-000000000000", + ], + ])("skips %s", async (_name, registrationId) => { + await runTask(sendReminder, { registrationId: await registrationId() }) + + expect(await jobsOf("send_email")).toEqual([]) + }) +}) + +// A flag closes the ways in, never the ways out: reminders stop while the +// `payments` flag is off, emails about payments already made still go out. +describe("payment emails while the payments flag is off", () => { + it("payment__send_reminder sends nothing", async () => { + const registration = await firstRegistration() + await setFeatureFlag(testPool(), "payments", "off") + + await runTask(sendReminder, { registrationId: registration.id }) + + expect(await jobsOf("send_email")).toEqual([]) + }) + + it("payment__send_received_email still sends", async () => { + const payment = await insertPayment(await firstRegistration()) + await setFeatureFlag(testPool(), "payments", "off") + + await runTask(sendReceivedEmail, { paymentId: payment.id }) + + expect(await jobsOf("send_email")).toHaveLength(1) + }) +}) diff --git a/@app/worker/__tests__/tasks/registration__process_queue.test.ts b/@app/worker/__tests__/tasks/registration__process_queue.test.ts new file mode 100644 index 000000000..22b0c086f --- /dev/null +++ b/@app/worker/__tests__/tasks/registration__process_queue.test.ts @@ -0,0 +1,84 @@ +import processQueue from "../../src/tasks/registration__process_queue" +import sendEmail from "../../src/tasks/send_email" +import { + createPaidEvent, + deleteTestData, + getEmails, + jobsOf, + runTask, + sendQueuedEmails, + setFeatureFlag, + testPool, +} from "../helpers" + +beforeEach(deleteTestData) +beforeEach(() => setFeatureFlag(testPool(), "payments", "on")) + +/** + * Deletes the first registration, so the queued second one gets the spot, + * and runs the queue job for it. + */ +async function moveUpFromQueue(options = {}) { + const data = await createPaidEvent({ + quotaSize: 1, + registrationCount: 2, + ...options, + }) + const [first, second] = data.registrations + await testPool().query("delete from app_public.registrations where id = $1", [ + first.id, + ]) + await testPool().query("delete from graphile_worker._private_jobs") + await runTask(processQueue, { + receivedSpot: { + id: second.id, + event_id: second.event_id, + quota_id: second.quota_id, + status: "IN_QUEUE", + position: 1, + }, + }) + const [payload] = await jobsOf("send_email") + return { ...data, payload, token: data.tokens[1] } +} + +const NON_PAID_VARIABLE_KEYS = [ + "eventLocation", + "eventName", + "eventRegistrationUpdateLink", + "eventSlug", + "eventTime", + "registrationName", + "registrationQuota", + "url", +] + +describe("registration__process_queue", () => { + it("adds the payment link once registration has closed", async () => { + const { payload, token } = await moveUpFromQueue({ signupClosed: true }) + + expect(payload.template).toEqual("spot_from_queue.mjml.njk") + expect(payload.variables).toMatchObject({ + price: 1800, + serviceFee: 25, + total: 1825, + payLink: `pay/${token}`, + }) + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).toContain("Maksa 18,25 €") + }) + + it.each([ + ["while registration is open", {}, false], + ["for a free quota", { priceCents: 0, signupClosed: true }, false], + ["while the payments flag is off", { signupClosed: true }, true], + ])("sends the normal email %s", async (_name, options, disable) => { + if (disable) await setFeatureFlag(testPool(), "payments", "off") + const { payload } = await moveUpFromQueue(options) + + expect(Object.keys(payload.variables).sort()).toEqual( + NON_PAID_VARIABLE_KEYS + ) + }) +}) diff --git a/@app/worker/__tests__/tasks/registration__send_confirmation_email.test.ts b/@app/worker/__tests__/tasks/registration__send_confirmation_email.test.ts new file mode 100644 index 000000000..f34544cfb --- /dev/null +++ b/@app/worker/__tests__/tasks/registration__send_confirmation_email.test.ts @@ -0,0 +1,136 @@ +import sendConfirmationEmail from "../../src/tasks/registration__send_confirmation_email" +import sendEmail, { loadTemplate } from "../../src/tasks/send_email" +import { + createPaidEvent, + deleteTestData, + getEmails, + insertPayment, + jobsOf, + runTask, + sendQueuedEmails, + setFeatureFlag, + testPool, +} from "../helpers" + +beforeEach(deleteTestData) +beforeEach(() => setFeatureFlag(testPool(), "payments", "on")) + +// The variables the task sent before payments existed +const NON_PAID_VARIABLE_KEYS = [ + "eventLocation", + "eventName", + "eventRegistrationUpdateLink", + "eventSlug", + "eventTime", + "isWaitlisted", + "registrationName", + "registrationQuota", + "url", +] + +async function confirmationPayload(registrationId: string) { + await runTask(sendConfirmationEmail, { id: registrationId }) + const [payload] = await jobsOf("send_email") + return payload +} + +describe("registration__send_confirmation_email", () => { + it("promises the payment link at the close of registration", async () => { + const { event, registrations } = await createPaidEvent() + + const payload = await confirmationPayload(registrations[0].id) + + expect(payload.variables).toMatchObject({ + price: 1800, + serviceFee: 25, + total: 1825, + isQueued: false, + }) + expect(payload.variables.payLink).toBeUndefined() + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).toContain("Maksu: maksulinkki tulee myöhemmin") + expect(text).toContain("Lippu 18,00 € + palvelumaksu 0,25 € = 18,25 €") + expect(text).toContain("Payment: link coming later") + expect(text).toContain( + `kun ilmoittautuminen sulkeutuu ${payload.variables.registrationEndDate} klo ${payload.variables.registrationEndTime}.` + ) + expect(payload.variables.registrationEndDate).toMatch(/^\d+\.\d+\.\d{4}$/) + expect(new Date(event.registration_end_time).getFullYear()).toEqual( + Number(payload.variables.registrationEndDate.split(".")[2]) + ) + expect(text).not.toContain("/pay/") + }) + + it("asks for payment when sent after registration has closed", async () => { + const { registrations, tokens } = await createPaidEvent({ + signupClosed: true, + }) + + const payload = await confirmationPayload(registrations[0].id) + + expect(payload.variables).toMatchObject({ payLink: `pay/${tokens[0]}` }) + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).toContain("Maksu: odottaa maksua") + expect(text).toContain( + `Maksa 18,25 € [${process.env.ROOT_URL}/fi/pay/${tokens[0]}]` + ) + expect(text).toContain("Payment: pending") + }) + + it("has no payment link once the registration is paid", async () => { + const { registrations } = await createPaidEvent({ signupClosed: true }) + await insertPayment(registrations[0]) + + const payload = await confirmationPayload(registrations[0].id) + + expect(payload.variables.payLink).toBeUndefined() + }) + + it("has no payment section for a queued registration", async () => { + const { registrations } = await createPaidEvent({ + quotaSize: 1, + registrationCount: 2, + }) + + const payload = await confirmationPayload(registrations[1].id) + + expect(payload.variables).toMatchObject({ isQueued: true }) + expect(payload.variables.payLink).toBeUndefined() + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).not.toContain("Maksu") + expect(text).not.toContain("Payment") + + // Renders exactly like the email of an event without payments + const render = await loadTemplate("event_registration.mjml.njk") + const nonPaidVariables = Object.fromEntries( + NON_PAID_VARIABLE_KEYS.map((key) => [key, payload.variables[key]]) + ) + expect(await render(payload.variables)).toEqual( + await render(nonPaidVariables) + ) + }) + + it.each([ + ["a free quota", { priceCents: 0 }, false], + ["a paid event while the payments flag is off", {}, true], + ])( + "sends exactly the variables of before for %s", + async (_name, options, disable) => { + const { registrations } = await createPaidEvent(options) + if (disable) await setFeatureFlag(testPool(), "payments", "off") + + const payload = await confirmationPayload(registrations[0].id) + + expect(Object.keys(payload.variables).sort()).toEqual( + NON_PAID_VARIABLE_KEYS + ) + await sendQueuedEmails(sendEmail) + const { text } = JSON.parse(getEmails()[0].message) + expect(text).not.toContain("Maksu") + expect(text).not.toContain("Payment") + } + ) +}) diff --git a/@app/worker/__tests__/telegramReminder.test.ts b/@app/worker/__tests__/telegramReminder.test.ts new file mode 100644 index 000000000..e5ec6a577 --- /dev/null +++ b/@app/worker/__tests__/telegramReminder.test.ts @@ -0,0 +1,210 @@ +import { TelegramError, telegramRequest } from "@app/lib/dist/cjs/telegram" + +import { registrationReminderTask } from "../src/tasks/reminder__send_registration" +import sendEmail from "../src/tasks/send_email" + +jest.mock("@app/lib/dist/cjs/telegram", () => ({ + ...jest.requireActual("@app/lib/dist/cjs/telegram"), + telegramRequest: jest.fn(), +})) +jest.mock("../src/tasks/send_email", () => ({ + __esModule: true, + default: jest.fn(), +})) + +const reminder = { + id: "test", + user_id: "user", + language: "fi", + bot_language: "fi", + delivery_method: "both", + name: { fi: "Testitapahtuma", en: "Test event" }, + slug: "test", + registration_start_time: "2026-10-24T15:00:00Z", + email: "test@example.com", + chat_id: "1234", +} +function context(row: any = reminder) { + const client = { + query: jest.fn(async (sql: string) => ({ + rows: sql.startsWith("select r.*") ? [row] : [], + })), + } + return { client, withPgClient: async (callback) => callback(client) } +} +beforeEach(() => { + jest.clearAllMocks() + process.env.ROOT_URL = "https://example.com" + jest.mocked(telegramRequest).mockResolvedValue({}) + jest.mocked(sendEmail).mockResolvedValue(undefined) +}) +it("sends a Telegram reminder with Finland time and an event button", async () => { + await registrationReminderTask("telegram")({ id: "test" }, context() as any) + expect(telegramRequest).toHaveBeenCalledWith( + "sendMessage", + expect.objectContaining({ + chat_id: "1234", + parse_mode: "HTML", + text: expect.stringContaining("la 24.10. klo 18.00"), + reply_markup: { + inline_keyboard: [ + [ + { + text: "Avaa tapahtuma", + url: "https://example.com/fi/event/test", + }, + ], + ], + }, + }) + ) + expect(sendEmail).not.toHaveBeenCalled() + const text = jest.mocked(telegramRequest).mock.calls[0][1].text as string + expect(text).toMatch(/^🔔 Ilmoittautumismuistutus/) + expect(text).toContain("Testitapahtuma") + expect(text).not.toContain("avautuu pian") + expect(text).not.toContain("Suomen aikaa") + expect(text).not.toContain("Muistutus ei varaa") +}) +it.each([ + { ...reminder, delivery_method: "email" }, + { ...reminder, chat_id: null }, + { ...reminder, telegram_sent_at: "2026-10-24" }, + { ...reminder, is_draft: true }, + { ...reminder, already_open: true }, +])( + "skips missing connections and ineligible or already delivered reminders", + async (row) => { + await registrationReminderTask("telegram")( + { id: "test" }, + context(row) as any + ) + expect(telegramRequest).not.toHaveBeenCalled() + } +) +it("does not resend email when retrying Telegram for a both reminder", async () => { + const row = { ...reminder, email_sent_at: "2026-10-24" } + await registrationReminderTask("email")({ id: "test" }, context(row) as any) + await registrationReminderTask("telegram")( + { id: "test" }, + context(row) as any + ) + expect(sendEmail).not.toHaveBeenCalled() + expect(telegramRequest).toHaveBeenCalledTimes(1) +}) +it("disconnects a blocked bot without endless retries", async () => { + jest.mocked(telegramRequest).mockRejectedValue(new TelegramError(403)) + const helpers = context() + await registrationReminderTask("telegram")({ id: "test" }, helpers as any) + expect(helpers.client.query).toHaveBeenCalledWith( + "select app_private.disconnect_telegram($1)", + ["user"] + ) + expect(helpers.client.query).toHaveBeenLastCalledWith("commit") +}) +it("reschedules rate-limited messages using Telegram's retry delay", async () => { + jest.mocked(telegramRequest).mockRejectedValue(new TelegramError(429, 42)) + const helpers = context() + await registrationReminderTask("telegram")({ id: "test" }, helpers as any) + expect(helpers.client.query).toHaveBeenCalledWith( + expect.stringContaining("run_at := clock_timestamp()"), + [JSON.stringify({ id: "test" }), 42, "registration-reminder:test:telegram"] + ) +}) +it("rolls back on a temporary failure so delivery can retry", async () => { + jest.mocked(telegramRequest).mockRejectedValue(new TelegramError(500)) + const helpers = context() + await expect( + registrationReminderTask("telegram")({ id: "test" }, helpers as any) + ).rejects.toThrow() + expect(helpers.client.query).toHaveBeenLastCalledWith("rollback") +}) + +it.each([ + ["en", "fi", "Registration reminder", "/en/event/test"], + ["fi", "en", "Ilmoittautumismuistutus", "/fi/event/test"], + ["auto", "fi", "Ilmoittautumismuistutus", "/fi/event/test"], + ["auto", "sv", "Registration reminder", "/en/event/test"], + [undefined, undefined, "Registration reminder", "/en/event/test"], +])( + "uses bot preference %s and detected %s instead of saved website language", + async (preference, detected, text, url) => { + await registrationReminderTask("telegram")( + { id: "test" }, + context({ + ...reminder, + bot_language: preference, + bot_detected_language: detected, + }) as any + ) + expect(telegramRequest).toHaveBeenCalledWith( + "sendMessage", + expect.objectContaining({ + text: expect.stringContaining(text), + reply_markup: { + inline_keyboard: [ + [expect.objectContaining({ url: `https://example.com${url}` })], + ], + }, + }) + ) + } +) +it("keeps email language independent from the bot preference", async () => { + await registrationReminderTask("email")( + { id: "test" }, + context({ ...reminder, bot_language: "en" }) as any + ) + expect(sendEmail).toHaveBeenCalledWith( + expect.objectContaining({ + variables: expect.objectContaining({ language: "fi" }), + }), + expect.anything() + ) +}) + +it("includes the year when the registration date is in a different year", async () => { + await registrationReminderTask("telegram")( + { id: "test" }, + context({ + ...reminder, + registration_start_time: "2027-10-24T15:00:00Z", + }) as any + ) + const text = jest.mocked(telegramRequest).mock.calls[0][1].text as string + expect(text).toContain("su 24.10.2027 klo 18.00") +}) + +it("escapes event names in Telegram HTML formatting", async () => { + await registrationReminderTask("telegram")( + { id: "test" }, + context({ + ...reminder, + name: { fi: "Rock & Roll", en: "Rock & Roll" }, + }) as any + ) + expect(telegramRequest).toHaveBeenCalledWith( + "sendMessage", + expect.objectContaining({ + parse_mode: "HTML", + text: expect.stringContaining( + "<b>Rock & Roll</b>" + ), + }) + ) +}) + +it("keeps a readable event link for local HTTP testing", async () => { + process.env.ROOT_URL = "http://localhost:5678" + await registrationReminderTask("telegram")({ id: "test" }, context() as any) + expect(telegramRequest).toHaveBeenCalledWith( + "sendMessage", + expect.objectContaining({ + parse_mode: "HTML", + text: expect.stringContaining("🔗 http://localhost:5678/fi/event/test"), + }) + ) + expect(jest.mocked(telegramRequest).mock.calls[0][1]).not.toHaveProperty( + "reply_markup" + ) +}) diff --git a/@app/worker/__tests__/telegramReply.test.ts b/@app/worker/__tests__/telegramReply.test.ts new file mode 100644 index 000000000..303ca8015 --- /dev/null +++ b/@app/worker/__tests__/telegramReply.test.ts @@ -0,0 +1,105 @@ +import { TelegramError, telegramRequest } from "@app/lib/dist/cjs/telegram" + +import { sendTelegramReply as replyTask } from "../src/tasks/telegram__reply" + +jest.mock("@app/lib/dist/cjs/telegram", () => ({ + ...jest.requireActual("@app/lib/dist/cjs/telegram"), + telegramRequest: jest.fn(), +})) + +function context(language = "auto", detected_language = "en") { + return { + withPgClient: async (callback) => + callback({ + query: jest.fn(async () => ({ + rows: [{ language, detected_language }], + })), + }), + } +} +beforeEach(() => { + jest.clearAllMocks() + jest.mocked(telegramRequest).mockResolvedValue({}) +}) +it("resolves queued replies using the current preference at delivery", async () => { + const payload = { chatId: 123, reply: "connected" } + await replyTask(payload, context("fi", "en") as any) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.objectContaining({ + text: expect.stringContaining("Telegram yhdistetty!"), + }) + ) + expect(jest.mocked(telegramRequest).mock.calls[0][1].text).toContain( + "Change language:" + ) + await replyTask(payload, context("en", "fi") as any) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.objectContaining({ + text: expect.stringContaining("Telegram connected!"), + }) + ) +}) +it("shows language buttons with stable native names and acknowledges selection", async () => { + await replyTask( + { chatId: 123, reply: "languageSaved", callbackQueryId: "callback" }, + context("fi") as any + ) + expect(telegramRequest).toHaveBeenNthCalledWith(1, "answerCallbackQuery", { + callback_query_id: "callback", + }) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.objectContaining({ + text: expect.stringContaining("Botin kieliasetus tallennettu"), + reply_markup: { + inline_keyboard: [ + [ + { text: "English", callback_data: "language:en" }, + { text: "Suomi", callback_data: "language:fi" }, + { text: "Automaattinen", callback_data: "language:auto" }, + ], + ], + }, + }) + ) +}) +it("still sends a reply if a callback acknowledgement has expired", async () => { + jest.mocked(telegramRequest).mockRejectedValueOnce(new TelegramError(400)) + await replyTask( + { chatId: 123, reply: "languageSaved", callbackQueryId: "old" }, + context() as any + ) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.anything() + ) +}) +it("automatically uses Finnish and falls back to English for unsupported languages", async () => { + await replyTask( + { chatId: 123, reply: "welcome" }, + context("auto", "fi") as any + ) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.objectContaining({ text: expect.stringContaining("Yhdistä tilisi") }) + ) + await replyTask( + { chatId: 123, reply: "welcome" }, + context("auto", "sv") as any + ) + expect(telegramRequest).toHaveBeenLastCalledWith( + "sendMessage", + expect.objectContaining({ + text: expect.stringContaining("Connect your account"), + }) + ) +}) +it("supports text-only replies already queued by older server versions", async () => { + await replyTask({ chatId: 123, text: "Already queued" }, context() as any) + expect(telegramRequest).toHaveBeenCalledWith("sendMessage", { + chat_id: 123, + text: "Already queued", + }) +}) diff --git a/@app/worker/crontab b/@app/worker/crontab index b24615f34..fcdc55265 100644 --- a/@app/worker/crontab +++ b/@app/worker/crontab @@ -15,3 +15,5 @@ # * * * * * task ?opts {payload} * * * * * gdpr__delete_event_registrations * * * * * registration__delete_unfinished_registrations +*/15 * * * * sessions__delete_inactive_mcp_sessions +* * * * * event__send_unpaid_on_close diff --git a/@app/worker/email.local.example.json b/@app/worker/email.local.example.json new file mode 100644 index 000000000..611a608f6 --- /dev/null +++ b/@app/worker/email.local.example.json @@ -0,0 +1,4 @@ +{ + "transport": "sendgrid", + "allowedRecipients": ["your-test-address@example.com"] +} diff --git a/@app/worker/jest.config.ts b/@app/worker/jest.config.ts new file mode 100644 index 000000000..9bc2d71a8 --- /dev/null +++ b/@app/worker/jest.config.ts @@ -0,0 +1,3 @@ +module.exports = { + ...require("../../jest.config.base")(__dirname), +} diff --git a/@app/worker/package.json b/@app/worker/package.json index 9408d7ae6..45408ea11 100644 --- a/@app/worker/package.json +++ b/@app/worker/package.json @@ -3,18 +3,20 @@ "private": true, "version": "0.0.0", "scripts": { - "gw": "cd dist && NODE_OPTIONS=\"-r @app/config/env.js\" graphile-worker --crontab ../crontab", + "gw": "cd dist && cross-env NODE_OPTIONS=\"-r @app/config/env.js\" graphile-worker --crontab ../crontab --max-pool-size ${WORKER_POOL_MAX:-2}", "build": "tsc -b", "start": "pnpm gw", - "dev": "cd dist && nodemon --signal SIGINT --watch '**/*.js' -x \"node --inspect -r @app/config/env.js -r source-map-support/register ../../../node_modules/graphile-worker/dist/cli.js --crontab ../crontab\"", + "dev": "cd dist && nodemon --signal SIGINT --watch '**/*.js' -x \"node --inspect -r @app/config/env.js -r source-map-support/register ../../../node_modules/graphile-worker/dist/cli.js --crontab ../crontab --max-pool-size ${WORKER_POOL_MAX:-2}\"", "watch": "exit 0", "install-db-schema": "mkdirp dist && pnpm gw --schema-only", + "test": "NODE_OPTIONS=\"-r @app/config/env.js\" NODE_ENV=test pnpm exec jest", "depcheck": "depcheck --ignores=\"tslib\"" }, "dependencies": { "@app/config": "workspace:*", "@app/lib": "workspace:*", "chalk": "^4.1.2", + "cross-env": "^7.0.3", "dayjs": "^1.11.4", "graphile-worker": "^0.16.6", "html-to-text": "^8.2.1", @@ -29,6 +31,8 @@ "@types/mjml": "^4.7.0", "@types/nodemailer": "^6.4.5", "@types/nunjucks": "^3.2.1", - "mkdirp": "^1.0.4" + "@types/pg": "^8.11.10", + "mkdirp": "^1.0.4", + "pg": "^8.7.3" } } diff --git a/@app/worker/src/calendarInvitation.ts b/@app/worker/src/calendarInvitation.ts new file mode 100644 index 000000000..e9a1a34b2 --- /dev/null +++ b/@app/worker/src/calendarInvitation.ts @@ -0,0 +1,86 @@ +import { fromEmail } from "@app/config" +import { calendarDescription, createEventCalendar } from "@app/lib" + +import { isFeatureEnabled } from "./featureFlags" + +import type { + RegistrationEmailContext, + RegistrationEmailContribution, +} from "./registrationEmail" +import type { EmailAttachment } from "./tasks/send_email" + +export interface InvitationEvent { + id: string + slug: string + name: Record + description?: Record | null + location: string + event_start_time: string | Date + event_end_time: string | Date +} + +export const CALENDAR_INVITATION_FILENAME = "event.ics" +export const CALENDAR_INVITATION_CONTENT_TYPE = "text/calendar; method=REQUEST" + +/** Statuses of a confirmed place; a queued registration gets no invitation. */ +const PLACE_STATUSES = ["IN_QUOTA", "IN_OPEN_QUOTA"] + +/** The iCalendar (METHOD:REQUEST) invitation to an event for one attendee. */ +export function registrationCalendarInvitation( + event: InvitationEvent, + recipient: string, + rootUrl: string +): EmailAttachment { + const description = event.description || {} + return { + filename: CALENDAR_INVITATION_FILENAME, + contentType: CALENDAR_INVITATION_CONTENT_TYPE, + content: createEventCalendar( + { + id: event.id, + name: + event.name.fi || event.name.en || Object.values(event.name)[0] || "", + description: calendarDescription( + description.fi || description.en || Object.values(description)[0] + ), + location: event.location || "", + start: new Date(event.event_start_time).toISOString(), + end: new Date(event.event_end_time).toISOString(), + url: new URL(`/event/${encodeURIComponent(event.slug)}`, rootUrl).href, + }, + new Date(), + { + organizer: fromEmail.match(/<([^>]+)>/)?.[1] || fromEmail, + attendee: recipient, + } + ), + } +} + +/** + * Registration email contributor: attaches a calendar invitation to the + * confirmation of a registration that has a place, and to the notice of a + * place received from the queue, while `calendar_invites` is enabled. + */ +export async function calendarInvitationContributor( + ctx: RegistrationEmailContext +): Promise { + const { kind, query, registration, event, rootUrl } = ctx + if (!rootUrl || !registration.email) { + return {} + } + if (!(await isFeatureEnabled(query, "calendar_invites"))) { + return {} + } + if ( + kind === "confirmation" && + !PLACE_STATUSES.includes(registration.status ?? "") + ) { + return {} + } + return { + attachments: [ + registrationCalendarInvitation(event, registration.email, rootUrl), + ], + } +} diff --git a/@app/worker/src/featureFlags.ts b/@app/worker/src/featureFlags.ts new file mode 100644 index 000000000..8ce74213c --- /dev/null +++ b/@app/worker/src/featureFlags.ts @@ -0,0 +1,43 @@ +import type { FeatureKey } from "@app/lib" +import type { JobHelpers, Task } from "graphile-worker" + +/** + * Runs `task` only while the feature is enabled, checked when the job runs + * rather than when it was queued. A job that runs while the feature is off + * completes without doing anything; it is not retried later. + * + * Jobs have no user session, so a flag in `admins_only` counts as off here, + * exactly as `app_public.feature_enabled()` evaluates it for an anonymous + * caller. + */ +/** + * Whether a feature is enabled, as `app_public.feature_enabled()` evaluates + * it without a user session (`admins_only` counts as off). + */ +export async function isFeatureEnabled( + query: JobHelpers["query"], + key: FeatureKey +): Promise { + const { + rows: [row], + } = await query<{ enabled: boolean }>( + "select app_public.feature_enabled($1) as enabled", + [key] + ) + return Boolean(row?.enabled) +} + +export function withFeature

( + key: FeatureKey, + task: (payload: P, helpers: JobHelpers) => ReturnType +): Task { + return async (payload, helpers) => { + if (!(await isFeatureEnabled(helpers.query, key))) { + helpers.logger.info( + `Skipping ${helpers.job.task_identifier}: feature "${key}" is off` + ) + return + } + return task(payload as P, helpers) + } +} diff --git a/@app/worker/src/localEmail.ts b/@app/worker/src/localEmail.ts new file mode 100644 index 000000000..e3747ca0b --- /dev/null +++ b/@app/worker/src/localEmail.ts @@ -0,0 +1,66 @@ +import { promises as fs } from "node:fs" +import path from "node:path" + +export interface LocalEmailSettings { + transport: "sendgrid" + allowedRecipients: string[] +} + +export function parseLocalEmailSettings(value: unknown): LocalEmailSettings { + const settings = value as LocalEmailSettings + if ( + settings?.transport !== "sendgrid" || + !Array.isArray(settings.allowedRecipients) || + settings.allowedRecipients.length === 0 || + settings.allowedRecipients.some( + (email) => + typeof email !== "string" || !/^[^\s<>@,;]+@[^\s<>@,;]+$/.test(email) + ) + ) { + throw new Error( + "Invalid email.local.json: specify sendgrid and allowedRecipients" + ) + } + return { + transport: "sendgrid", + allowedRecipients: settings.allowedRecipients.map((email) => + email.toLowerCase() + ), + } +} + +export async function getLocalEmailSettings(): Promise< + LocalEmailSettings | undefined +> { + // A developer's delivery override must never enable real email in Jest/CI. + if ( + process.env.NODE_ENV === "production" || + process.env.JEST_WORKER_ID || + process.env.IN_TESTS === "1" + ) + return + let content: string + try { + content = await fs.readFile( + path.join(__dirname, "../email.local.json"), + "utf8" + ) + } catch (error) { + if (error.code === "ENOENT") return + throw error + } + return parseLocalEmailSettings(JSON.parse(content)) +} + +export function localRecipientAllowed( + recipient: string | string[], + settings: LocalEmailSettings +) { + const recipients = Array.isArray(recipient) ? recipient : [recipient] + return ( + recipients.length > 0 && + recipients.every((email) => + settings.allowedRecipients.includes(email.trim().toLowerCase()) + ) + ) +} diff --git a/@app/worker/src/paymentEmail.ts b/@app/worker/src/paymentEmail.ts new file mode 100644 index 000000000..50944a359 --- /dev/null +++ b/@app/worker/src/paymentEmail.ts @@ -0,0 +1,72 @@ +import dayjs from "dayjs" + +import { isFeatureEnabled } from "./featureFlags" +import { + loadRegistrationPaymentState, + payLink, + ticketAmounts, +} from "./payments" + +import type { + RegistrationEmailContext, + RegistrationEmailContribution, +} from "./registrationEmail" + +/** + * Registration email contributor: the payment block of the confirmation and + * of the notice of a spot received from the queue, while `payments` is + * enabled. Empty when the quota is free, so emails of free events are + * unchanged. Amounts are cents, at the quota's current price. + * + * Payment opens when registration closes, so `payLink` is included only + * once signup has closed and the registration is unpaid; before that the + * link comes with the close email. + * + * Confirmation: amounts, `isQueued` (queued registrations get no payment + * block) and the registration end, which the email names as when the link + * arrives. + * + * Spot from the queue: amounts and `payLink`, only when the registration can + * be paid now. + */ +export async function paymentEmailContributor( + ctx: RegistrationEmailContext +): Promise { + const { kind, query, event, quota, registration, registrationSecret } = ctx + const priceCents: number = quota.price_cents ?? 0 + if (priceCents <= 0) { + return {} + } + if (!(await isFeatureEnabled(query, "payments"))) { + return {} + } + const state = await loadRegistrationPaymentState(query, registration.id) + const payable = !!state?.signup_closed && state.payment_status === "UNPAID" + const amounts = ticketAmounts(priceCents) + + if (kind === "spotFromQueue") { + if (!payable) { + return {} + } + return { + variables: { + ...amounts, + payLink: payLink(registrationSecret.update_token), + }, + } + } + + const isQueued = state?.queue_status === "IN_QUEUE" + const registrationEnd = dayjs(event.registration_end_time) + return { + variables: { + ...amounts, + isQueued, + ...(payable && !isQueued + ? { payLink: payLink(registrationSecret.update_token) } + : {}), + registrationEndDate: registrationEnd.format("D.M.YYYY"), + registrationEndTime: registrationEnd.format("HH:mm"), + }, + } +} diff --git a/@app/worker/src/payments.ts b/@app/worker/src/payments.ts new file mode 100644 index 000000000..1d8491d22 --- /dev/null +++ b/@app/worker/src/payments.ts @@ -0,0 +1,91 @@ +import { SERVICE_FEE_CENTS, totalChargeCents } from "@app/lib" +import dayjs from "dayjs" + +import type { JobHelpers } from "graphile-worker" + +/* + * Shared helpers for the payment tasks. Money is integer cents everywhere + * here; the templates format it with the `euro` filter (see send_email). + * + * Whether payments are on is the `payments` feature flag: tasks that start + * something new (reminders, the close email) run under `withFeature`, the + * registration email block checks it itself. The emails about payments + * already made are never gated. The worker never calls Stripe. + */ + +export type TranslatedField = { fi?: string; en?: string } + +/** + * The payment link of a registration, relative to `${url}/${lang}/` like + * `eventRegistrationUpdateLink`. It reuses the update token, so whoever can + * edit the registration can also pay for it. + */ +export function payLink(updateToken: string): string { + return `pay/${updateToken}` +} + +/** + * The amounts of a ticket, for the payment blocks of the emails: ticket + * price, service fee and total, in cents. + */ +export function ticketAmounts(priceCents: number) { + return { + price: priceCents, + serviceFee: SERVICE_FEE_CENTS, + total: totalChargeCents(priceCents), + } +} + +/** Email subjects use the Finnish event name, or else the English one. */ +export function subjectEventName(name: TranslatedField | null): string { + return name?.fi || name?.en || "" +} + +/** A date and time as in the designs, e.g. `17.10.2026 14:32`. */ +export function formatDateTime(date: Date | string): string { + return dayjs(date).format("D.M.YYYY HH:mm") +} + +export interface RegistrationPaymentState { + /** IN_QUOTA, IN_OPEN_QUOTA or IN_QUEUE; null if the view has no row. */ + queue_status: "IN_QUOTA" | "IN_OPEN_QUOTA" | "IN_QUEUE" | null + payment_status: "NOT_REQUIRED" | "UNPAID" | "PAID" | "PAID_MANUALLY" + signup_closed: boolean +} + +/** Queue status, payment status and whether signup has closed. */ +export async function loadRegistrationPaymentState( + query: JobHelpers["query"], + registrationId: string +): Promise { + const { + rows: [state], + } = await query>( + `select + s.status as queue_status, + app_private.registration_payment_status(r) as payment_status, + now() > e.registration_end_time as signup_closed + from app_public.registrations as r + join app_public.events as e on e.id = r.event_id + left join app_hidden.registrations_status_and_position as s on s.id = r.id + where r.id = $1`, + [registrationId] + ) + return state ?? null +} + +export interface PaymentRow { + id: string + registration_id: string | null + event_id: string | null + quota_id: string | null + event_name: TranslatedField + quota_title: TranslatedField + method: "STRIPE" | "MANUAL" + status: "PENDING" | "PAID" | "EXPIRED" + ticket_amount_cents: number + service_fee_cents: number + stripe_checkout_session_id: string | null + stripe_payment_intent_id: string | null + paid_at: Date | null +} diff --git a/@app/worker/src/registrationEmail.ts b/@app/worker/src/registrationEmail.ts new file mode 100644 index 000000000..94eb488be --- /dev/null +++ b/@app/worker/src/registrationEmail.ts @@ -0,0 +1,299 @@ +import dayjs from "dayjs" + +import { calendarInvitationContributor } from "./calendarInvitation" +import { paymentEmailContributor } from "./paymentEmail" + +import type { EmailAttachment, SendEmailPayload } from "./tasks/send_email" +import type { JobHelpers } from "graphile-worker" + +/* + * Builds the emails sent about a single registration: the confirmation after + * registering and the notice of a spot received from the queue. + * + * The builder loads the registration, its event, quota and secret once, runs + * the checks of the email kind, assembles the base payload and merges in the + * output of every contributor. A new block in these emails is a contributor + * (plus a partial in the template), not an edit to the tasks. + */ + +type Query = JobHelpers["query"] + +export type RegistrationEmailKind = "confirmation" | "spotFromQueue" + +/* Rows are `select *`; only the columns used here are typed. */ +export interface RegistrationRow { + id: string + event_id: string + quota_id: string + email: string | null + first_name: string + last_name: string + is_finished: boolean + /** `app_public.registrations_status(registration)` */ + status: string | null + [column: string]: any +} +export interface EventRow { + id: string + slug: string + name: { fi?: string; en?: string; [lang: string]: string | undefined } + location: string + event_start_time: string | Date + event_end_time: string | Date + [column: string]: any +} +export interface QuotaRow { + id: string + title: { [lang: string]: string } + [column: string]: any +} +export interface RegistrationSecretRow { + registration_id: string + update_token: string + confirmation_email_sent: boolean + received_spot_from_queue_email_sent: boolean + [column: string]: any +} + +/** Everything a contributor can read. All rows have passed the checks. */ +export interface RegistrationEmailContext { + kind: RegistrationEmailKind + query: Query + rootUrl: string | undefined + registration: RegistrationRow + event: EventRow + quota: QuotaRow + registrationSecret: RegistrationSecretRow +} + +export interface RegistrationEmailContribution { + /** Merged into the template variables, after the base variables. */ + variables?: { [varName: string]: any } + /** Appended to the email's attachments. */ + attachments?: EmailAttachment[] +} + +/** + * Adds a block to the registration emails. It checks its own flag and + * conditions, and returns `{}` when it has nothing to add, so that the email + * is unchanged. Contributors run in parallel; their output is merged in list + * order. A contributor that throws fails the job (graphile-worker retries + * it); catch inside the contributor if its block is optional. + */ +export type RegistrationEmailContributor = ( + ctx: RegistrationEmailContext +) => Promise + +/** The contributors of the registration emails, in merge order. */ +export const registrationEmailContributors: RegistrationEmailContributor[] = [ + calendarInvitationContributor, + paymentEmailContributor, +] + +export function getFormattedEventTime(event: { + event_start_time: string | Date + event_end_time: string | Date +}) { + const { event_start_time, event_end_time } = event + const formatString = "D.M.YY HH:mm" + const startTime = dayjs(event_start_time).format(formatString) + const endTime = dayjs(event_end_time).format(formatString) + return `${startTime} - ${endTime}` +} + +interface LoadedRows { + registration: RegistrationRow | undefined + event: EventRow | undefined + quota: QuotaRow | undefined + registrationSecret: RegistrationSecretRow | undefined +} + +type CheckedRows = { + [K in keyof LoadedRows]-?: NonNullable +} + +interface KindSpec { + /** Checks in order; logs and returns false to abort, or throws. */ + check(rows: LoadedRows): rows is CheckedRows + subject(rows: CheckedRows): string + /** Template variables of this kind, merged after the shared ones. */ + variables?(rows: CheckedRows): { [varName: string]: any } + template: string + /** Marks the email of this kind as sent for the registration. */ + markSentSql: string +} + +function isQueued(registration: RegistrationRow) { + return registration.status === "IN_QUEUE" +} + +function abort(message: string): false { + console.error(message) + return false +} + +const kinds: Record = { + confirmation: { + check(rows): rows is CheckedRows { + const { registration, event, quota, registrationSecret } = rows + if (!registration) return abort("Registration not found; aborting") + if (!registration.is_finished) { + return abort("Registration is not finished; aborting") + } + if (!event) return abort("No event found; aborting") + if (!quota) return abort("No quota found; aborting") + if (!registrationSecret) { + return abort("No registration secrets found; aborting") + } + if (registrationSecret.confirmation_email_sent) { + return abort("Confirmation email already sent; aborting") + } + if (!registration.email) return abort("No email specified; aborting") + return true + }, + subject: ({ event, registration }) => { + const queued = isQueued(registration) + return event.name.fi + ? `${event.name.fi} - ${queued ? "Ilmoittautuminen jonoon" : "Ilmoittautuminen onnistui"}` + : `${event.name.en} - ${queued ? "Added to waiting list" : "Registration successful"}` + }, + variables: ({ registration }) => ({ + isWaitlisted: isQueued(registration), + }), + template: "event_registration.mjml.njk", + markSentSql: + "update app_private.registration_secrets set confirmation_email_sent = true where registration_id = $1", + }, + spotFromQueue: { + check(rows): rows is CheckedRows { + const { registration, event, quota, registrationSecret } = rows + if (!registrationSecret) { + return abort("No registration secrets found; aborting") + } + if (registrationSecret.received_spot_from_queue_email_sent) { + return abort("Received spot from queue email already sent; aborting") + } + if (!registration) { + // A secret without its registration cannot exist (the foreign key + // cascades); fail the job rather than skip the email silently. + throw new Error("Registration not found") + } + if (!registration.is_finished) { + return abort("Registration is not finished; aborting") + } + if (!event || !quota) { + return abort("Event or quota not found; aborting") + } + if (!registration.email) return abort("No email specified; aborting") + return true + }, + subject: ({ event }) => + event.name.fi + ? `${event.name.fi} - Olet saanut paikan jonosta` + : `${event.name.en} - You have received a spot from the queue`, + template: "spot_from_queue.mjml.njk", + markSentSql: + "update app_private.registration_secrets set received_spot_from_queue_email_sent = true where registration_id = $1", + }, +} + +async function loadRows( + query: Query, + registrationId: string +): Promise { + const { + rows: [registration], + } = await query( + "select r.*, app_public.registrations_status(r) as status from app_public.registrations as r where r.id = $1", + [registrationId] + ) + const { + rows: [registrationSecret], + } = await query( + "select * from app_private.registration_secrets where registration_id = $1", + [registrationId] + ) + if (!registration) { + return { + registration, + event: undefined, + quota: undefined, + registrationSecret, + } + } + const { + rows: [event], + } = await query("select * from app_public.events where id = $1", [ + registration.event_id, + ]) + const { + rows: [quota], + } = await query("select * from app_public.quotas where id = $1", [ + registration.quota_id, + ]) + return { registration, event, quota, registrationSecret } +} + +/** + * Loads a registration and builds the `send_email` payload of the given kind. + * Returns null, after logging why, when the email must not be sent. + */ +export async function buildRegistrationEmail( + query: Query, + registrationId: string, + kind: RegistrationEmailKind, + contributors: RegistrationEmailContributor[] = registrationEmailContributors +): Promise { + const spec = kinds[kind] + const rows = await loadRows(query, registrationId) + if (!spec.check(rows)) { + return null + } + const { registration, event, quota, registrationSecret } = rows + const rootUrl = process.env.ROOT_URL + const ctx: RegistrationEmailContext = { + kind, + query, + rootUrl, + registration, + event, + quota, + registrationSecret, + } + + const contributions = await Promise.all(contributors.map((c) => c(ctx))) + const variables = Object.assign( + { + url: rootUrl, + eventName: event.name, + registrationName: `${registration.first_name} ${registration.last_name}`, + registrationQuota: quota.title, + eventTime: getFormattedEventTime(event), + eventSlug: event.slug, + eventLocation: event.location, + eventRegistrationUpdateLink: `update-registration/${registrationSecret.update_token}`, + ...spec.variables?.(rows), + }, + ...contributions.map((c) => c.variables) + ) + const attachments = contributions.flatMap((c) => c.attachments ?? []) + + return { + options: { + to: registration.email!, + subject: spec.subject(rows), + }, + template: spec.template, + variables, + ...(attachments.length > 0 ? { attachments } : {}), + } +} + +/** Records that the email of this kind was queued for the registration. */ +export async function markRegistrationEmailSent( + query: Query, + registrationId: string, + kind: RegistrationEmailKind +): Promise { + await query(kinds[kind].markSentSql, [registrationId]) +} diff --git a/@app/worker/src/tasks/event__send_unpaid_on_close.ts b/@app/worker/src/tasks/event__send_unpaid_on_close.ts new file mode 100644 index 000000000..14d5b6c37 --- /dev/null +++ b/@app/worker/src/tasks/event__send_unpaid_on_close.ts @@ -0,0 +1,87 @@ +import { withFeature } from "../featureFlags" + +import type { PaymentReminderPayload } from "./payment__send_reminder" +import type { Task } from "graphile-worker" + +/** + * Close-of-registration payment email, run every minute from the + * crontab. Finds paid events (a quota has a price) whose registration has + * ended and whose close email hasn't been sent, and queues a payment reminder + * (with `closed: true`) for every finished, unpaid registration holding a + * spot. This email is how participants get their payment link. + * + * Runs once per close: `unpaid_close_email_sent_at` is set in the same + * transaction that queues the reminders, and `for update skip locked` keeps + * two overlapping runs from picking the same event. Moving + * `registration_end_time` later clears it (a database trigger), so a + * reopened registration gets the email again when it closes. + * + * Does nothing while the `payments` flag is off. A send missed while it was + * off stays missed: only events whose registration closed after the flag was + * last switched (its `updated_at`) are considered, so switching payments on + * does not email people about events that closed weeks ago. + */ +const task: Task = withFeature( + "payments", + async (_payload, { withPgClient, logger }) => { + await withPgClient(async (client) => { + await client.query("begin") + try { + const { rows: events } = await client.query<{ id: string }>( + `select e.id + from app_public.events as e + where + exists( + select 1 from app_public.quotas as q + where q.event_id = e.id and q.price_cents > 0 + ) + and e.registration_end_time < now() + and e.unpaid_close_email_sent_at is null + and e.registration_end_time > ( + select f.updated_at from app_public.feature_flags as f where f.key = 'payments' + ) + order by e.registration_end_time + for update skip locked` + ) + + for (const event of events) { + await client.query( + "update app_public.events set unpaid_close_email_sent_at = now() where id = $1", + [event.id] + ) + const { rows: registrations } = await client.query<{ id: string }>( + `select r.id + from app_public.registrations as r + join app_hidden.registrations_status_and_position as s on s.id = r.id + where + r.event_id = $1 + and r.is_finished is true + and s.status in ('IN_QUOTA', 'IN_OPEN_QUOTA') + and app_private.registration_payment_status(r) = 'UNPAID' + order by r.created_at`, + [event.id] + ) + for (const registration of registrations) { + const payload: PaymentReminderPayload = { + registrationId: registration.id, + closed: true, + } + await client.query("select graphile_worker.add_job($1, $2::json)", [ + "payment__send_reminder", + JSON.stringify(payload), + ]) + } + logger.info( + `Registration closed for event ${event.id}: queued ${registrations.length} payment reminder(s)` + ) + } + await client.query("commit") + } catch (e) { + await client.query("rollback") + throw e + } + }) + } +) + +export default task diff --git a/@app/worker/src/tasks/payment__send_received_email.ts b/@app/worker/src/tasks/payment__send_received_email.ts new file mode 100644 index 000000000..e677b67ae --- /dev/null +++ b/@app/worker/src/tasks/payment__send_received_email.ts @@ -0,0 +1,103 @@ +import { formatDateTime, PaymentRow, subjectEventName } from "../payments" + +import { getFormattedEventTime } from "./registration__send_confirmation_email" + +import type { EventRow } from "../registrationEmail" +import type { SendEmailPayload } from "./send_email" +import type { Task } from "graphile-worker" + +interface PaymentReceivedEmailPayload { + paymentId: string +} + +const { ROOT_URL } = process.env + +/** + * Payment received email, sent when the webhook marks a card + * payment paid and when an organizer marks a registration paid by hand. A + * manual payment has no service fee, so its row is left out and the total is + * the ticket price. + */ +const task: Task = async (inPayload, { addJob, query, logger }) => { + const { paymentId } = inPayload as PaymentReceivedEmailPayload + + const { + rows: [payment], + } = await query( + "select * from app_public.payments where id = $1", + [paymentId] + ) + if (!payment) { + logger.error(`Payment ${paymentId} not found; aborting`) + return + } + // Undone (manual) in the meantime + if (payment.status !== "PAID") { + logger.info(`Payment ${paymentId} is ${payment.status}; not sending`) + return + } + if (!payment.registration_id) { + logger.info(`The registration of payment ${paymentId} is gone; not sending`) + return + } + + const { + rows: [registration], + } = await query("select * from app_public.registrations where id = $1", [ + payment.registration_id, + ]) + const { + rows: [event], + } = await query("select * from app_public.events where id = $1", [ + registration?.event_id, + ]) + const { + rows: [quota], + } = await query("select * from app_public.quotas where id = $1", [ + registration?.quota_id, + ]) + const { + rows: [registrationSecret], + } = await query( + "select update_token from app_private.registration_secrets where registration_id = $1", + [payment.registration_id] + ) + if (!registration || !event || !quota || !registrationSecret) { + logger.error( + `Registration, event, quota or secrets of payment ${paymentId} not found; aborting` + ) + return + } + const { email, first_name, last_name } = registration + if (!email) { + logger.error("No email specified; aborting") + return + } + + const serviceFee = payment.method === "MANUAL" ? 0 : payment.service_fee_cents + const sendEmailPayload: SendEmailPayload = { + options: { + to: email, + subject: `${subjectEventName(event.name)} - Maksu vastaanotettu / Payment received`, + }, + template: "payment_received.mjml.njk", + variables: { + url: ROOT_URL, + eventName: event.name, + registrationName: `${first_name} ${last_name}`, + registrationQuota: quota.title, + eventTime: getFormattedEventTime(event), + eventSlug: event.slug, + eventLocation: event.location, + eventRegistrationUpdateLink: `update-registration/${registrationSecret.update_token}`, + price: payment.ticket_amount_cents, + serviceFee, + total: payment.ticket_amount_cents + serviceFee, + paidAt: formatDateTime(payment.paid_at ?? new Date()), + paymentMethod: payment.method, + }, + } + await addJob("send_email", sendEmailPayload) +} + +export default task diff --git a/@app/worker/src/tasks/payment__send_reminder.ts b/@app/worker/src/tasks/payment__send_reminder.ts new file mode 100644 index 000000000..f47dd478f --- /dev/null +++ b/@app/worker/src/tasks/payment__send_reminder.ts @@ -0,0 +1,104 @@ +import { withFeature } from "../featureFlags" +import { + loadRegistrationPaymentState, + payLink, + subjectEventName, + ticketAmounts, +} from "../payments" + +import type { SendEmailPayload } from "./send_email" +import type { Task } from "graphile-worker" + +export interface PaymentReminderPayload { + registrationId: string + /** Sent by the close-of-registration job: says registration has closed. */ + closed?: boolean +} + +const { ROOT_URL } = process.env + +/** + * Payment reminder, queued by the organizers' bulk reminder + * (admin_send_payment_reminders) and by event__send_unpaid_on_close. Checks + * again when it runs, so a registration paid, made free, moved or deleted in + * the meantime gets nothing. The amounts are the quota's current price. Does + * nothing while the `payments` flag is off. + */ +const task: Task = withFeature( + "payments", + async (payload, { addJob, query, logger }) => { + const { registrationId, closed = false } = payload + + const { + rows: [registration], + } = await query("select * from app_public.registrations where id = $1", [ + registrationId, + ]) + if (!registration || !registration.is_finished) { + logger.info(`Registration ${registrationId} not found; not reminding`) + return + } + const { + rows: [event], + } = await query("select * from app_public.events where id = $1", [ + registration.event_id, + ]) + const { + rows: [quota], + } = await query("select * from app_public.quotas where id = $1", [ + registration.quota_id, + ]) + const { + rows: [registrationSecret], + } = await query( + "select update_token from app_private.registration_secrets where registration_id = $1", + [registrationId] + ) + if (!event || !quota || !registrationSecret) { + logger.error( + `Event, quota or secrets of registration ${registrationId} not found; aborting` + ) + return + } + const state = await loadRegistrationPaymentState(query, registrationId) + if (state?.payment_status !== "UNPAID") { + logger.info( + `Registration ${registrationId} is ${state?.payment_status}; not reminding` + ) + return + } + if ( + state.queue_status !== "IN_QUOTA" && + state.queue_status !== "IN_OPEN_QUOTA" + ) { + logger.info(`Registration ${registrationId} is queued; not reminding`) + return + } + + const { email, first_name } = registration + if (!email) { + logger.error("No email specified; aborting") + return + } + + const sendEmailPayload: SendEmailPayload = { + options: { + to: email, + subject: `${subjectEventName(event.name)} - Maksumuistutus / Payment reminder`, + }, + template: "payment_reminder.mjml.njk", + variables: { + url: ROOT_URL, + eventName: event.name, + firstName: first_name, + registrationQuota: quota.title, + ...ticketAmounts(quota.price_cents), + payLink: payLink(registrationSecret.update_token), + closed, + }, + } + await addJob("send_email", sendEmailPayload) + } +) + +export default task diff --git a/@app/worker/src/tasks/registration__delete_rate_limit_key.ts b/@app/worker/src/tasks/registration__delete_rate_limit_key.ts index bc7d07f8c..b7a9b7277 100644 --- a/@app/worker/src/tasks/registration__delete_rate_limit_key.ts +++ b/@app/worker/src/tasks/registration__delete_rate_limit_key.ts @@ -3,9 +3,7 @@ import Redis from "ioredis" import type { Task } from "graphile-worker" interface Payload { - eventId: string - quotaId: string - ipAddress: string + key: string } const isTest = process.env.NODE_ENV === "test" @@ -15,10 +13,7 @@ const task: Task = async (inPayload, _helpers) => { const client = new Redis(url) try { const payload: Payload = inPayload as any - const { eventId, quotaId, ipAddress } = payload - - const key = `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:${ipAddress}` - client.del(key) + await client.del(payload.key) } finally { await client.quit() } diff --git a/@app/worker/src/tasks/registration__process_queue.ts b/@app/worker/src/tasks/registration__process_queue.ts index 4ad3fa686..d4082d305 100644 --- a/@app/worker/src/tasks/registration__process_queue.ts +++ b/@app/worker/src/tasks/registration__process_queue.ts @@ -1,6 +1,8 @@ -import { getFormattedEventTime } from "./registration__send_confirmation_email" +import { + buildRegistrationEmail, + markRegistrationEmailSent, +} from "../registrationEmail" -import type { SendEmailPayload } from "./send_email" import type { RegistrationStatusAndPosition } from "@app/lib" import type { Task } from "graphile-worker" @@ -11,80 +13,21 @@ interface RegistrationProcessQueue { receivedSpot: RegistrationStatusAndPosition } -const { ROOT_URL } = process.env - const task: Task = async (inPayload, { addJob, query }) => { const payload: RegistrationProcessQueue = inPayload as any const { receivedSpot } = payload - const { - rows: [registrationSecret], - } = await query( - "select * from app_private.registration_secrets where registration_id = $1", - [receivedSpot.id] - ) - - if (!registrationSecret) { - console.error("No registration secrets found; aborting") - return - } - - if (registrationSecret.received_spot_from_queue_email_sent) { - console.error("Received spot from queue email already sent; aborting") - return - } - - const { - rows: [registration], - } = await query("select * from app_public.registrations where id = $1", [ + const email = await buildRegistrationEmail( + query, receivedSpot.id, - ]) - const { - rows: [event], - } = await query("select * from app_public.events where id = $1", [ - receivedSpot.event_id, - ]) - const { - rows: [quota], - } = await query("select * from app_public.quotas where id = $1", [ - receivedSpot.quota_id, - ]) - if (!event || !quota) { - console.error("Event or quota not found; aborting") - return - } - const { email, first_name, last_name } = registration - + "spotFromQueue" + ) if (!email) { - console.error("No email specified; aborting") return } - const sendEmailPayload: SendEmailPayload = { - options: { - to: email, - subject: event.name.fi - ? `${event.name.fi} - Olet saanut paikan jonosta` - : `${event.name.en} - You have received a spot from the queue`, - }, - template: "spot_from_queue.mjml.njk", - variables: { - url: ROOT_URL, - eventName: event.name, - registrationName: `${first_name} ${last_name}`, - registrationQuota: quota.title, - eventTime: getFormattedEventTime(event), - eventSlug: event.slug, - eventLocation: event.location, - eventRegistrationUpdateLink: `update-registration/${registrationSecret.update_token}`, - }, - } - - await addJob("send_email", sendEmailPayload) - await query( - "update app_private.registration_secrets set received_spot_from_queue_email_sent = true where registration_id = $1", - [receivedSpot.id] - ) + await addJob("send_email", email) + await markRegistrationEmailSent(query, receivedSpot.id, "spotFromQueue") } export default task diff --git a/@app/worker/src/tasks/registration__send_confirmation_email.ts b/@app/worker/src/tasks/registration__send_confirmation_email.ts index 281ab9b4c..768992580 100644 --- a/@app/worker/src/tasks/registration__send_confirmation_email.ts +++ b/@app/worker/src/tasks/registration__send_confirmation_email.ts @@ -1,8 +1,12 @@ -import dayjs from "dayjs" +import { + buildRegistrationEmail, + markRegistrationEmailSent, +} from "../registrationEmail" -import type { SendEmailPayload } from "./send_email" import type { Task } from "graphile-worker" +export { getFormattedEventTime } from "../registrationEmail" + interface RegistrationSendConfirmationEmail { /** * registration id @@ -10,100 +14,21 @@ interface RegistrationSendConfirmationEmail { id: string } -const { ROOT_URL } = process.env - -export function getFormattedEventTime(event: any) { - const { event_start_time, event_end_time } = event - const formatString = "D.M.YY HH:mm" - const startTime = dayjs(event_start_time).format(formatString) - const endTime = dayjs(event_end_time).format(formatString) - return `${startTime} - ${endTime}` -} - const task: Task = async (inPayload, { addJob, query }) => { const payload: RegistrationSendConfirmationEmail = inPayload as any const { id: registrationId } = payload - const { - rows: [registration], - } = await query("select * from app_public.registrations where id = $1", [ - registrationId, - ]) - if (!registration) { - console.error("Registration not found; aborting") - return - } - const { - rows: [event], - } = await query("select * from app_public.events where id = $1", [ - registration.event_id, - ]) - - if (!event) { - console.error("No event found; aborting") - return - } - - const { - rows: [quota], - } = await query("select * from app_public.quotas where id = $1", [ - registration.quota_id, - ]) - - if (!quota) { - console.error("No quota found; aborting") - return - } - - const { - rows: [registrationSecret], - } = await query( - "select * from app_private.registration_secrets where registration_id = $1", - [registration.id] + const email = await buildRegistrationEmail( + query, + registrationId, + "confirmation" ) - - if (!registrationSecret) { - console.error("No registration secrets found; aborting") - return - } - - if (registrationSecret.confirmation_email_sent) { - console.error("Confirmation email already sent; aborting") - return - } - - const { email, first_name, last_name } = registration - if (!email) { - console.error("No email specified; aborting") return } - const sendEmailPayload: SendEmailPayload = { - options: { - to: email, - subject: event.name.fi - ? `${event.name.fi} - Rekisteröinti onnnistui` - : `${event.name.en} - Registration successful`, - }, - template: "event_registration.mjml.njk", - variables: { - url: ROOT_URL, - eventName: event.name, - registrationName: `${first_name} ${last_name}`, - registrationQuota: quota.title, - eventTime: getFormattedEventTime(event), - eventSlug: event.slug, - eventLocation: event.location, - eventRegistrationUpdateLink: `update-registration/${registrationSecret.update_token}`, - }, - } - - await addJob("send_email", sendEmailPayload) - await query( - "update app_private.registration_secrets set confirmation_email_sent = true where registration_id = $1", - [registrationId] - ) + await addJob("send_email", email) + await markRegistrationEmailSent(query, registrationId, "confirmation") } export default task diff --git a/@app/worker/src/tasks/reminder__send_registration.ts b/@app/worker/src/tasks/reminder__send_registration.ts new file mode 100644 index 000000000..51bc3a2c4 --- /dev/null +++ b/@app/worker/src/tasks/reminder__send_registration.ts @@ -0,0 +1,235 @@ +import { + resolveTelegramLanguage, + TelegramError, + telegramRequest, +} from "@app/lib/dist/cjs/telegram" + +import { withFeature } from "../featureFlags" + +import sendEmail from "./send_email" + +import type { Task } from "graphile-worker" + +function telegramHtml(text: string) { + return text.replace(/&/g, "&").replace(//g, ">") +} + +function formatOpeningTime(date: Date, language: "fi" | "en") { + const timeZone = "Europe/Helsinki" + const year = new Intl.DateTimeFormat("en", { + timeZone, + year: "numeric", + }).format(date) + const currentYear = new Intl.DateTimeFormat("en", { + timeZone, + year: "numeric", + }).format(new Date()) + const parts = new Intl.DateTimeFormat(language === "fi" ? "fi-FI" : "en-GB", { + timeZone, + weekday: "short", + day: "numeric", + month: language === "fi" ? "numeric" : "short", + ...(year !== currentYear ? { year: "numeric" as const } : {}), + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(date) + const value = (type: Intl.DateTimeFormatPartTypes) => + parts.find((part) => part.type === type)?.value ?? "" + + if (language === "fi") { + const yearSuffix = year !== currentYear ? `.${year}` : "" + const separator = year !== currentYear ? " klo " : ". klo " + return `${value("weekday").replace(/\.$/, "")} ${value("day")}.${value("month")}${yearSuffix}${separator}${value("hour")}.${value("minute")}` + } + + const yearSuffix = year !== currentYear ? ` ${year}` : "" + return `${value("weekday")} ${value("day")} ${value("month")}${yearSuffix} at ${value("hour")}:${value("minute")}` +} + +export function registrationReminderTask(channel: "email" | "telegram"): Task { + return async (payload, { withPgClient }) => { + const { id } = payload as { id: string } + await withPgClient(async (client) => { + await client.query("begin") + try { + // Serialize retries/cancellation for this reminder. Holding a shared event + // lock keeps its opening time stable while deciding and sending. + const { + rows: [reminder], + } = await client.query( + `select r.*, e.name, e.slug, e.registration_start_time, e.is_draft, + e.registration_start_time <= clock_timestamp() as already_open, + e.registration_start_time - make_interval(mins => r.minutes_before) > clock_timestamp() as too_early, + (select language from app_private.telegram_preferences p + join app_public.telegram_accounts a on a.chat_id = p.chat_id where a.user_id = r.user_id) as bot_language, + (select detected_language from app_private.telegram_preferences p + join app_public.telegram_accounts a on a.chat_id = p.chat_id where a.user_id = r.user_id) as bot_detected_language, + (select chat_id from app_public.telegram_accounts where user_id = r.user_id) as chat_id, + (select email from app_public.user_emails + where user_id = r.user_id and is_primary and is_verified) as email + from app_public.event_registration_reminders r + join app_public.events e on e.id = r.event_id + where r.id = $1 for update of r for share of e`, + [id] + ) + if ( + !reminder || + reminder.sent_at || + reminder.is_draft || + reminder.already_open || + (channel === "email" && + (reminder.delivery_method === "telegram" || + reminder.email_sent_at || + !reminder.email)) || + (channel === "telegram" && + (reminder.delivery_method === "email" || + reminder.telegram_sent_at || + !reminder.chat_id)) + ) { + await client.query("commit") + return + } + if (reminder.too_early) { + await client.query( + "select app_private.schedule_registration_reminder($1)", + [id] + ) + await client.query("commit") + return + } + const language = + channel === "telegram" + ? resolveTelegramLanguage({ + language: reminder.bot_language, + detected_language: reminder.bot_detected_language, + }) + : reminder.language === "en" + ? "en" + : "fi" + const name = + reminder.name[language] || reminder.name.fi || reminder.name.en || "" + const openingTime = new Intl.DateTimeFormat( + language === "fi" ? "fi-FI" : "en-GB", + { + timeZone: "Europe/Helsinki", + dateStyle: "full", + timeStyle: "short", + } + ).format(new Date(reminder.registration_start_time)) + const telegramOpeningTime = formatOpeningTime( + new Date(reminder.registration_start_time), + language + ) + const rootUrl = process.env.ROOT_URL + if (!rootUrl) + throw new Error("ROOT_URL is required for registration reminders") + const eventLanguage = reminder.name[language] + ? language + : reminder.name.fi + ? "fi" + : "en" + const eventUrl = new URL( + `/${eventLanguage}/event/${encodeURIComponent(reminder.slug)}`, + rootUrl + ).href + if (channel === "email") { + await sendEmail( + { + options: { + to: reminder.email, + subject: + language === "fi" + ? `${name} – ilmoittautuminen avautuu pian` + : `${name} – registration opens soon`, + }, + template: "registration_reminder.mjml.njk", + variables: { language, eventName: name, openingTime, eventUrl }, + }, + {} as any + ) + } else { + try { + const text = + language === "fi" + ? `🔔 Ilmoittautumismuistutus\n\n${telegramHtml(name)}\n📅 Ilmoittautuminen alkaa ${telegramHtml(telegramOpeningTime)}.` + : `🔔 Registration reminder\n\n${telegramHtml(name)}\n📅 Registration opens ${telegramHtml(telegramOpeningTime)}.` + await telegramRequest("sendMessage", { + chat_id: reminder.chat_id, + parse_mode: "HTML", + text, + // Telegram rejects local/private URLs in inline buttons. A plain link + // also makes the same reminder usable during local testing. + ...(new URL(eventUrl).protocol === "https:" + ? { + reply_markup: { + inline_keyboard: [ + [ + { + text: + language === "fi" + ? "Avaa tapahtuma" + : "Open event", + url: eventUrl, + }, + ], + ], + }, + } + : { + text: `${text}\n\n🔗 ${telegramHtml(eventUrl)}`, + }), + }) + // The shared Graphile queue serializes Telegram deliveries; stay below + // Telegram's free broadcast limit even when many reminders become due. + await new Promise((resolve) => setTimeout(resolve, 50)) + } catch (error) { + if (error instanceof TelegramError && error.code === 403) { + await client.query("select app_private.disconnect_telegram($1)", [ + reminder.user_id, + ]) + await client.query("commit") + return + } + if (error instanceof TelegramError && error.code === 429) { + await client.query( + "select graphile_worker.add_job('reminder__send_telegram', $1::json, run_at := clock_timestamp() + make_interval(secs => $2), job_key := $3, queue_name := 'telegram-reminders')", + [ + JSON.stringify({ id }), + error.retryAfter || 60, + `registration-reminder:${id}:telegram`, + ] + ) + await client.query("commit") + return + } + throw error + } + } + // Each channel commits its own checkpoint. Retrying the other channel + // cannot resend a successfully recorded delivery. + const column = + channel === "email" ? "email_sent_at" : "telegram_sent_at" + await client.query( + `update app_public.event_registration_reminders set ${column} = clock_timestamp(), + sent_at = case when delivery_method <> 'both' or ${channel === "email" ? "telegram_sent_at" : "email_sent_at"} is not null then clock_timestamp() else null end + where id = $1`, + [id] + ) + await client.query("commit") + } catch (error) { + await client.query("rollback") + throw error + } + }) + } +} + +/** Sends the email of a registration reminder, whatever the flags. */ +export const sendRegistrationReminderEmail = registrationReminderTask("email") + +// A reminder that comes due while the feature is off is not sent later. +export default withFeature( + "registration_reminders", + sendRegistrationReminderEmail +) diff --git a/@app/worker/src/tasks/reminder__send_telegram.ts b/@app/worker/src/tasks/reminder__send_telegram.ts new file mode 100644 index 000000000..40fc6bb5f --- /dev/null +++ b/@app/worker/src/tasks/reminder__send_telegram.ts @@ -0,0 +1,14 @@ +import { withFeature } from "../featureFlags" + +import { registrationReminderTask } from "./reminder__send_registration" + +/** Sends the Telegram message of a registration reminder, whatever the flags. */ +export const sendRegistrationReminderTelegram = + registrationReminderTask("telegram") + +// Telegram reminders are registration reminders: both flags must be on. A +// reminder that comes due while either is off is not sent later. +export default withFeature( + "registration_reminders", + withFeature("telegram_reminders", sendRegistrationReminderTelegram) +) diff --git a/@app/worker/src/tasks/send_email.ts b/@app/worker/src/tasks/send_email.ts index 308927b97..ebb28fbdd 100644 --- a/@app/worker/src/tasks/send_email.ts +++ b/@app/worker/src/tasks/send_email.ts @@ -3,12 +3,14 @@ import { fromEmail, projectName, } from "@app/config" +import { formatEuro } from "@app/lib" import chalk from "chalk" import html2text from "html-to-text" import mjml2html from "mjml" import nodemailer from "nodemailer" import nunjucks from "nunjucks" +import { getLocalEmailSettings, localRecipientAllowed } from "../localEmail" import getTransport from "../transport" import type { Task } from "graphile-worker" @@ -22,10 +24,23 @@ global.TEST_EMAILS = [] const njk = new nunjucks.Environment( new nunjucks.FileSystemLoader(`${__dirname}/../../../worker/templates/`) ) +// Money is integer cents in template variables; `{{ total | euro }}` -> 18,25 € +njk.addFilter("euro", (cents: number) => formatEuro(cents)) const isTest = process.env.NODE_ENV === "test" const isDev = process.env.NODE_ENV !== "production" +/** + * A nodemailer attachment that survives the JSON job payload: `content` is a + * string, base64 encoded when `encoding` is "base64". + */ +export interface EmailAttachment { + filename: string + content: string + contentType?: string + encoding?: "base64" | "utf8" +} + export interface SendEmailPayload { options: { from?: string @@ -36,15 +51,24 @@ export interface SendEmailPayload { variables: { [varName: string]: any } + attachments?: EmailAttachment[] } const task: Task = async (inPayload) => { const payload: SendEmailPayload = inPayload as any + const { options: inOptions, template, variables, attachments } = payload + const localSettings = await getLocalEmailSettings() + if (localSettings && !localRecipientAllowed(inOptions.to, localSettings)) { + console.log( + "Skipped local email: recipient is outside the delivery allowlist." + ) + return + } const transport = await getTransport() - const { options: inOptions, template, variables } = payload const options = { from: fromEmail, ...inOptions, + ...(attachments ? { attachments } : {}), } if (template) { const templateFn = await loadTemplate(template) @@ -54,11 +78,16 @@ const task: Task = async (inPayload) => { .fromString(html2textableHtml, { wordwrap: 120, tags: { img: { format: "skip" } }, + // Amount tables of the payment emails (payment_macros.njk) + tables: [".amounts"], }) .replace(/\n\s+\n/g, "\n\n") Object.assign(options, { html, text }) } const info = await transport.sendMail(options) + if (localSettings) { + console.log(`Local email accepted by SendGrid: ${info.messageId}`) + } if (isTest) { global.TEST_EMAILS.push(info) } else if (isDev) { diff --git a/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts b/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts new file mode 100644 index 000000000..b85464758 --- /dev/null +++ b/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts @@ -0,0 +1,16 @@ +import type { Task } from "graphile-worker" + +// An MCP session is recreated from the next valid access token, so deleting an +// idle one costs nothing but a row insert. +const INACTIVITY_TIMEOUT_MINUTES = 60 + +const task: Task = async (_, { query }) => { + await query( + `delete from app_private.sessions + where kind = 'mcp' + and last_active < now() - interval '1 minute' * $1`, + [INACTIVITY_TIMEOUT_MINUTES] + ) +} + +export default task diff --git a/@app/worker/src/tasks/telegram__reply.ts b/@app/worker/src/tasks/telegram__reply.ts new file mode 100644 index 000000000..a66e46f9d --- /dev/null +++ b/@app/worker/src/tasks/telegram__reply.ts @@ -0,0 +1,56 @@ +import { + resolveTelegramLanguage, + TelegramError, + telegramLanguageKeyboard, + TelegramReply, + telegramReplyText, + telegramRequest, +} from "@app/lib/dist/cjs/telegram" + +import { withFeature } from "../featureFlags" + +import type { Task } from "graphile-worker" + +/** Sends a bot reply, whatever the flags. */ +export const sendTelegramReply: Task = async (payload, { withPgClient }) => { + // A job carries a ready `text`, or a `reply` translated at delivery time. + const { chatId, text, reply, callbackQueryId } = payload as { + chatId: number + text?: string + reply?: TelegramReply + callbackQueryId?: string + } + try { + if (callbackQueryId) { + try { + await telegramRequest("answerCallbackQuery", { + callback_query_id: callbackQueryId, + }) + } catch (error) { + // Callback acknowledgements expire; a retry must still deliver the reply. + if (!(error instanceof TelegramError && error.code === 400)) throw error + } + } + const language = await withPgClient(async (client) => { + const { + rows: [preferences], + } = await client.query( + "select language, detected_language from app_private.telegram_preferences where chat_id = $1", + [chatId] + ) + return resolveTelegramLanguage(preferences) + }) + await telegramRequest("sendMessage", { + chat_id: chatId, + text: reply ? telegramReplyText(reply, language) : text, + ...(reply === "languageMenu" || reply === "languageSaved" + ? { reply_markup: telegramLanguageKeyboard(language) } + : {}), + }) + await new Promise((resolve) => setTimeout(resolve, 50)) + } catch (error) { + if (error instanceof TelegramError && error.code === 403) return + throw error + } +} +export default withFeature("telegram_reminders", sendTelegramReply) diff --git a/@app/worker/src/transport.ts b/@app/worker/src/transport.ts index 107f65320..e7449207d 100644 --- a/@app/worker/src/transport.ts +++ b/@app/worker/src/transport.ts @@ -2,6 +2,8 @@ import chalk from "chalk" import { promises as fsp } from "node:fs" import nodemailer from "nodemailer" +import { getLocalEmailSettings } from "./localEmail" + const { readFile, writeFile } = fsp const isTest = process.env.NODE_ENV === "test" @@ -15,6 +17,27 @@ let logged = false export default function getTransport(): Promise { if (!transporterPromise) { transporterPromise = (async () => { + const localSettings = await getLocalEmailSettings() + if (!isDev || localSettings?.transport === "sendgrid") { + const { SENDGRID_API_KEY, SENDGRID_USERNAME } = process.env + if (!SENDGRID_USERNAME || !SENDGRID_API_KEY) { + throw new Error("SendGrid credentials are not configured") + } + if (localSettings) { + console.log( + "Local SendGrid delivery enabled for allowed recipients only." + ) + } + return nodemailer.createTransport({ + host: "smtp.sendgrid.net", + port: 465, + secure: true, + connectionTimeout: 15000, + greetingTimeout: 15000, + socketTimeout: 30000, + auth: { user: SENDGRID_USERNAME, pass: SENDGRID_API_KEY }, + }) + } if (isTest) { return nodemailer.createTransport({ jsonTransport: true, @@ -52,24 +75,8 @@ export default function getTransport(): Promise { pass: account.pass, }, }) - } else { - const { SENDGRID_API_KEY, SENDGRID_USERNAME } = process.env - if (!SENDGRID_USERNAME) { - throw new Error("Misconfiguration: no SENDGRID_USERNAME") - } - if (!SENDGRID_API_KEY) { - throw new Error("Misconfiguration: no SENDGRID_API_KEY") - } - return nodemailer.createTransport({ - host: "smtp.sendgrid.net", - port: 465, - secure: true, - auth: { - user: SENDGRID_USERNAME, - pass: SENDGRID_API_KEY, - }, - }) } + throw new Error("Email transport is not configured") })() } return transporterPromise! diff --git a/@app/worker/templates/event_registration.mjml.njk b/@app/worker/templates/event_registration.mjml.njk index 9c7a1c708..9ec64cd60 100644 --- a/@app/worker/templates/event_registration.mjml.njk +++ b/@app/worker/templates/event_registration.mjml.njk @@ -2,7 +2,14 @@ {% block content %} + {% if isWaitlisted %} + + Olet tällä hetkellä tapahtuman jonossa. Lähetämme sinulle vahvistusviestin, + kun saat paikan tapahtumaan. + + {% else %} Ilmoittautuminen tapahtumaan onnistui: + {% endif %} - Nimi: {{ registrationName }}
- Kiintiö: {{ registrationQuota.fi }}
@@ -12,13 +19,32 @@ - Linkki tapahtumaan: {{ url }}/fi/event/{{ eventSlug }}
+ {%- if price and not isQueued %} + {%- from "payment_macros.njk" import paymentBox, payButton %} + {% call paymentBox() %} + {% if payLink %}Maksu: odottaa maksua{% else %}Maksu: maksulinkki tulee myöhemmin{% endif %}
+ Lippu {{ price | euro }} + palvelumaksu {{ serviceFee | euro }} = {{ total | euro }} + {% if payLink %} + {{ payButton(url + "/fi/" + payLink, "Maksa " + (total | euro)) }} + {% else %} +
Lähetämme maksulinkin sähköpostiisi, kun ilmoittautuminen sulkeutuu{% if registrationEndDate %} {{ registrationEndDate }} klo {{ registrationEndTime }}{% endif %}. + {% endif %} + {% endcall %} + {%- endif %} Voit muokata tietojasi tai poistaa ilmoittautumisesi tämän linkin takaa: {{ url }}/fi/{{ eventRegistrationUpdateLink }} + {% if isWaitlisted %} + + You're currently on the waiting list. We'll send you a confirmation email + when a place becomes available for you. + + {% else %} Successfully registered to the event: + {% endif %} - Name: {{ registrationName }}
- Quota: {{ registrationQuota.en }}
@@ -28,6 +54,18 @@ - Link to the event: {{ url }}/en/event/{{ eventSlug }}
+ {%- if price and not isQueued %} + {%- from "payment_macros.njk" import paymentBox, payButton %} + {% call paymentBox() %} + {% if payLink %}Payment: pending{% else %}Payment: link coming later{% endif %}
+ Ticket {{ price | euro }} + service fee {{ serviceFee | euro }} = {{ total | euro }} + {% if payLink %} + {{ payButton(url + "/en/" + payLink, "Pay " + (total | euro)) }} + {% else %} +
We'll email you a payment link when registration closes{% if registrationEndDate %} on {{ registrationEndDate }} at {{ registrationEndTime }}{% endif %}. + {% endif %} + {% endcall %} + {%- endif %} You can update or delete your registration via this link: {{ url }}/en/{{ eventRegistrationUpdateLink }} diff --git a/@app/worker/templates/payment_macros.njk b/@app/worker/templates/payment_macros.njk new file mode 100644 index 000000000..f41a506c1 --- /dev/null +++ b/@app/worker/templates/payment_macros.njk @@ -0,0 +1,61 @@ +{# + Building blocks for the payment sections of the emails (boards 12–15). + Not an email itself: the admin Emails page lists only *.mjml.njk files. + + Amounts are integer cents; the `euro` filter formats them (18,25 €). + Everything here is plain HTML inside an , built from tables so it + holds up in email clients. +#} + +{# A bordered box. `tone` is "info" (blue, pay) or "success" (green, paid). #} +{% macro paymentBox(tone="info") %} + + + + + +
+ {{ caller() }} +
+
+{% endmacro %} + +{# The "Pay 18,25 €" button, linking to the /pay page. #} +{% macro payButton(href, label) %} + + + + +
+ {{ label }} +
+{% endmacro %} + +{# + A table of label / amount rows, filled with amountRow. The "amounts" class + makes the plain text version lay it out as a table too. +#} +{% macro amountTable() %} + + {{ caller() }} + +{% endmacro %} + +{% macro amountRow(label, value, strong=false, muted=false) %} + + {% if strong %}{{ label }}{% else %}{{ label }}{% endif %} + {% if strong %}{{ value }}{% else %}{{ value }}{% endif %} + +{% endmacro %} + +{# A small grey note under a box. #} +{% macro note() %} +{{ caller() }} +{% endmacro %} + +{# The event name in the blue band at the top. #} +{% macro eventHeader(eventName) %} + + {{ eventName.fi or eventName.en }} + +{% endmacro %} diff --git a/@app/worker/templates/payment_received.mjml.njk b/@app/worker/templates/payment_received.mjml.njk new file mode 100644 index 000000000..b6c9d3bce --- /dev/null +++ b/@app/worker/templates/payment_received.mjml.njk @@ -0,0 +1,58 @@ +{% extends "base.mjml.njk" %} +{% from "payment_macros.njk" import eventHeader, paymentBox, amountTable, amountRow %} + +{# + Payment received. Sent when a card payment is confirmed by + Stripe and when an organizer marks a registration paid by hand. A manual + payment has no service fee: leave serviceFee out (or 0) and total equals + the ticket price. + Amounts are cents: price, serviceFee, total. +#} + +{% block headerContent %} +{{ eventHeader(eventName) }} +{% endblock %} + +{% block content %} + + Maksusi on vastaanotettu. Nähdään tapahtumassa! + + - Nimi: {{ registrationName }}
+ - Kiintiö: {{ registrationQuota.fi }}
+ - Ajankohta: {{ eventTime }}
+ - Paikka: {{ eventLocation }}
+
+ {% call paymentBox("success") %} + {% call amountTable() %} + {{ amountRow("Lippu", price | euro) }} + {% if serviceFee %}{{ amountRow("Palvelumaksu", serviceFee | euro) }}{% endif %} + {{ amountRow("Yhteensä", total | euro, strong=true) }} + {{ amountRow("Maksettu", paidAt, muted=true) }} + {% endcall %} + {% endcall %} + + Voit muokata tietojasi tai poistaa ilmoittautumisesi tämän linkin takaa: + {{ url }}/fi/{{ eventRegistrationUpdateLink }} + + + Your payment has been received. See you at the event! + + - Name: {{ registrationName }}
+ - Quota: {{ registrationQuota.en }}
+ - Event time: {{ eventTime }}
+ - Event location: {{ eventLocation }}
+
+ {% call paymentBox("success") %} + {% call amountTable() %} + {{ amountRow("Ticket", price | euro) }} + {% if serviceFee %}{{ amountRow("Service fee", serviceFee | euro) }}{% endif %} + {{ amountRow("Total", total | euro, strong=true) }} + {{ amountRow("Paid", paidAt, muted=true) }} + {% endcall %} + {% endcall %} + + You can update or delete your registration via this link: + {{ url }}/en/{{ eventRegistrationUpdateLink }} + +
+{% endblock %} diff --git a/@app/worker/templates/payment_reminder.mjml.njk b/@app/worker/templates/payment_reminder.mjml.njk new file mode 100644 index 000000000..892b20eda --- /dev/null +++ b/@app/worker/templates/payment_reminder.mjml.njk @@ -0,0 +1,43 @@ +{% extends "base.mjml.njk" %} +{% from "payment_macros.njk" import eventHeader, paymentBox, payButton, note %} + +{# + Payment reminder. Sent by the organizers' "Send reminder to all + unpaid" action and, with `closed`, by the automatic email when + registration closes. + Amounts are cents: price, serviceFee, total. +#} + +{% block headerContent %} +{{ eventHeader(eventName) }} +{% endblock %} + +{% block content %} + + {% if closed %} + Ilmoittautuminen on päättynyt. + {% endif %} + Hei {{ firstName }}, + + ilmoittautumisesi tapahtumaan {{ eventName.fi }} (kiintiö: {{ registrationQuota.fi }}) on vielä maksamatta. Voit maksaa osallistumisen alla olevasta linkistä: + + {% call paymentBox() %} + Lippu {{ price | euro }} + palvelumaksu {{ serviceFee | euro }} = {{ total | euro }} + {{ payButton(url + "/fi/" + payLink, "Maksa " + (total | euro)) }} + {% endcall %} + {% call note() %}Jos et pääse tapahtumaan, ota yhteyttä järjestäjiin.{% endcall %} + + {% if closed %} + Registration has closed. + {% endif %} + Hi {{ firstName }}, + + your registration to {{ eventName.en }} (quota: {{ registrationQuota.en }}) hasn't been paid yet. Please pay using the link below: + + {% call paymentBox() %} + Ticket {{ price | euro }} + service fee {{ serviceFee | euro }} = {{ total | euro }} + {{ payButton(url + "/en/" + payLink, "Pay " + (total | euro)) }} + {% endcall %} + {% call note() %}If you can't attend, please contact the organizers.{% endcall %} + +{% endblock %} diff --git a/@app/worker/templates/registration_reminder.mjml.njk b/@app/worker/templates/registration_reminder.mjml.njk new file mode 100644 index 000000000..07c5431f7 --- /dev/null +++ b/@app/worker/templates/registration_reminder.mjml.njk @@ -0,0 +1,16 @@ +{% extends "base.mjml.njk" %} +{% block content %} + + {% if language == 'fi' %} + Ilmoittautuminen avautuu pian: {{ eventName }} + Ilmoittautuminen alkaa {{ openingTime }} (Suomen aikaa). + Avaa tapahtuma + Pyysit muistutuksen tähän tapahtumaan. Muistutus ei varaa paikkaa tapahtumasta. + {% else %} + Registration opens soon: {{ eventName }} + Registration opens {{ openingTime }} (Finland time). + Open event + You requested a reminder for this event. This reminder does not reserve a place. + {% endif %} + +{% endblock %} diff --git a/@app/worker/templates/spot_from_queue.mjml.njk b/@app/worker/templates/spot_from_queue.mjml.njk index bc766bc0c..9054fa863 100644 --- a/@app/worker/templates/spot_from_queue.mjml.njk +++ b/@app/worker/templates/spot_from_queue.mjml.njk @@ -12,6 +12,14 @@ - Linkki tapahtumaan: {{ url }}/fi/event/{{ eventSlug }}
+ {%- if price and payLink %} + {%- from "payment_macros.njk" import paymentBox, payButton %} + {% call paymentBox() %} + Maksu: odottaa maksua
+ Lippu {{ price | euro }} + palvelumaksu {{ serviceFee | euro }} = {{ total | euro }} + {{ payButton(url + "/fi/" + payLink, "Maksa " + (total | euro)) }} + {% endcall %} + {%- endif %} Voit muokata tietojasi tai poistaa ilmoittautumisesi tämän linkin takaa: {{ url }}/fi/{{ eventRegistrationUpdateLink }} @@ -28,6 +36,14 @@ - Link to the event: {{ url }}/en/event/{{ eventSlug }}
+ {%- if price and payLink %} + {%- from "payment_macros.njk" import paymentBox, payButton %} + {% call paymentBox() %} + Payment: pending
+ Ticket {{ price | euro }} + service fee {{ serviceFee | euro }} = {{ total | euro }} + {{ payButton(url + "/en/" + payLink, "Pay " + (total | euro)) }} + {% endcall %} + {%- endif %} You can update or delete your registration via this link: {{ url }}/en/{{ eventRegistrationUpdateLink }} diff --git a/@app/worker/tsconfig.json b/@app/worker/tsconfig.json index 03140d362..09ca64a09 100644 --- a/@app/worker/tsconfig.json +++ b/@app/worker/tsconfig.json @@ -11,5 +11,5 @@ "module": "commonjs" }, "include": ["src"], - "references": [{ "path": "../config" }] + "references": [{ "path": "../config" }, { "path": "../lib" }] } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 09f51d310..931323ff2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,25 +5,72 @@ without first discussing it with the maintainers (by opening an issue). ## Migrations -This project will only ever have one migration; we do not need to cater to -backwards compatibility, prefering simplicity for new users. +The database schema is managed with +[graphile-migrate](https://github.com/graphile/migrate). Released migrations +live in `@app/db/migrations/committed/`. Work in progress lives in +`@app/db/migrations/current/`, which `pnpm dev` (through `pnpm db watch`) +re-applies to your development database on every save. -If you wish to change the database, run +### In a pull request -``` -yarn db uncommit -``` +- Put your SQL in `@app/db/migrations/current/NN-.sql`: one file per + feature, named with the next free number, for example + `3-event-ribbon-text.sql`. Numbers must be unique; graphile-migrate runs the + files in numeric order and refuses two files with the same number. +- Make the file idempotent. It runs again on every save and on top of other open + features' files, so use `create or replace`, `drop ... if exists`, + `add column if not exists` and `insert ... on conflict do nothing`. +- Never add or edit files under `@app/db/migrations/committed/`. +- If your file redefines an existing function (`create or replace function`), + say so in the pull request description and name the function. Two features + that redefine the same function must be reconciled by hand, because each + definition replaces the whole body. +- Leave `data/schema.sql` unchanged. It is dumped from committed migrations + only, so files in `current/` do not appear in it. -to move the migration back to `current.sql`; then make your changes, and when -you're happy run: +CI enforces two of these rules with `scripts/check-migrations.mjs`: it fails +when two files in `current/` share a number, and when a pull request changes +`committed/`. +### Committing migrations (maintainers) + +Maintainers commit migrations on `main`, in a pull request that carries the +`migration-commit` label, which lets that pull request change `committed/`. Add +the label before CI runs, or re-run the "Migration files" job after adding it. + +```sh +pnpm db commit # current/ -> committed/NNNNNN.sql, resets current/, re-dumps data/schema.sql +pnpm db migrate # record the new migration in your development database ``` -yarn db commit -``` -and commit your changes. +`pnpm db uncommit` moves the latest committed migration back to `current/`. Use +it only for a migration that has not reached production. + +### Regenerating generated files + +Regenerate these files with the commands below and commit the result. Do not +edit or hand-merge them. The GraphQL files follow your development database, so +a pull request that changes the GraphQL API regenerates them; `data/schema.sql` +changes only when migrations are committed. + +| File | Command | +| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `data/schema.sql` | `pnpm db dump` (`pnpm db commit` runs it; CI fails when it is stale) | +| `data/schema.graphql` | `pnpm server schema:export` (also written when the server starts in development) | +| `@app/graphql/client.json`, `server.json`, `.persisted_operations/` | `pnpm graphql codegen` (reads `data/schema.graphql`; `pnpm graphql build` also compiles) | + +CI dumps `data/schema.sql` with the PGDG `pg_dump` 16 client against PostgreSQL +14; other client versions produce a different file. If your default `pg_dump` is +another version, set `PG_DUMP` in `.env` to a matching binary. ## Docker and non-Docker This project is designed to work both with and without Docker. Please don't break this! + +## Pre-commit hook + +`pnpm install` sets up a git pre-commit hook (husky + lint-staged) that runs +`eslint --fix` and `prettier --write` on the files you have staged. Type +checking and tests still run in CI. Skip the hook with `git commit --no-verify` +if you need to. diff --git a/README.md b/README.md index 24a77900f..e3a14006b 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,7 @@ - Node.js v20 LTS - pnpm 10 (`npm install -g pnpm`) - Docker (for db + redis services) -- PostgreSQL with wal2json — the project ships a Docker image with wal2json - included, so no host install is needed +- PostgreSQL — the project runs it in Docker, so no host install is needed ## NOT FOR BEGINNERS @@ -52,8 +51,8 @@ CONFIRM_DROP=1 pnpm setup:db pnpm dev ``` -The server runs on http://localhost:5678. The Postgres (with wal2json) and Redis -services run in Docker; everything else runs on the host. +The server runs on http://localhost:5678. The Postgres and Redis services run in +Docker; everything else runs on the host. ## Table of contents @@ -77,7 +76,7 @@ Then install dependencies: pnpm install ``` -Start the data services (PostgreSQL with wal2json, and Redis) in Docker: +Start the data services (PostgreSQL and Redis) in Docker: ```sh docker compose up -d db redis @@ -137,6 +136,16 @@ To shut down the application press Ctrl-c. To stop the Docker data services: docker compose down ``` +### Stripe payments (optional) + +Paid events use Stripe. They need `STRIPE_SECRET_KEY` and +`STRIPE_WEBHOOK_SECRET`, and are switched on with the `payments` feature flag, +which reads as off while either secret is missing. See +[docs/payments.md](docs/payments.md) for testing locally with your own Stripe +test-mode keys and the Stripe CLI, the Stripe dashboard setup for staging and +production, refunds (made by hand in Stripe; Ilmo never refunds) and how to turn +payments off. + ### Useful commands Run tests: @@ -175,6 +184,9 @@ Run a command in a specific workspace: pnpm --filter @app/foo run ``` +To run reminders and the Telegram bot in production, see +[docs/reminder-operations.md](docs/reminder-operations.md). + ## Building the production docker image To build the production image, use `docker build` as shown below. You should diff --git a/data/schema.graphql b/data/schema.graphql index d973bbe26..e3e1541f6 100644 --- a/data/schema.graphql +++ b/data/schema.graphql @@ -73,6 +73,97 @@ type AdminDeleteUserPayload { success: Boolean } +"""All input for the `adminMarkRegistrationPaid` mutation.""" +input AdminMarkRegistrationPaidInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + registrationId: UUID! +} + +"""The output of our `adminMarkRegistrationPaid` mutation.""" +type AdminMarkRegistrationPaidPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """Reads a single `Event` that is related to this `Payment`.""" + event: Event + payment: Payment + + """An edge for our `Payment`. May be used by Relay 1.""" + paymentEdge( + """The method to use when ordering `Payment`.""" + orderBy: [PaymentsOrderBy!] = [PRIMARY_KEY_ASC] + ): PaymentsEdge + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query + + """Reads a single `Quota` that is related to this `Payment`.""" + quota: Quota + + """Reads a single `Registration` that is related to this `Payment`.""" + registration: Registration +} + +"""All input for the `adminSendPaymentReminders` mutation.""" +input AdminSendPaymentRemindersInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + eventId: UUID! +} + +"""The output of our `adminSendPaymentReminders` mutation.""" +type AdminSendPaymentRemindersPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + integer: Int + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + +"""All input for the `adminUnmarkRegistrationPaid` mutation.""" +input AdminUnmarkRegistrationPaidInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + registrationId: UUID! +} + +"""The output of our `adminUnmarkRegistrationPaid` mutation.""" +type AdminUnmarkRegistrationPaidPayload { + boolean: Boolean + + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + """All input for the `adminUpdateRegistration` mutation.""" input AdminUpdateRegistrationInput { """ @@ -223,9 +314,14 @@ type ConfirmAccountDeletionPayload { success: Boolean } -"""A field which must not contain spaces""" +"""A name field which must not be empty or contain only whitespace""" scalar ConstrainedName +type CreateCheckoutSessionPayload { + """The Stripe Checkout page to redirect to.""" + url: String! +} + """All input for the create `EventCategory` mutation.""" input CreateEventCategoryInput { """ @@ -309,12 +405,14 @@ input CreateEventQuestionInput { isRequired: Boolean label: TranslatedField position: Int + prefill: QuestionPrefill type: QuestionType } """An input for mutations affecting `CreateEventQuota`""" input CreateEventQuotaInput { position: Int + priceCents: Int size: Int title: JSON } @@ -569,6 +667,50 @@ type DeleteEventPayload { query: Query } +"""All input for the `deleteEventRegistrationReminder` mutation.""" +input DeleteEventRegistrationReminderInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + id: UUID! +} + +"""The output of our delete `EventRegistrationReminder` mutation.""" +type DeleteEventRegistrationReminderPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + deletedEventRegistrationReminderNodeId: ID + + """ + Reads a single `Event` that is related to this `EventRegistrationReminder`. + """ + event: Event + + """The `EventRegistrationReminder` that was deleted by this mutation.""" + eventRegistrationReminder: EventRegistrationReminder + + """An edge for our `EventRegistrationReminder`. May be used by Relay 1.""" + eventRegistrationReminderEdge( + """The method to use when ordering `EventRegistrationReminder`.""" + orderBy: [EventRegistrationRemindersOrderBy!] = [PRIMARY_KEY_ASC] + ): EventRegistrationRemindersEdge + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query + + """ + Reads a single `User` that is related to this `EventRegistrationReminder`. + """ + user: User +} + """All input for the `deleteOrganization` mutation.""" input DeleteOrganizationInput { """ @@ -618,6 +760,31 @@ type DeleteRegistrationPayload { success: Boolean } +"""All input for the `deleteRegistrationProfile` mutation.""" +input DeleteRegistrationProfileInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String +} + +"""The output of our `deleteRegistrationProfile` mutation.""" +type DeleteRegistrationProfilePayload { + boolean: Boolean + + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + """All input for the `deleteUserAuthentication` mutation.""" input DeleteUserAuthenticationInput { """ @@ -686,6 +853,31 @@ type DeleteUserEmailPayload { ): UserEmailsEdge } +"""All input for the `disconnectTelegram` mutation.""" +input DisconnectTelegramInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String +} + +"""The output of our `disconnectTelegram` mutation.""" +type DisconnectTelegramPayload { + boolean: Boolean + + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + scalar Email """The output of our `renderEmailTemplate` query.""" @@ -698,17 +890,40 @@ type EmailTemplate { input EmailTemplateVariables { actionDescription: String + + """The reminder is the email sent when registration closes.""" + closed: Boolean deleteAccountLink: String eventLocation: String eventName: TranslatedInputField eventRegistrationUpdateLink: String eventSlug: String eventTime: String + firstName: String + isQueued: Boolean link: String organizationName: String + paidAt: String + + """ + The payment link relative to the language root, e.g. `pay/`. + """ + payLink: String + paymentMethod: PaymentMethod + + """Ticket price in cents (payment emails).""" + price: Int + registrationEndDate: String + registrationEndTime: String registrationName: String registrationQuota: TranslatedInputField + + """Service fee in cents (payment emails).""" + serviceFee: Int token: String + + """Ticket price plus service fee, in cents (payment emails).""" + total: Int url: String verifyLink: String } @@ -718,6 +933,33 @@ type EmailTemplatesConnection { templates: [EmailTemplate!]! } +"""All input for the `enableEventReminder` mutation.""" +input EnableEventReminderInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + eventId: UUID! + language: String +} + +"""The output of our `enableEventReminder` mutation.""" +type EnableEventReminderPayload { + boolean: Boolean + + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + """Main table for events.""" type Event { """Reads a single `EventCategory` that is related to this `Event`.""" @@ -768,12 +1010,51 @@ type Event { orderBy: [EventQuestionsOrderBy!] = [PRIMARY_KEY_ASC] ): EventQuestionsConnection! + """ + Reads and enables pagination through a set of `EventRegistrationReminder`. + """ + eventRegistrationReminders( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: EventRegistrationReminderCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: EventRegistrationReminderFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `EventRegistrationReminder`.""" + orderBy: [EventRegistrationRemindersOrderBy!] = [PRIMARY_KEY_ASC] + ): EventRegistrationRemindersConnection! + """Starting time of the event.""" eventStartTime: Datetime! """Header image for the event""" headerImageFile: String + """Text shown on the ribbon of a highlighted event.""" + highlightText: TranslatedField + """Unique identifier for the event.""" id: UUID! @@ -783,6 +1064,11 @@ type Event { """A highlighted event.""" isHighlighted: Boolean! + """ + When an organizer last sent payment reminders to all unpaid participants. + """ + lastPaymentReminderSentAt: Datetime + """Event location.""" location: String! @@ -798,6 +1084,45 @@ type Event { """Identifier of the event organizer""" ownerOrganizationId: UUID! + """ + Payment totals for organizers: counts of registrations holding a spot (in quota or open quota) that are paid, unpaid and due, the ticket amount paid, the estimated amount the guild receives and the number of card payments not linked to a registration (deleted registrations, second payments), which organizers may refund by hand in Stripe. Null unless the current user may manage the event's payments. + """ + paymentSummary: EventPaymentSummary + + """Reads and enables pagination through a set of `Payment`.""" + payments( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: PaymentCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: PaymentFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `Payment`.""" + orderBy: [PaymentsOrderBy!] = [PRIMARY_KEY_ASC] + ): PaymentsConnection! + """Reads and enables pagination through a set of `Quota`.""" quotas( """Read all values in the set after (below) this cursor.""" @@ -883,6 +1208,11 @@ type Event { """Slug for the event.""" slug: String! + + """ + When the close-of-registration payment email was sent. Set by the worker; cleared when registration_end_time moves later, so that the email goes out again at the new close. + """ + unpaidCloseEmailSentAt: Datetime updatedAt: Datetime! updatedBy: UUID } @@ -1184,6 +1514,7 @@ input EventInputRecordInput { eventEndTime: Datetime eventStartTime: Datetime headerImageFile: Upload + highlightText: TranslatedField isDraft: Boolean isHighlighted: Boolean location: String @@ -1195,6 +1526,16 @@ input EventInputRecordInput { slug: String } +"""Payment totals for an event, for organizers.""" +type EventPaymentSummary { + dueCount: Int + guildReceivesCents: Int + paidCount: Int + ticketsPaidCents: Int + unlinkedCardPaymentCount: Int + unpaidCount: Int +} + """Main table for event questions.""" type EventQuestion { createdAt: Datetime! @@ -1221,6 +1562,11 @@ type EventQuestion { """Question position. Used to order question.""" position: Int! + """ + Which registration profile field prefills the answer to this question, if any. + """ + prefill: QuestionPrefill + """Question type (e.g. radio button, text, checkbox).""" type: QuestionType! updatedAt: Datetime! @@ -1320,23 +1666,128 @@ enum EventQuestionsOrderBy { UPDATED_BY_DESC } -type EventRegistrationsSubscriptionPayload { - event: String - registrations(after: Datetime): [Registration] -} +""" +Registration reminders requested by the current user, before registration opens. +""" +type EventRegistrationReminder { + createdAt: Datetime! + deliveryMethod: String! + emailSentAt: Datetime -"""A connection to a list of `Event` values.""" -type EventsConnection { """ - A list of edges which contains the `Event` and cursor to aid in pagination. + Reads a single `Event` that is related to this `EventRegistrationReminder`. """ - edges: [EventsEdge!]! - - """A list of `Event` objects.""" - nodes: [Event!]! + event: Event + eventId: UUID! + id: UUID! + language: String! + minutesBefore: Int! + sentAt: Datetime + telegramSentAt: Datetime - """Information to aid in pagination.""" - pageInfo: PageInfo! + """ + Reads a single `User` that is related to this `EventRegistrationReminder`. + """ + user: User + userId: UUID! +} + +""" +A condition to be used against `EventRegistrationReminder` object types. All +fields are tested for equality and combined with a logical ‘and.’ +""" +input EventRegistrationReminderCondition { + """Checks for equality with the object’s `eventId` field.""" + eventId: UUID + + """Checks for equality with the object’s `id` field.""" + id: UUID + + """Checks for equality with the object’s `userId` field.""" + userId: UUID +} + +""" +A filter to be used against `EventRegistrationReminder` object types. All fields are combined with a logical ‘and.’ +""" +input EventRegistrationReminderFilter { + """Checks for all expressions in this list.""" + and: [EventRegistrationReminderFilter!] + + """Filter by the object’s `eventId` field.""" + eventId: UUIDFilter + + """Filter by the object’s `id` field.""" + id: UUIDFilter + + """Negates the expression.""" + not: EventRegistrationReminderFilter + + """Checks for any expressions in this list.""" + or: [EventRegistrationReminderFilter!] + + """Filter by the object’s `userId` field.""" + userId: UUIDFilter +} + +"""A connection to a list of `EventRegistrationReminder` values.""" +type EventRegistrationRemindersConnection { + """ + A list of edges which contains the `EventRegistrationReminder` and cursor to aid in pagination. + """ + edges: [EventRegistrationRemindersEdge!]! + + """A list of `EventRegistrationReminder` objects.""" + nodes: [EventRegistrationReminder!]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! + + """ + The count of *all* `EventRegistrationReminder` you could get from the connection. + """ + totalCount: Int! +} + +"""A `EventRegistrationReminder` edge in the connection.""" +type EventRegistrationRemindersEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `EventRegistrationReminder` at the end of the edge.""" + node: EventRegistrationReminder! +} + +"""Methods to use when ordering `EventRegistrationReminder`.""" +enum EventRegistrationRemindersOrderBy { + EVENT_ID_ASC + EVENT_ID_DESC + ID_ASC + ID_DESC + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + USER_ID_ASC + USER_ID_DESC +} + +type EventRegistrationsSubscriptionPayload { + event: String + registrations(after: Datetime): [Registration] +} + +"""A connection to a list of `Event` values.""" +type EventsConnection { + """ + A list of edges which contains the `Event` and cursor to aid in pagination. + """ + edges: [EventsEdge!]! + + """A list of `Event` objects.""" + nodes: [Event!]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! """The count of *all* `Event` you could get from the connection.""" totalCount: Int! @@ -1384,6 +1835,206 @@ enum EventsOrderBy { UPDATED_BY_DESC } +""" +A feature that can be switched on or off at runtime. Rows are created by migrations. +""" +type FeatureFlag { + """ + False when the server lacks the configuration the feature needs; the feature then reads as off whatever its state. + """ + available: Boolean! + + """What the flag gates.""" + description: String! + + """Identifier of the feature, as used in code.""" + key: String! + + """ + Set when the gates have been removed from code. A retired flag reads as on. + """ + retiredAt: Datetime + + """Who the feature is enabled for.""" + state: FeatureState! + + """When the state was last changed.""" + updatedAt: Datetime! + + """Who last changed the state.""" + updatedBy: UUID +} + +""" +A condition to be used against `FeatureFlag` object types. All fields are tested +for equality and combined with a logical ‘and.’ +""" +input FeatureFlagCondition { + """Checks for equality with the object’s `key` field.""" + key: String + + """Checks for equality with the object’s `updatedBy` field.""" + updatedBy: UUID +} + +"""The return type of our `featureFlagEvents` query.""" +type FeatureFlagEventsRecord { + actorId: UUID + actorName: String + actorUsername: String + createdAt: Datetime + id: UUID + key: String + newState: FeatureState + oldState: FeatureState +} + +""" +A filter to be used against `FeatureFlagEventsRecord` object types. All fields are combined with a logical ‘and.’ +""" +input FeatureFlagEventsRecordFilter { + """Filter by the object’s `actorId` field.""" + actorId: UUIDFilter + + """Filter by the object’s `actorName` field.""" + actorName: StringFilter + + """Filter by the object’s `actorUsername` field.""" + actorUsername: StringFilter + + """Checks for all expressions in this list.""" + and: [FeatureFlagEventsRecordFilter!] + + """Filter by the object’s `createdAt` field.""" + createdAt: DatetimeFilter + + """Filter by the object’s `id` field.""" + id: UUIDFilter + + """Filter by the object’s `key` field.""" + key: StringFilter + + """Filter by the object’s `newState` field.""" + newState: FeatureStateFilter + + """Negates the expression.""" + not: FeatureFlagEventsRecordFilter + + """Filter by the object’s `oldState` field.""" + oldState: FeatureStateFilter + + """Checks for any expressions in this list.""" + or: [FeatureFlagEventsRecordFilter!] +} + +""" +A filter to be used against `FeatureFlag` object types. All fields are combined with a logical ‘and.’ +""" +input FeatureFlagFilter { + """Checks for all expressions in this list.""" + and: [FeatureFlagFilter!] + + """Filter by the object’s `key` field.""" + key: StringFilter + + """Negates the expression.""" + not: FeatureFlagFilter + + """Checks for any expressions in this list.""" + or: [FeatureFlagFilter!] + + """Filter by the object’s `updatedBy` field.""" + updatedBy: UUIDFilter +} + +"""A connection to a list of `FeatureFlag` values.""" +type FeatureFlagsConnection { + """ + A list of edges which contains the `FeatureFlag` and cursor to aid in pagination. + """ + edges: [FeatureFlagsEdge!]! + + """A list of `FeatureFlag` objects.""" + nodes: [FeatureFlag!]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! + + """The count of *all* `FeatureFlag` you could get from the connection.""" + totalCount: Int! +} + +"""A `FeatureFlag` edge in the connection.""" +type FeatureFlagsEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `FeatureFlag` at the end of the edge.""" + node: FeatureFlag! +} + +"""Methods to use when ordering `FeatureFlag`.""" +enum FeatureFlagsOrderBy { + KEY_ASC + KEY_DESC + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + UPDATED_BY_ASC + UPDATED_BY_DESC +} + +""" +State of a feature flag: off for everyone, on for signed-in admins only, or on for everyone. +""" +enum FeatureState { + ADMINS_ONLY + OFF + ON +} + +""" +A filter to be used against FeatureState fields. All fields are combined with a logical ‘and.’ +""" +input FeatureStateFilter { + """ + Not equal to the specified value, treating null like an ordinary value. + """ + distinctFrom: FeatureState + + """Equal to the specified value.""" + equalTo: FeatureState + + """Greater than the specified value.""" + greaterThan: FeatureState + + """Greater than or equal to the specified value.""" + greaterThanOrEqualTo: FeatureState + + """Included in the specified list.""" + in: [FeatureState!] + + """ + Is null (if `true` is specified) or is not null (if `false` is specified). + """ + isNull: Boolean + + """Less than the specified value.""" + lessThan: FeatureState + + """Less than or equal to the specified value.""" + lessThanOrEqualTo: FeatureState + + """Equal to the specified value, treating null like an ordinary value.""" + notDistinctFrom: FeatureState + + """Not equal to the specified value.""" + notEqualTo: FeatureState + + """Not included in the specified list.""" + notIn: [FeatureState!] +} + """All input for the `forgotPassword` mutation.""" input ForgotPasswordInput { """ @@ -1568,6 +2219,36 @@ type Mutation { input: AdminDeleteUserInput! ): AdminDeleteUserPayload + """ + Records a manual payment (cash, bank transfer) of the current quota price for a registration and emails the participant a payment confirmation. + """ + adminMarkRegistrationPaid( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: AdminMarkRegistrationPaidInput! + ): AdminMarkRegistrationPaidPayload + + """ + Emails a payment reminder to every finished, unpaid registration holding a spot in the event. Returns the number of reminders queued. Refused for 10 minutes after the last reminders were sent. + """ + adminSendPaymentReminders( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: AdminSendPaymentRemindersInput! + ): AdminSendPaymentRemindersPayload + + """ + Removes a manual payment recorded with adminMarkRegistrationPaid. Card payments cannot be undone this way. + """ + adminUnmarkRegistrationPaid( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: AdminUnmarkRegistrationPaidInput! + ): AdminUnmarkRegistrationPaidPayload + """ Mutation only accessible to admin users. Allows updating a registration via the admin panel. """ @@ -1607,6 +2288,15 @@ type Mutation { input: ConfirmAccountDeletionInput! ): ConfirmAccountDeletionPayload + """ + Starts Stripe Checkout for the registration with this update token and + returns the Checkout URL. Expires the registration's other open + Checkout Sessions. Fails with a PaymentErrorCode as the error code when + the registration can't be paid now. language (fi, en or se, default + fi) sets the Checkout language and the /pay page Stripe returns to. + """ + createCheckoutSession(language: String, updateToken: String!): CreateCheckoutSessionPayload + """ Create an event as well as any related quotas and questions with one mutation. """ @@ -1669,6 +2359,14 @@ type Mutation { input: DeleteEventCategoryInput! ): DeleteEventCategoryPayload + """Deletes a single `EventRegistrationReminder` using a unique key.""" + deleteEventRegistrationReminder( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: DeleteEventRegistrationReminderInput! + ): DeleteEventRegistrationReminderPayload + """ Only the 'owner' may delete an organization. This operation cannot be undone, so be sure that it is what you intend. """ @@ -1687,6 +2385,14 @@ type Mutation { input: DeleteRegistrationInput! ): DeleteRegistrationPayload + """Delete the values saved to prefill your event registrations.""" + deleteRegistrationProfile( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: DeleteRegistrationProfileInput! + ): DeleteRegistrationProfilePayload + """Deletes a single `UserAuthentication` using a unique key.""" deleteUserAuthentication( """ @@ -1702,6 +2408,18 @@ type Mutation { """ input: DeleteUserEmailInput! ): DeleteUserEmailPayload + disconnectTelegram( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: DisconnectTelegramInput! + ): DisconnectTelegramPayload + enableEventReminder( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: EnableEventReminderInput! + ): EnableEventReminderPayload """ If you've forgotten your password, give us one of your email addresses and we'll send you a reset token. Note this only works if you have added an email address! @@ -1767,6 +2485,12 @@ type Mutation { """ input: RequestAccountDeletionInput! ): RequestAccountDeletionPayload + requestTelegramLink( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: RequestTelegramLinkInput! + ): RequestTelegramLinkPayload """ If you didn't receive the verification code for this email, we can resend it. We silently cap the rate of resends on the backend, so calls to this function may not result in another email being sent if it has been called recently. @@ -1787,6 +2511,12 @@ type Mutation { """ input: ResetPasswordInput! ): ResetPasswordPayload + saveReminderPreferences( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: SaveReminderPreferencesInput! + ): SaveReminderPreferencesPayload """Make an existing user admin. Only accessible to admin users.""" setAdminStatus( @@ -1795,6 +2525,32 @@ type Mutation { """ input: SetAdminStatusInput! ): SetAdminStatusPayload + setEventRegistrationReminder( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: SetEventRegistrationReminderInput! + ): SetEventRegistrationReminderPayload + + """ + Changes the state of an existing feature flag. Only accessible to developers. + """ + setFeatureFlag( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: SetFeatureFlagInput! + ): SetFeatureFlagPayload + + """ + Set the values used to prefill your event registrations. A null value keeps the saved one and an empty value clears it. + """ + setRegistrationProfile( + """ + The exclusive input argument for this mutation. An object type, make sure to see documentation for this object’s fields. + """ + input: SetRegistrationProfileInput! + ): SetRegistrationProfilePayload """ The owner of an `Organization` may use this mutation to transfer ownership to a different organization member. Take care, if you assign ownership to someone who cannot or will not access their account then you may need to contact support to have ownership reassigned. @@ -1808,7 +2564,7 @@ type Mutation { translateText(fromLanguage: SupportedLanguages!, text: String!, toLanguage: SupportedLanguages!): TranslateTextPayload! """ - Updates an event as well as any related quotas and questions with one mutation. + Updates an event as well as any related quotas and questions with one mutation. An omitted event attribute keeps its value, except `highlightText`, which is replaced (null clears it) whenever `isHighlighted` is given. """ updateEvent( """ @@ -2219,7 +2975,208 @@ type PasswordStrengthPayload { score: Int! } -"""The root query type which gives access points into the data universe.""" +""" +Payments for registrations. Rows outlive their registration (and event and quota) so they can be reconciled with Stripe payouts; they hold no personal data. Ilmo never refunds: a card payment without a registration is refunded by hand in Stripe, if at all. +""" +type Payment { + createdAt: Datetime! + + """The organizer who recorded a manual payment.""" + createdBy: UUID + currency: String! + + """Reads a single `Event` that is related to this `Payment`.""" + event: Event + + """The event paid for. Null once the event has been deleted.""" + eventId: UUID + + """Snapshot of the event name when the payment was created.""" + eventName: JSON! + id: UUID! + method: PaymentMethod! + paidAt: Datetime + + """Reads a single `Quota` that is related to this `Payment`.""" + quota: Quota + + """The quota paid for. Null once the quota has been deleted.""" + quotaId: UUID + + """Snapshot of the quota title when the payment was created.""" + quotaTitle: JSON! + + """Reads a single `Registration` that is related to this `Payment`.""" + registration: Registration + + """ + The registration paid for. Null once the registration has been deleted, and for a card payment that could not be applied to it (a second payment, or an amount that did not match). + """ + registrationId: UUID + + """ + Service fee paid on top of the ticket, in cents. 0 for manual payments. + """ + serviceFeeCents: Int! + status: PaymentStatus! + stripeCheckoutSessionId: String + stripePaymentIntentId: String + + """ + Ticket price paid, in cents: the quota price when the payment was started. + """ + ticketAmountCents: Int! + updatedAt: Datetime! +} + +""" +A condition to be used against `Payment` object types. All fields are tested for equality and combined with a logical ‘and.’ +""" +input PaymentCondition { + """Checks for equality with the object’s `createdBy` field.""" + createdBy: UUID + + """Checks for equality with the object’s `eventId` field.""" + eventId: UUID + + """Checks for equality with the object’s `id` field.""" + id: UUID + + """Checks for equality with the object’s `quotaId` field.""" + quotaId: UUID + + """Checks for equality with the object’s `registrationId` field.""" + registrationId: UUID + + """Checks for equality with the object’s `stripeCheckoutSessionId` field.""" + stripeCheckoutSessionId: String + + """Checks for equality with the object’s `stripePaymentIntentId` field.""" + stripePaymentIntentId: String +} + +""" +Why a registration can't be paid right now. The error code of +createCheckoutSession, and blockedReason of paymentByUpdateToken. +""" +enum PaymentErrorCode { + """The registration has been paid (by card or marked paid by hand).""" + ALREADY_PAID + + """The registration is in the queue; it is paid once it gets a spot.""" + IN_QUEUE + + """Payments are switched off, or Stripe is not configured on this server.""" + PAYMENTS_DISABLED + + """Payment opens when registration closes; registration is open (again).""" + PAYMENT_NOT_OPEN + + """The quota is free, or the event has no payments.""" + PAYMENT_NOT_REQUIRED + + """No finished registration has this update token.""" + REGISTRATION_NOT_FOUND +} + +""" +A filter to be used against `Payment` object types. All fields are combined with a logical ‘and.’ +""" +input PaymentFilter { + """Checks for all expressions in this list.""" + and: [PaymentFilter!] + + """Filter by the object’s `createdBy` field.""" + createdBy: UUIDFilter + + """Filter by the object’s `eventId` field.""" + eventId: UUIDFilter + + """Filter by the object’s `id` field.""" + id: UUIDFilter + + """Negates the expression.""" + not: PaymentFilter + + """Checks for any expressions in this list.""" + or: [PaymentFilter!] + + """Filter by the object’s `quotaId` field.""" + quotaId: UUIDFilter + + """Filter by the object’s `registrationId` field.""" + registrationId: UUIDFilter + + """Filter by the object’s `stripeCheckoutSessionId` field.""" + stripeCheckoutSessionId: StringFilter + + """Filter by the object’s `stripePaymentIntentId` field.""" + stripePaymentIntentId: StringFilter +} + +""" +How a payment was made: by card through Stripe Checkout, or marked paid by an organizer (cash, bank transfer). +""" +enum PaymentMethod { + MANUAL + STRIPE +} + +"""State of a single payment attempt.""" +enum PaymentStatus { + EXPIRED + PAID + PENDING +} + +"""A connection to a list of `Payment` values.""" +type PaymentsConnection { + """ + A list of edges which contains the `Payment` and cursor to aid in pagination. + """ + edges: [PaymentsEdge!]! + + """A list of `Payment` objects.""" + nodes: [Payment!]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! + + """The count of *all* `Payment` you could get from the connection.""" + totalCount: Int! +} + +"""A `Payment` edge in the connection.""" +type PaymentsEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `Payment` at the end of the edge.""" + node: Payment! +} + +"""Methods to use when ordering `Payment`.""" +enum PaymentsOrderBy { + CREATED_BY_ASC + CREATED_BY_DESC + EVENT_ID_ASC + EVENT_ID_DESC + ID_ASC + ID_DESC + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + QUOTA_ID_ASC + QUOTA_ID_DESC + REGISTRATION_ID_ASC + REGISTRATION_ID_DESC + STRIPE_CHECKOUT_SESSION_ID_ASC + STRIPE_CHECKOUT_SESSION_ID_DESC + STRIPE_PAYMENT_INTENT_ID_ASC + STRIPE_PAYMENT_INTENT_ID_DESC +} + +"""The root query type which gives access points into the data universe.""" type Query { """List all users. Only accessible to admin users.""" adminListUsers( @@ -2255,8 +3212,45 @@ type Query { orderBy: [UsersOrderBy!] ): UsersConnection + """ + Keys of the features enabled for the current user only because they are in admins_only. Empty unless the current user is an admin. + """ + adminPreviewFeaturesList( + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: StringFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Skip the first `n` values.""" + offset: Int + ): [String] + currentReminderPreferences: ReminderPreference + currentTelegramAccount: TelegramAccount + """The currently logged in user (or null if not logged in).""" currentUser: User + + """ + Returns true if the current user is both an admin and a developer, false otherwise. + """ + currentUserIsDeveloper: Boolean + + """Keys of the features enabled for the current user.""" + enabledFeaturesList( + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: StringFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Skip the first `n` values.""" + offset: Int + ): [String] event(id: UUID!): Event eventBySlug(slug: String!): Event @@ -2329,6 +3323,44 @@ type Query { """The method to use when ordering `EventQuestion`.""" orderBy: [EventQuestionsOrderBy!] = [PRIMARY_KEY_ASC] ): EventQuestionsConnection + eventRegistrationReminder(id: UUID!): EventRegistrationReminder + eventRegistrationReminderByUserIdAndEventId(eventId: UUID!, userId: UUID!): EventRegistrationReminder + + """ + Reads and enables pagination through a set of `EventRegistrationReminder`. + """ + eventRegistrationReminders( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: EventRegistrationReminderCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: EventRegistrationReminderFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `EventRegistrationReminder`.""" + orderBy: [EventRegistrationRemindersOrderBy!] = [PRIMARY_KEY_ASC] + ): EventRegistrationRemindersConnection """Reads and enables pagination through a set of `Event`.""" events( @@ -2363,6 +3395,58 @@ type Query { """The method to use when ordering `Event`.""" orderBy: [EventsOrderBy!] = [PRIMARY_KEY_ASC] ): EventsConnection + featureFlag(key: String!): FeatureFlag + + """ + Feature flag state changes, newest first, optionally for one key. Only accessible to developers. + """ + featureFlagEventsList( + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: FeatureFlagEventsRecordFilter + + """Only read the first `n` values of the set.""" + first: Int + flagKey: String + + """Skip the first `n` values.""" + offset: Int + ): [FeatureFlagEventsRecord] + + """Reads and enables pagination through a set of `FeatureFlag`.""" + featureFlags( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: FeatureFlagCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: FeatureFlagFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `FeatureFlag`.""" + orderBy: [FeatureFlagsOrderBy!] = [PRIMARY_KEY_ASC] + ): FeatureFlagsConnection organization(id: UUID!): Organization organizationBySlug(slug: String!): Organization @@ -2404,6 +3488,50 @@ type Query { """The method to use when ordering `Organization`.""" orderBy: [OrganizationsOrderBy!] = [PRIMARY_KEY_ASC] ): OrganizationsConnection + payment(id: UUID!): Payment + paymentByStripeCheckoutSessionId(stripeCheckoutSessionId: String!): Payment + + """ + The payment state of the registration with this update token, for the + /pay page. Null when Stripe is not configured on this server or the + token is unknown. Answers while the payments feature is off too, so + that a payment already made stays visible; Pay is then blocked. + """ + paymentByUpdateToken(updateToken: String!): RegistrationPayment + + """Reads and enables pagination through a set of `Payment`.""" + payments( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: PaymentCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: PaymentFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `Payment`.""" + orderBy: [PaymentsOrderBy!] = [PRIMARY_KEY_ASC] + ): PaymentsConnection quota(id: UUID!): Quota """Reads and enables pagination through a set of `Quota`.""" @@ -2443,6 +3571,7 @@ type Query { """Get registration by update token.""" registrationByUpdateToken(updateToken: String!): Registration + registrationProfile(userId: UUID!): RegistrationProfile """Reads and enables pagination through a set of `Registration`.""" registrations( @@ -2477,25 +3606,105 @@ type Query { """The method to use when ordering `Registration`.""" orderBy: [RegistrationsOrderBy!] = [PRIMARY_KEY_ASC] ): RegistrationsConnection + reminderPreference(userId: UUID!): ReminderPreference - """Use this query to render server-side mjml templates to html and text.""" - renderEmailTemplate(input: RenderEmailInput!): EmailTemplate + """Reads and enables pagination through a set of `ReminderPreference`.""" + reminderPreferences( + """Read all values in the set after (below) this cursor.""" + after: Cursor - """ - Use this query to render all server-side email templates to html and text. - """ - renderEmailTemplates: EmailTemplatesConnection + """Read all values in the set before (above) this cursor.""" + before: Cursor - """True when Keycloak SSO login is configured on this server.""" - ssoLoginEnabled: Boolean! + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: ReminderPreferenceCondition - """Supported languages of the app.""" + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: ReminderPreferenceFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `ReminderPreference`.""" + orderBy: [ReminderPreferencesOrderBy!] = [PRIMARY_KEY_ASC] + ): ReminderPreferencesConnection + + """Use this query to render server-side mjml templates to html and text.""" + renderEmailTemplate(input: RenderEmailInput!): EmailTemplate + + """ + Use this query to render all server-side email templates to html and text. + """ + renderEmailTemplates: EmailTemplatesConnection + + """True when Keycloak SSO login is configured on this server.""" + ssoLoginEnabled: Boolean! + + """Supported languages of the app.""" supportedLanguages: [SupportedLanguages] + telegramAccount(userId: UUID!): TelegramAccount + + """Reads and enables pagination through a set of `TelegramAccount`.""" + telegramAccounts( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: TelegramAccountCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: TelegramAccountFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `TelegramAccount`.""" + orderBy: [TelegramAccountsOrderBy!] = [PRIMARY_KEY_ASC] + ): TelegramAccountsConnection + telegramBotUsername: String user(id: UUID!): User userAuthentication(id: UUID!): UserAuthentication userEmail(id: UUID!): UserEmail } +""" +Which registration profile field prefills the answer to a question. NONE is only an input value: it clears the prefill of a question in `updateEvent`, where an omitted prefill keeps the stored one. +""" +enum QuestionPrefill { + DIETARY_RESTRICTIONS + NONE + TELEGRAM +} + enum QuestionType { CHECKBOX RADIO @@ -2514,9 +3723,48 @@ type Quota { eventId: UUID! id: UUID! + """Reads and enables pagination through a set of `Payment`.""" + payments( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: PaymentCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: PaymentFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `Payment`.""" + orderBy: [PaymentsOrderBy!] = [PRIMARY_KEY_ASC] + ): PaymentsConnection! + """Quota position. Used to order quotas.""" position: Int! + """ + Ticket price in cents. 0 means the quota is free; a paid price is at least 25 cents so that the total charge with the service fee reaches Stripe's minimum, and at most 1 000 000 cents (10 000 €). Registrants pay the price in effect when they pay. + """ + priceCents: Int! + """Reads and enables pagination through a set of `Registration`.""" registrations( """Read all values in the set after (below) this cursor.""" @@ -2683,6 +3931,45 @@ type Registration { """Last name of the person registered to an event.""" lastName: ConstrainedName + """ + Payment status of the registration. Null unless the current user may manage the event's payments, because registrations are publicly readable. + """ + paymentStatus: RegistrationPaymentStatus + + """Reads and enables pagination through a set of `Payment`.""" + payments( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: PaymentCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: PaymentFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `Payment`.""" + orderBy: [PaymentsOrderBy!] = [PRIMARY_KEY_ASC] + ): PaymentsConnection! + """Returns the position of the registration.""" position: Int @@ -2715,6 +4002,9 @@ input RegistrationCondition { """Checks for equality with the object’s `id` field.""" id: UUID + """Checks for equality with the object’s `paymentStatus` field.""" + paymentStatus: RegistrationPaymentStatus + """Checks for equality with the object’s `position` field.""" position: Int @@ -2759,6 +4049,9 @@ input RegistrationFilter { """Checks for any expressions in this list.""" or: [RegistrationFilter!] + """Filter by the object’s `paymentStatus` field.""" + paymentStatus: RegistrationPaymentStatusFilter + """Filter by the object’s `position` field.""" position: IntFilter @@ -2772,6 +4065,128 @@ input RegistrationFilter { updatedBy: UUIDFilter } +"""What the /pay page shows for a registration. Amounts are in cents.""" +type RegistrationPayment { + """Why Pay is not available right now; null when it is.""" + blockedReason: PaymentErrorCode + eventEndTime: Datetime! + eventId: UUID! + eventName: JSON! + eventSlug: String! + eventStartTime: Datetime! + firstName: String + lastName: String + paidAt: Datetime + + """True when the paid payment was recorded by an organizer by hand.""" + paidManually: Boolean! + + """What was paid, fee included (paid registrations only).""" + paidTotalCents: Int + + """The quota's current ticket price, which Pay charges. 0 when free.""" + priceCents: Int! + queuePosition: Int + + """Queue status; null while the registration is not yet placed.""" + queueStatus: RegistrationStatus + quotaTitle: JSON! + registrationEndTime: Datetime! + + """The service fee charged on top of a paid ticket. 0 when free.""" + serviceFeeCents: Int! + status: RegistrationPaymentStatus! + totalCents: Int! +} + +"""Payment state of a registration as shown to organizers.""" +enum RegistrationPaymentStatus { + NOT_REQUIRED + PAID + PAID_MANUALLY + UNPAID +} + +""" +A filter to be used against RegistrationPaymentStatus fields. All fields are combined with a logical ‘and.’ +""" +input RegistrationPaymentStatusFilter { + """ + Not equal to the specified value, treating null like an ordinary value. + """ + distinctFrom: RegistrationPaymentStatus + + """Equal to the specified value.""" + equalTo: RegistrationPaymentStatus + + """Greater than the specified value.""" + greaterThan: RegistrationPaymentStatus + + """Greater than or equal to the specified value.""" + greaterThanOrEqualTo: RegistrationPaymentStatus + + """Included in the specified list.""" + in: [RegistrationPaymentStatus!] + + """ + Is null (if `true` is specified) or is not null (if `false` is specified). + """ + isNull: Boolean + + """Less than the specified value.""" + lessThan: RegistrationPaymentStatus + + """Less than or equal to the specified value.""" + lessThanOrEqualTo: RegistrationPaymentStatus + + """Equal to the specified value, treating null like an ordinary value.""" + notDistinctFrom: RegistrationPaymentStatus + + """Not equal to the specified value.""" + notEqualTo: RegistrationPaymentStatus + + """Not included in the specified list.""" + notIn: [RegistrationPaymentStatus!] +} + +""" +Values used to prefill event registration answers. Only visible to the user themselves. +""" +type RegistrationProfile { + createdAt: Datetime! + + """Dietary restrictions and allergies.""" + dietaryRestrictions: String + + """Telegram handle.""" + telegram: String + updatedAt: Datetime! + + """Reads a single `User` that is related to this `RegistrationProfile`.""" + user: User + + """The user this registration profile belongs to.""" + userId: UUID! +} + +"""A `RegistrationProfile` edge in the connection.""" +type RegistrationProfilesEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `RegistrationProfile` at the end of the edge.""" + node: RegistrationProfile! +} + +"""Methods to use when ordering `RegistrationProfile`.""" +enum RegistrationProfilesOrderBy { + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + USER_ID_ASC + USER_ID_DESC +} + enum RegistrationStatus { IN_OPEN_QUOTA IN_QUEUE @@ -2857,6 +4272,8 @@ enum RegistrationsOrderBy { ID_ASC ID_DESC NATURAL + PAYMENT_STATUS_ASC + PAYMENT_STATUS_DESC POSITION_ASC POSITION_DESC PRIMARY_KEY_ASC @@ -2869,6 +4286,79 @@ enum RegistrationsOrderBy { UPDATED_BY_DESC } +"""Delivery and timing preferences for upcoming registration reminders.""" +type ReminderPreference { + deliveryMethod: String! + minutesBefore: Int! + + """Reads a single `User` that is related to this `ReminderPreference`.""" + user: User + userId: UUID! +} + +""" +A condition to be used against `ReminderPreference` object types. All fields are +tested for equality and combined with a logical ‘and.’ +""" +input ReminderPreferenceCondition { + """Checks for equality with the object’s `userId` field.""" + userId: UUID +} + +""" +A filter to be used against `ReminderPreference` object types. All fields are combined with a logical ‘and.’ +""" +input ReminderPreferenceFilter { + """Checks for all expressions in this list.""" + and: [ReminderPreferenceFilter!] + + """Negates the expression.""" + not: ReminderPreferenceFilter + + """Checks for any expressions in this list.""" + or: [ReminderPreferenceFilter!] + + """Filter by the object’s `userId` field.""" + userId: UUIDFilter +} + +"""A connection to a list of `ReminderPreference` values.""" +type ReminderPreferencesConnection { + """ + A list of edges which contains the `ReminderPreference` and cursor to aid in pagination. + """ + edges: [ReminderPreferencesEdge!]! + + """A list of `ReminderPreference` objects.""" + nodes: [ReminderPreference!]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! + + """ + The count of *all* `ReminderPreference` you could get from the connection. + """ + totalCount: Int! +} + +"""A `ReminderPreference` edge in the connection.""" +type ReminderPreferencesEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `ReminderPreference` at the end of the edge.""" + node: ReminderPreference! +} + +"""Methods to use when ordering `ReminderPreference`.""" +enum ReminderPreferencesOrderBy { + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + USER_ID_ASC + USER_ID_DESC +} + """All input for the `removeFromOrganization` mutation.""" input RemoveFromOrganizationInput { """ @@ -2924,6 +4414,30 @@ type RequestAccountDeletionPayload { success: Boolean } +"""All input for the `requestTelegramLink` mutation.""" +input RequestTelegramLinkInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String +} + +"""The output of our `requestTelegramLink` mutation.""" +type RequestTelegramLinkPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query + string: String +} + """All input for the `resendEmailVerificationCode` mutation.""" input ResendEmailVerificationCodeInput { """ @@ -2976,6 +4490,41 @@ type ResetPasswordPayload { success: Boolean } +"""All input for the `saveReminderPreferences` mutation.""" +input SaveReminderPreferencesInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + deliveryMethod: String! + minutesBefore: Int! +} + +"""The output of our `saveReminderPreferences` mutation.""" +type SaveReminderPreferencesPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query + reminderPreference: ReminderPreference + + """An edge for our `ReminderPreference`. May be used by Relay 1.""" + reminderPreferenceEdge( + """The method to use when ordering `ReminderPreference`.""" + orderBy: [ReminderPreferencesOrderBy!] = [PRIMARY_KEY_ASC] + ): ReminderPreferencesEdge + + """Reads a single `User` that is related to this `ReminderPreference`.""" + user: User +} + """All input for the `setAdminStatus` mutation.""" input SetAdminStatusInput { """ @@ -3002,6 +4551,103 @@ type SetAdminStatusPayload { success: Boolean } +"""All input for the `setEventRegistrationReminder` mutation.""" +input SetEventRegistrationReminderInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + deliveryMethod: String + enabled: Boolean! + eventId: UUID! + language: String + minutesBefore: Int +} + +"""The output of our `setEventRegistrationReminder` mutation.""" +type SetEventRegistrationReminderPayload { + boolean: Boolean + + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + +"""All input for the `setFeatureFlag` mutation.""" +input SetFeatureFlagInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + key: String! + state: FeatureState! +} + +"""The output of our `setFeatureFlag` mutation.""" +type SetFeatureFlagPayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + featureFlag: FeatureFlag + + """An edge for our `FeatureFlag`. May be used by Relay 1.""" + featureFlagEdge( + """The method to use when ordering `FeatureFlag`.""" + orderBy: [FeatureFlagsOrderBy!] = [PRIMARY_KEY_ASC] + ): FeatureFlagsEdge + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query +} + +"""All input for the `setRegistrationProfile` mutation.""" +input SetRegistrationProfileInput { + """ + An arbitrary string value with no semantic meaning. Will be included in the + payload verbatim. May be used to track mutations by the client. + """ + clientMutationId: String + dietaryRestrictions: String + telegram: String +} + +"""The output of our `setRegistrationProfile` mutation.""" +type SetRegistrationProfilePayload { + """ + The exact same `clientMutationId` that was provided in the mutation input, + unchanged and unused. May be used by a client to track mutations. + """ + clientMutationId: String + + """ + Our root query field type. Allows us to run any query from our mutation payload. + """ + query: Query + registrationProfile: RegistrationProfile + + """An edge for our `RegistrationProfile`. May be used by Relay 1.""" + registrationProfileEdge( + """The method to use when ordering `RegistrationProfile`.""" + orderBy: [RegistrationProfilesOrderBy!] = [PRIMARY_KEY_ASC] + ): RegistrationProfilesEdge + + """Reads a single `User` that is related to this `RegistrationProfile`.""" + user: User +} + """ A filter to be used against String fields. All fields are combined with a logical ‘and.’ """ @@ -3084,392 +4730,148 @@ input StringFilter { """ Equal to the specified value, treating null like an ordinary value (case-insensitive). - """ - notDistinctFromInsensitive: String - - """Does not end with the specified string (case-sensitive).""" - notEndsWith: String - - """Does not end with the specified string (case-insensitive).""" - notEndsWithInsensitive: String - - """Not equal to the specified value.""" - notEqualTo: String - - """Not equal to the specified value (case-insensitive).""" - notEqualToInsensitive: String - - """Not included in the specified list.""" - notIn: [String!] - - """Not included in the specified list (case-insensitive).""" - notInInsensitive: [String!] - - """Does not contain the specified string (case-sensitive).""" - notIncludes: String - - """Does not contain the specified string (case-insensitive).""" - notIncludesInsensitive: String - - """ - Does not match the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. - """ - notLike: String - - """ - Does not match the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. - """ - notLikeInsensitive: String - - """Does not start with the specified string (case-sensitive).""" - notStartsWith: String - - """Does not start with the specified string (case-insensitive).""" - notStartsWithInsensitive: String - - """Starts with the specified string (case-sensitive).""" - startsWith: String - - """Starts with the specified string (case-insensitive).""" - startsWithInsensitive: String -} - -""" -The root subscription type: contains events and live queries you can subscribe to with the `subscription` operation. - -#### Live Queries - -Live query fields are differentiated by containing `(live)` at the end of their -description, they are added for each field in the `Query` type. When you -subscribe to a live query field, the selection set will be evaluated and sent to -the client, and then most things\* that would cause the output of the selection -set to change will trigger the selection set to be re-evaluated and the results -to be re-sent to the client. - -_(\* Not everything: typically only changes to persisted data referenced by the query are detected, not computed fields.)_ - -Live queries can be very expensive, so try and keep them small and focussed. - -#### Events - -Event fields will run their selection set when, and only when, the specified -server-side event occurs. This makes them a lot more efficient than Live -Queries, but it is still recommended that you keep payloads fairly small. -""" -type Subscription { - """List all users. Only accessible to admin users. (live)""" - adminListUsers( - """Read all values in the set after (below) this cursor.""" - after: Cursor - - """Read all values in the set before (above) this cursor.""" - before: Cursor - - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: UserCondition - - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: UserFilter - - """Only read the first `n` values of the set.""" - first: Int - - """Only read the last `n` values of the set.""" - last: Int - - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int - - """The method to use when ordering `User`.""" - orderBy: [UsersOrderBy!] - ): UsersConnection - - """Returns the server time every second.""" - currentTime: Date! - - """The currently logged in user (or null if not logged in). (live)""" - currentUser: User - - """Triggered when the logged in user's record is updated in some way.""" - currentUserUpdated: UserSubscriptionPayload! - - """ (live)""" - event(id: UUID!): Event - - """ (live)""" - eventBySlug(slug: String!): Event - - """Reads and enables pagination through a set of `EventCategory`. (live)""" - eventCategories( - """Read all values in the set after (below) this cursor.""" - after: Cursor - - """Read all values in the set before (above) this cursor.""" - before: Cursor - - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: EventCategoryCondition - - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: EventCategoryFilter - - """Only read the first `n` values of the set.""" - first: Int - - """Only read the last `n` values of the set.""" - last: Int - - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int - - """The method to use when ordering `EventCategory`.""" - orderBy: [EventCategoriesOrderBy!] = [PRIMARY_KEY_ASC] - ): EventCategoriesConnection - - """ (live)""" - eventCategory(id: UUID!): EventCategory - - """ (live)""" - eventQuestion(id: UUID!): EventQuestion - - """Reads and enables pagination through a set of `EventQuestion`. (live)""" - eventQuestions( - """Read all values in the set after (below) this cursor.""" - after: Cursor - - """Read all values in the set before (above) this cursor.""" - before: Cursor - - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: EventQuestionCondition - - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: EventQuestionFilter - - """Only read the first `n` values of the set.""" - first: Int - - """Only read the last `n` values of the set.""" - last: Int - - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int - - """The method to use when ordering `EventQuestion`.""" - orderBy: [EventQuestionsOrderBy!] = [PRIMARY_KEY_ASC] - ): EventQuestionsConnection - - """ - Triggered when new event registrations are created or updated. Each event has its own subscription topic. - """ - eventRegistrations(eventId: UUID!): EventRegistrationsSubscriptionPayload! - - """Reads and enables pagination through a set of `Event`. (live)""" - events( - """Read all values in the set after (below) this cursor.""" - after: Cursor - - """Read all values in the set before (above) this cursor.""" - before: Cursor - - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: EventCondition - - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: EventFilter - - """Only read the first `n` values of the set.""" - first: Int - - """Only read the last `n` values of the set.""" - last: Int - - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int - - """The method to use when ordering `Event`.""" - orderBy: [EventsOrderBy!] = [PRIMARY_KEY_ASC] - ): EventsConnection - - """ (live)""" - organization(id: UUID!): Organization - - """ (live)""" - organizationBySlug(slug: String!): Organization - - """ - Given an invitation UUID (and, if required, the code that was emailed to you), retrieves the `Organization` that you were invited to. (live) - """ - organizationForInvitation(code: String, invitationId: UUID!): Organization - - """Reads and enables pagination through a set of `Organization`. (live)""" - organizations( - """Read all values in the set after (below) this cursor.""" - after: Cursor - - """Read all values in the set before (above) this cursor.""" - before: Cursor - - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: OrganizationCondition - - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: OrganizationFilter + """ + notDistinctFromInsensitive: String - """Only read the first `n` values of the set.""" - first: Int + """Does not end with the specified string (case-sensitive).""" + notEndsWith: String - """Only read the last `n` values of the set.""" - last: Int + """Does not end with the specified string (case-insensitive).""" + notEndsWithInsensitive: String - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int + """Not equal to the specified value.""" + notEqualTo: String - """The method to use when ordering `Organization`.""" - orderBy: [OrganizationsOrderBy!] = [PRIMARY_KEY_ASC] - ): OrganizationsConnection + """Not equal to the specified value (case-insensitive).""" + notEqualToInsensitive: String - """ (live)""" - quota(id: UUID!): Quota + """Not included in the specified list.""" + notIn: [String!] - """Reads and enables pagination through a set of `Quota`. (live)""" - quotas( - """Read all values in the set after (below) this cursor.""" - after: Cursor + """Not included in the specified list (case-insensitive).""" + notInInsensitive: [String!] - """Read all values in the set before (above) this cursor.""" - before: Cursor + """Does not contain the specified string (case-sensitive).""" + notIncludes: String - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: QuotaCondition + """Does not contain the specified string (case-insensitive).""" + notIncludesInsensitive: String - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: QuotaFilter + """ + Does not match the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + notLike: String - """Only read the first `n` values of the set.""" - first: Int + """ + Does not match the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + notLikeInsensitive: String - """Only read the last `n` values of the set.""" - last: Int + """Does not start with the specified string (case-sensitive).""" + notStartsWith: String - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int + """Does not start with the specified string (case-insensitive).""" + notStartsWithInsensitive: String - """The method to use when ordering `Quota`.""" - orderBy: [QuotasOrderBy!] = [PRIMARY_KEY_ASC] - ): QuotasConnection + """Starts with the specified string (case-sensitive).""" + startsWith: String - """ (live)""" - registration(id: UUID!): Registration + """Starts with the specified string (case-insensitive).""" + startsWithInsensitive: String +} - """Get registration by update token. (live)""" - registrationByUpdateToken(updateToken: String!): Registration +""" +The root subscription type: contains realtime events you can subscribe to with the `subscription` operation. +""" +type Subscription { + """Returns the server time every second.""" + currentTime: Date! - """Reads and enables pagination through a set of `Registration`. (live)""" - registrations( - """Read all values in the set after (below) this cursor.""" - after: Cursor + """Triggered when the logged in user's record is updated in some way.""" + currentUserUpdated: UserSubscriptionPayload! - """Read all values in the set before (above) this cursor.""" - before: Cursor + """ + Triggered when new event registrations are created or updated. Each event has its own subscription topic. + """ + eventRegistrations(eventId: UUID!): EventRegistrationsSubscriptionPayload! +} - """ - A condition to be used in determining which values should be returned by the collection. - """ - condition: RegistrationCondition +enum SupportedLanguages { + EN + FI +} - """ - A filter to be used in determining which values should be returned by the collection. - """ - filter: RegistrationFilter +"""Telegram accounts linked by their owners.""" +type TelegramAccount { + createdAt: Datetime! - """Only read the first `n` values of the set.""" - first: Int + """Reads a single `User` that is related to this `TelegramAccount`.""" + user: User + userId: UUID! + username: String +} - """Only read the last `n` values of the set.""" - last: Int +""" +A condition to be used against `TelegramAccount` object types. All fields are +tested for equality and combined with a logical ‘and.’ +""" +input TelegramAccountCondition { + """Checks for equality with the object’s `userId` field.""" + userId: UUID +} - """ - Skip the first `n` values from our `after` cursor, an alternative to cursor - based pagination. May not be used with `last`. - """ - offset: Int +""" +A filter to be used against `TelegramAccount` object types. All fields are combined with a logical ‘and.’ +""" +input TelegramAccountFilter { + """Checks for all expressions in this list.""" + and: [TelegramAccountFilter!] - """The method to use when ordering `Registration`.""" - orderBy: [RegistrationsOrderBy!] = [PRIMARY_KEY_ASC] - ): RegistrationsConnection + """Negates the expression.""" + not: TelegramAccountFilter - """ - Use this query to render server-side mjml templates to html and text. (live) - """ - renderEmailTemplate(input: RenderEmailInput!): EmailTemplate + """Checks for any expressions in this list.""" + or: [TelegramAccountFilter!] + + """Filter by the object’s `userId` field.""" + userId: UUIDFilter +} +"""A connection to a list of `TelegramAccount` values.""" +type TelegramAccountsConnection { """ - Use this query to render all server-side email templates to html and text. (live) + A list of edges which contains the `TelegramAccount` and cursor to aid in pagination. """ - renderEmailTemplates: EmailTemplatesConnection + edges: [TelegramAccountsEdge!]! - """True when Keycloak SSO login is configured on this server. (live)""" - ssoLoginEnabled: Boolean! + """A list of `TelegramAccount` objects.""" + nodes: [TelegramAccount!]! - """Supported languages of the app. (live)""" - supportedLanguages: [SupportedLanguages] + """Information to aid in pagination.""" + pageInfo: PageInfo! - """ (live)""" - user(id: UUID!): User + """ + The count of *all* `TelegramAccount` you could get from the connection. + """ + totalCount: Int! +} - """ (live)""" - userAuthentication(id: UUID!): UserAuthentication +"""A `TelegramAccount` edge in the connection.""" +type TelegramAccountsEdge { + """A cursor for use in pagination.""" + cursor: Cursor - """ (live)""" - userEmail(id: UUID!): UserEmail + """The `TelegramAccount` at the end of the edge.""" + node: TelegramAccount! } -enum SupportedLanguages { - EN - FI +"""Methods to use when ordering `TelegramAccount`.""" +enum TelegramAccountsOrderBy { + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + USER_ID_ASC + USER_ID_DESC } """All input for the `transferOrganizationOwnership` mutation.""" @@ -3712,6 +5114,7 @@ input UpdateEventQuestionInput { isRequired: Boolean label: TranslatedField position: Int + prefill: QuestionPrefill type: QuestionType } @@ -3719,6 +5122,7 @@ input UpdateEventQuestionInput { input UpdateEventQuotaInput { id: UUID position: Int + priceCents: Int size: Int title: JSON } @@ -3852,6 +5256,47 @@ type User { """Optional avatar URL.""" avatarUrl: String createdAt: Datetime! + + """ + Reads and enables pagination through a set of `EventRegistrationReminder`. + """ + eventRegistrationReminders( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: EventRegistrationReminderCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: EventRegistrationReminderFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `EventRegistrationReminder`.""" + orderBy: [EventRegistrationRemindersOrderBy!] = [PRIMARY_KEY_ASC] + ): EventRegistrationRemindersConnection! + + """ + The user's first name(s), from the Keycloak `given_name` claim. Null for users that have not logged in with Keycloak. + """ + firstName: String hasPassword: Boolean """Unique identifier for the user.""" @@ -3859,8 +5304,18 @@ type User { """If true, the user has elevated privileges.""" isAdmin: Boolean! + + """ + If true and the user is also an admin, the user can manage feature flags. + """ + isDeveloper: Boolean! isVerified: Boolean! + """ + The user's last name, from the Keycloak `family_name` claim. Null for users that have not logged in with Keycloak. + """ + lastName: String + """Public-facing name (or pseudonym) of the user.""" name: String @@ -3902,6 +5357,83 @@ type User { """Users primary email.""" primaryEmail: String + + """Reads a single `RegistrationProfile` that is related to this `User`.""" + registrationProfile: RegistrationProfile + + """Reads a single `ReminderPreference` that is related to this `User`.""" + reminderPreference: ReminderPreference + + """Reads and enables pagination through a set of `ReminderPreference`.""" + reminderPreferences( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: ReminderPreferenceCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: ReminderPreferenceFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `ReminderPreference`.""" + orderBy: [ReminderPreferencesOrderBy!] = [PRIMARY_KEY_ASC] + ): ReminderPreferencesConnection! @deprecated(reason: "Please use reminderPreference instead") + + """Reads a single `TelegramAccount` that is related to this `User`.""" + telegramAccount: TelegramAccount + + """Reads and enables pagination through a set of `TelegramAccount`.""" + telegramAccounts( + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """ + A condition to be used in determining which values should be returned by the collection. + """ + condition: TelegramAccountCondition + + """ + A filter to be used in determining which values should be returned by the collection. + """ + filter: TelegramAccountFilter + + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """The method to use when ordering `TelegramAccount`.""" + orderBy: [TelegramAccountsOrderBy!] = [PRIMARY_KEY_ASC] + ): TelegramAccountsConnection! @deprecated(reason: "Please use telegramAccount instead") updatedAt: Datetime! """Reads and enables pagination through a set of `UserAuthentication`.""" diff --git a/data/schema.sql b/data/schema.sql index 80709ee2a..3040a3f54 100644 --- a/data/schema.sql +++ b/data/schema.sql @@ -117,14 +117,32 @@ CREATE TYPE app_public.claim_registration_token_output AS ( -- CREATE DOMAIN app_public.constrained_name AS text - CONSTRAINT constrained_name_check CHECK ((VALUE !~ '\s'::text)); + CONSTRAINT constrained_name_check CHECK ((VALUE ~ '\S'::text)); -- -- Name: DOMAIN constrained_name; Type: COMMENT; Schema: app_public; Owner: - -- -COMMENT ON DOMAIN app_public.constrained_name IS 'A field which must not contain spaces'; +COMMENT ON DOMAIN app_public.constrained_name IS 'A name field which must not be empty or contain only whitespace'; + + +-- +-- Name: question_prefill; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.question_prefill AS ENUM ( + 'TELEGRAM', + 'DIETARY_RESTRICTIONS', + 'NONE' +); + + +-- +-- Name: TYPE question_prefill; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.question_prefill IS 'Which registration profile field prefills the answer to a question. NONE is only an input value: it clears the prefill of a question in `updateEvent`, where an omitted prefill keeps the stored one.'; -- @@ -185,7 +203,8 @@ CREATE TYPE app_public.create_event_questions AS ( type app_public.question_type, label app_public.translated_field, is_required boolean, - data app_public.translated_field[] + data app_public.translated_field[], + prefill app_public.question_prefill ); @@ -196,7 +215,8 @@ CREATE TYPE app_public.create_event_questions AS ( CREATE TYPE app_public.create_event_quotas AS ( "position" smallint, title jsonb, - size smallint + size smallint, + price_cents integer ); @@ -226,10 +246,50 @@ CREATE TYPE app_public.event_input AS ( header_image_file text, open_quota_size smallint, owner_organization_id uuid, - category_id uuid + category_id uuid, + highlight_text app_public.translated_field +); + + +-- +-- Name: event_payment_summary; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.event_payment_summary AS ( + paid_count integer, + unpaid_count integer, + due_count integer, + tickets_paid_cents integer, + guild_receives_cents integer, + unlinked_card_payment_count integer +); + + +-- +-- Name: TYPE event_payment_summary; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.event_payment_summary IS 'Payment totals for an event, for organizers.'; + + +-- +-- Name: feature_state; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.feature_state AS ENUM ( + 'off', + 'admins_only', + 'on' ); +-- +-- Name: TYPE feature_state; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.feature_state IS 'State of a feature flag: off for everyone, on for signed-in admins only, or on for everyone.'; + + -- -- Name: hex_color; Type: DOMAIN; Schema: app_public; Owner: - -- @@ -238,6 +298,60 @@ CREATE DOMAIN app_public.hex_color AS text CONSTRAINT hex_color_check CHECK ((VALUE ~* '^#[a-f0-9]{6}$'::text)); +-- +-- Name: payment_method; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.payment_method AS ENUM ( + 'STRIPE', + 'MANUAL' +); + + +-- +-- Name: TYPE payment_method; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.payment_method IS 'How a payment was made: by card through Stripe Checkout, or marked paid by an organizer (cash, bank transfer).'; + + +-- +-- Name: payment_status; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.payment_status AS ENUM ( + 'PENDING', + 'PAID', + 'EXPIRED' +); + + +-- +-- Name: TYPE payment_status; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.payment_status IS 'State of a single payment attempt.'; + + +-- +-- Name: registration_payment_status; Type: TYPE; Schema: app_public; Owner: - +-- + +CREATE TYPE app_public.registration_payment_status AS ENUM ( + 'NOT_REQUIRED', + 'UNPAID', + 'PAID', + 'PAID_MANUALLY' +); + + +-- +-- Name: TYPE registration_payment_status; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TYPE app_public.registration_payment_status IS 'Payment state of a registration as shown to organizers.'; + + -- -- Name: registration_status; Type: TYPE; Schema: app_public; Owner: - -- @@ -259,7 +373,8 @@ CREATE TYPE app_public.update_event_questions AS ( type app_public.question_type, label app_public.translated_field, is_required boolean, - data app_public.translated_field[] + data app_public.translated_field[], + prefill app_public.question_prefill ); @@ -271,7 +386,8 @@ CREATE TYPE app_public.update_event_quotas AS ( id uuid, "position" smallint, title jsonb, - size smallint + size smallint, + price_cents integer ); @@ -291,6 +407,73 @@ end; $$; +-- +-- Name: connect_telegram(text, bigint, text); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.connect_telegram(token text, chat_id bigint, username text) RETURNS boolean + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + +-- +-- Name: current_user_can_manage_event_payments(uuid); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.current_user_can_manage_event_payments(event_id uuid) RETURNS boolean + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select app_public.current_user_is_admin() + or app_public.current_user_has_event_permissions(event_id); +$$; + + +-- +-- Name: FUNCTION current_user_can_manage_event_payments(event_id uuid); Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON FUNCTION app_private.current_user_can_manage_event_payments(event_id uuid) IS 'True if the current user may see and manage payments of the event: admins and members of the event''s owner organization.'; + + +-- +-- Name: disconnect_telegram(uuid); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.disconnect_telegram(target_user uuid) RETURNS void + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + SET default_tablespace = ''; SET default_table_access_method = heap; @@ -308,6 +491,9 @@ CREATE TABLE app_public.users ( is_verified boolean DEFAULT false NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, updated_at timestamp with time zone DEFAULT now() NOT NULL, + is_developer boolean DEFAULT false NOT NULL, + first_name text, + last_name text, CONSTRAINT users_avatar_url_check CHECK ((avatar_url ~ '^https?://[^/]+'::text)), CONSTRAINT users_username_check CHECK (((length((username)::text) >= 2) AND (length((username)::text) <= 24) AND (username OPERATOR(public.~) '^[a-zA-Z]([_]?[a-zA-Z0-9])+$'::public.citext))) ); @@ -355,6 +541,27 @@ COMMENT ON COLUMN app_public.users.avatar_url IS 'Optional avatar URL.'; COMMENT ON COLUMN app_public.users.is_admin IS 'If true, the user has elevated privileges.'; +-- +-- Name: COLUMN users.is_developer; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.users.is_developer IS 'If true and the user is also an admin, the user can manage feature flags.'; + + +-- +-- Name: COLUMN users.first_name; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.users.first_name IS 'The user''s first name(s), from the Keycloak `given_name` claim. Null for users that have not logged in with Keycloak.'; + + +-- +-- Name: COLUMN users.last_name; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.users.last_name IS 'The user''s last name, from the Keycloak `family_name` claim. Null for users that have not logged in with Keycloak.'; + + -- -- Name: link_or_register_user(uuid, character varying, character varying, json, json); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -471,10 +678,28 @@ CREATE TABLE app_private.sessions ( uuid uuid DEFAULT gen_random_uuid() NOT NULL, user_id uuid NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, - last_active timestamp with time zone DEFAULT now() NOT NULL + last_active timestamp with time zone DEFAULT now() NOT NULL, + kind text DEFAULT 'web'::text NOT NULL, + oauth_sid text, + CONSTRAINT sessions_kind_check CHECK ((kind = ANY (ARRAY['web'::text, 'mcp'::text]))), + CONSTRAINT sessions_oauth_sid_check CHECK (((kind = 'mcp'::text) = (oauth_sid IS NOT NULL))) ); +-- +-- Name: COLUMN sessions.kind; Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON COLUMN app_private.sessions.kind IS 'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; + + +-- +-- Name: COLUMN sessions.oauth_sid; Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON COLUMN app_private.sessions.oauth_sid IS 'Keycloak session id (the access token sid claim) of an mcp session.'; + + -- -- Name: login(public.citext, text); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -607,6 +832,101 @@ $$; COMMENT ON FUNCTION app_private.really_create_user(username public.citext, email text, name text, avatar_url text, password text, email_is_verified boolean, is_admin boolean) IS 'Creates a user account. All arguments are optional, it trusts the calling method to perform sanitisation.'; +-- +-- Name: refresh_registration_positions(uuid); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.refresh_registration_positions(p_event_id uuid) RETURNS void + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +declare + v_queued uuid[]; +begin + perform pg_advisory_xact_lock(hashtext('registration_positions:' || p_event_id::text)); + + select coalesce(array_agg(id), '{}') + into v_queued + from app_hidden.registrations_status_and_position + where event_id = p_event_id and status = 'IN_QUEUE'::app_public.registration_status; + + delete from app_hidden.registrations_status_and_position + where event_id = p_event_id; + + insert into app_hidden.registrations_status_and_position(id, event_id, quota_id, status, position) + with cte1 as ( + select + r.id, + size, + r.event_id, + r.quota_id, + e.open_quota_size, + r.created_at, + row_number() over (partition by r.quota_id order by r.created_at asc) as tmp_pos_quota + from app_public.registrations r + left join app_public.quotas q + on r.quota_id = q.id + left join app_public.events e + on r.event_id = e.id + where r.event_id = p_event_id + ), cte2 as ( + select + tmp.*, + row_number() over (partition by event_id, tmp_status order by created_at asc) as tmp_pos_status + from ( + select + *, + case + when tmp_pos_quota <= size then 'IN_QUOTA'::text + else 'OPEN_OR_QUEUE'::text + end as tmp_status + from cte1 + ) as tmp + ), cte3 as ( + select + *, + case + when tmp_status = 'OPEN_OR_QUEUE'::text and tmp_pos_status <= open_quota_size then 'IN_OPEN_QUOTA'::app_public.registration_status + when tmp_status = 'OPEN_OR_QUEUE'::text then 'IN_QUEUE'::app_public.registration_status + else 'IN_QUOTA'::app_public.registration_status + end as status + from cte2 + ) select + id, + event_id, + quota_id, + status, + case + -- row_number() returns bigint but we cast it to integer to avoid + -- introducing another type to our GraphQL API. Besides, we are not + -- expecting to have that many registrations in the system. + when status = 'IN_QUOTA'::app_public.registration_status then cast(row_number() over (partition by quota_id, status order by created_at asc) as integer) + else cast(row_number() over (partition by event_id, status order by created_at asc) as integer) + end as position + from cte3; + + perform graphile_worker.add_job( + 'registration__process_queue', + json_build_object('receivedSpot', received_spot) + ) + from app_hidden.registrations_status_and_position received_spot + join app_public.registrations r on r.id = received_spot.id + where + received_spot.event_id = p_event_id and + received_spot.id = any(v_queued) and + received_spot.status <> 'IN_QUEUE'::app_public.registration_status and + r.is_finished; +end; +$$; + + +-- +-- Name: FUNCTION refresh_registration_positions(p_event_id uuid); Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON FUNCTION app_private.refresh_registration_positions(p_event_id uuid) IS 'Recomputes app_hidden.registrations_status_and_position for the registrations of one event.'; + + -- -- Name: register_user(character varying, character varying, json, json, boolean); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -683,6 +1003,127 @@ $$; COMMENT ON FUNCTION app_private.register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean) IS 'Used to register a user from information gleaned from OAuth. Primarily used by link_or_register_user'; +-- +-- Name: registrations; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.registrations ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + event_id uuid NOT NULL, + quota_id uuid NOT NULL, + first_name app_public.constrained_name, + last_name app_public.constrained_name, + email app_public.email, + answers jsonb, + is_finished boolean DEFAULT false NOT NULL, + created_by uuid, + updated_by uuid, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: TABLE registrations; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.registrations IS 'Main table for registrations.'; + + +-- +-- Name: COLUMN registrations.id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.id IS 'Unique identifier for the registration.'; + + +-- +-- Name: COLUMN registrations.event_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.event_id IS 'Identifier of a related event.'; + + +-- +-- Name: COLUMN registrations.quota_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.quota_id IS 'Identifier of a related quota.'; + + +-- +-- Name: COLUMN registrations.first_name; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.first_name IS 'First name of the person registered to an event.'; + + +-- +-- Name: COLUMN registrations.last_name; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.last_name IS 'Last name of the person registered to an event.'; + + +-- +-- Name: COLUMN registrations.email; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.email IS '@omit +Email address of the person registered to an event.'; + + +-- +-- Name: COLUMN registrations.answers; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.answers IS 'Answers to event questions.'; + + +-- +-- Name: COLUMN registrations.is_finished; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registrations.is_finished IS 'True if the registration is completed succesfully.'; + + +-- +-- Name: registration_payment_status(app_public.registrations); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.registration_payment_status(registration app_public.registrations) RETURNS app_public.registration_payment_status + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select + case + when exists( + select 1 from app_public.payments as p + where p.registration_id = registration.id and p.status = 'PAID' and p.method = 'MANUAL' + ) + then 'PAID_MANUALLY'::app_public.registration_payment_status + when exists( + select 1 from app_public.payments as p + where p.registration_id = registration.id and p.status = 'PAID' + ) + then 'PAID'::app_public.registration_payment_status + when registration.is_finished is true and exists( + select 1 from app_public.quotas as q + where q.id = registration.quota_id and q.price_cents > 0 + ) + then 'UNPAID'::app_public.registration_payment_status + else 'NOT_REQUIRED'::app_public.registration_payment_status + end; +$$; + + +-- +-- Name: FUNCTION registration_payment_status(registration app_public.registrations); Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON FUNCTION app_private.registration_payment_status(registration app_public.registrations) IS 'Payment status of the registration, without a permission check.'; + + -- -- Name: reset_password(uuid, text, text); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -755,6 +1196,64 @@ end; $$; +-- +-- Name: schedule_registration_reminder(uuid); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.schedule_registration_reminder(reminder_id uuid) RETURNS void + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + +-- +-- Name: set_feature_available(text, boolean); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.set_feature_available(key text, available boolean) RETURNS boolean + LANGUAGE sql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + with updated as ( + update app_public.feature_flags as f + set available = set_feature_available.available + where f.key = set_feature_available.key + returning 1 + ) + select exists (select 1 from updated); +$$; + + +-- +-- Name: FUNCTION set_feature_available(key text, available boolean); Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON FUNCTION app_private.set_feature_available(key text, available boolean) IS 'Records whether the server has the configuration a feature needs. Returns false for an unknown key. Does not change `updated_at`, which tracks state changes.'; + + -- -- Name: tg__add_audit_job(); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -871,71 +1370,25 @@ COMMENT ON FUNCTION app_private.tg__ownership_info() IS 'This trigger should be -- --- Name: tg__process_queue(); Type: FUNCTION; Schema: app_private; Owner: - +-- Name: tg__refresh_registration_positions(); Type: FUNCTION; Schema: app_private; Owner: - -- -CREATE FUNCTION app_private.tg__process_queue() RETURNS trigger - LANGUAGE plpgsql +CREATE FUNCTION app_private.tg__refresh_registration_positions() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' AS $$ -declare - v_old_registration_status app_hidden.registrations_status_and_position; - v_received_spot app_hidden.registrations_status_and_position; begin - select * - into v_old_registration_status - from app_hidden.registrations_status_and_position - where - id = OLD.id; - - if v_old_registration_status.status = 'IN_QUOTA' then - select * - into v_received_spot - from app_hidden.registrations_status_and_position - where - event_id = v_old_registration_status.event_id and - quota_id = v_old_registration_status.quota_id and - status = 'IN_QUEUE'::app_public.registration_status and - position = 1 - order by position desc; - elsif v_old_registration_status.status = 'IN_OPEN_QUOTA' then - select * - into v_received_spot - from app_hidden.registrations_status_and_position - where - -- Almost the same where condition as above, only quota_id is - -- missing since open quota spots can be populated by any quota - event_id = v_old_registration_status.event_id and - status = 'IN_QUEUE'::app_public.registration_status and - position = 1 - order by position desc; - else - -- The deleted registration was in queue, nobody will get a spot so return. - return OLD; + if TG_TABLE_NAME = 'events' then + perform app_private.refresh_registration_positions(coalesce(NEW.id, OLD.id)); + return null; end if; - if v_received_spot is not null then - perform graphile_worker.add_job( - 'registration__process_queue', - json_build_object('receivedSpot', v_received_spot) - ); + if TG_OP in ('UPDATE', 'DELETE') then + perform app_private.refresh_registration_positions(OLD.event_id); + end if; + if TG_OP = 'INSERT' or (TG_OP = 'UPDATE' and NEW.event_id is distinct from OLD.event_id) then + perform app_private.refresh_registration_positions(NEW.event_id); end if; - - return OLD; -end; -$$; - - --- --- Name: tg__refresh_materialized_view(); Type: FUNCTION; Schema: app_private; Owner: - --- - -CREATE FUNCTION app_private.tg__refresh_materialized_view() RETURNS trigger - LANGUAGE plpgsql SECURITY DEFINER - SET search_path TO 'pg_catalog', 'public', 'pg_temp' - AS $$ -begin - -- Docs on CONCURRENTLY option: https://www.postgresql.org/docs/12/sql-refreshmaterializedview.html - refresh materialized view concurrently app_hidden.registrations_status_and_position; return null; end; $$; @@ -976,6 +1429,47 @@ $$; COMMENT ON FUNCTION app_private.tg__registration_is_valid() IS 'This trigger validates that a registration is valid. That is, the related event is open to registrations.'; +-- +-- Name: tg__reschedule_registration_reminders(); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.tg__reschedule_registration_reminders() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + +-- +-- Name: tg__schedule_registration_reminder(); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.tg__schedule_registration_reminder() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + -- -- Name: tg__timestamps(); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -999,6 +1493,28 @@ $$; COMMENT ON FUNCTION app_private.tg__timestamps() IS 'This trigger should be called on all tables with created_at, updated_at - it ensures that they cannot be manipulated and that updated_at will always be larger than the previous updated_at.'; +-- +-- Name: tg_events__reset_unpaid_close_email(); Type: FUNCTION; Schema: app_private; Owner: - +-- + +CREATE FUNCTION app_private.tg_events__reset_unpaid_close_email() RETURNS trigger + LANGUAGE plpgsql + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +begin + NEW.unpaid_close_email_sent_at := null; + return NEW; +end; +$$; + + +-- +-- Name: FUNCTION tg_events__reset_unpaid_close_email(); Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON FUNCTION app_private.tg_events__reset_unpaid_close_email() IS 'Clears events.unpaid_close_email_sent_at when registration_end_time moves later.'; + + -- -- Name: tg_user_email_secrets__insert_with_user_email(); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -1172,6 +1688,344 @@ COMMENT ON FUNCTION app_public.admin_list_users() IS '@sortable List all users. Only accessible to admin users.'; +-- +-- Name: payments; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.payments ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + registration_id uuid, + event_id uuid, + quota_id uuid, + event_name jsonb NOT NULL, + quota_title jsonb NOT NULL, + method app_public.payment_method NOT NULL, + status app_public.payment_status DEFAULT 'PENDING'::app_public.payment_status NOT NULL, + ticket_amount_cents integer NOT NULL, + service_fee_cents integer DEFAULT 0 NOT NULL, + currency text DEFAULT 'eur'::text NOT NULL, + stripe_checkout_session_id text, + stripe_payment_intent_id text, + paid_at timestamp with time zone, + created_by uuid, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT payments_service_fee_cents_check CHECK ((service_fee_cents >= 0)), + CONSTRAINT payments_ticket_amount_cents_check CHECK ((ticket_amount_cents >= 0)) +); + + +-- +-- Name: TABLE payments; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.payments IS '@omit create,update,delete +Payments for registrations. Rows outlive their registration (and event and quota) so they can be reconciled with Stripe payouts; they hold no personal data. Ilmo never refunds: a card payment without a registration is refunded by hand in Stripe, if at all.'; + + +-- +-- Name: COLUMN payments.registration_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.registration_id IS 'The registration paid for. Null once the registration has been deleted, and for a card payment that could not be applied to it (a second payment, or an amount that did not match).'; + + +-- +-- Name: COLUMN payments.event_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.event_id IS 'The event paid for. Null once the event has been deleted.'; + + +-- +-- Name: COLUMN payments.quota_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.quota_id IS 'The quota paid for. Null once the quota has been deleted.'; + + +-- +-- Name: COLUMN payments.event_name; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.event_name IS 'Snapshot of the event name when the payment was created.'; + + +-- +-- Name: COLUMN payments.quota_title; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.quota_title IS 'Snapshot of the quota title when the payment was created.'; + + +-- +-- Name: COLUMN payments.ticket_amount_cents; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.ticket_amount_cents IS 'Ticket price paid, in cents: the quota price when the payment was started.'; + + +-- +-- Name: COLUMN payments.service_fee_cents; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.service_fee_cents IS 'Service fee paid on top of the ticket, in cents. 0 for manual payments.'; + + +-- +-- Name: COLUMN payments.created_by; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.payments.created_by IS 'The organizer who recorded a manual payment.'; + + +-- +-- Name: admin_mark_registration_paid(uuid); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.admin_mark_registration_paid(registration_id uuid) RETURNS app_public.payments + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +declare + v_registration app_public.registrations; + v_event app_public.events; + v_quota app_public.quotas; + v_payment app_public.payments; +begin + select * into v_registration + from app_public.registrations as r + where r.id = admin_mark_registration_paid.registration_id; + + if v_registration.id is null then + raise exception 'Registration was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(v_registration.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + select * into v_event from app_public.events where id = v_registration.event_id; + select * into v_quota from app_public.quotas where id = v_registration.quota_id; + + if v_registration.is_finished is not true or v_quota.price_cents = 0 then + raise exception 'This registration does not require payment.' using errcode = 'DNIED'; + end if; + + if exists( + select 1 from app_public.payments as p + where p.registration_id = v_registration.id and p.status = 'PAID' + ) then + raise exception 'This registration has already been paid.' using errcode = 'DNIED'; + end if; + + -- Queued registrations pay once they get a spot, like on the /pay page + if exists( + select 1 from app_hidden.registrations_status_and_position as s + where s.id = v_registration.id and s.status = 'IN_QUEUE' + ) then + raise exception 'This registration is in the queue.' using errcode = 'DNIED'; + end if; + + insert into app_public.payments ( + registration_id, + event_id, + quota_id, + event_name, + quota_title, + method, + status, + ticket_amount_cents, + service_fee_cents, + paid_at, + created_by + ) + values ( + v_registration.id, + v_registration.event_id, + v_registration.quota_id, + v_event.name, + v_quota.title, + 'MANUAL', + 'PAID', + v_quota.price_cents, + 0, + now(), + app_public.current_user_id() + ) + returning * into v_payment; + + perform graphile_worker.add_job( + 'payment__send_received_email', + json_build_object('paymentId', v_payment.id) + ); + + return v_payment; +end; +$$; + + +-- +-- Name: FUNCTION admin_mark_registration_paid(registration_id uuid); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.admin_mark_registration_paid(registration_id uuid) IS 'Records a manual payment (cash, bank transfer) of the current quota price for a registration and emails the participant a payment confirmation.'; + + +-- +-- Name: admin_preview_features(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.admin_preview_features() RETURNS SETOF text + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select f.key + from app_public.feature_flags as f + where + app_public.current_user_is_admin() + and f.retired_at is null + and f.available + and f.state = 'admins_only' + order by f.key; +$$; + + +-- +-- Name: FUNCTION admin_preview_features(); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.admin_preview_features() IS '@simpleCollections only +Keys of the features enabled for the current user only because they are in admins_only. Empty unless the current user is an admin.'; + + +-- +-- Name: admin_send_payment_reminders(uuid); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.admin_send_payment_reminders(event_id uuid) RETURNS integer + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +declare + v_registration_id uuid; + v_count integer := 0; + v_last_sent_at timestamptz; +begin + if not exists(select 1 from app_public.events as e where e.id = admin_send_payment_reminders.event_id) then + raise exception 'Event was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(admin_send_payment_reminders.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + -- A short cooldown, so a double click or a script can't email everyone + -- many times over. The event row lock makes concurrent calls wait here + -- and then see the first call's timestamp. + select e.last_payment_reminder_sent_at into v_last_sent_at + from app_public.events as e + where e.id = admin_send_payment_reminders.event_id + for update; + if v_last_sent_at > now() - interval '10 minutes' then + raise exception 'Payment reminders were sent less than 10 minutes ago. Try again later.' using errcode = 'DNIED'; + end if; + + for v_registration_id in + select r.id + from app_public.registrations as r + join app_hidden.registrations_status_and_position as s on s.id = r.id + where + r.event_id = admin_send_payment_reminders.event_id + and r.is_finished is true + and s.status in ('IN_QUOTA', 'IN_OPEN_QUOTA') + and app_public.registrations_payment_status(r) = 'UNPAID' + order by r.created_at, r.id + loop + perform graphile_worker.add_job( + 'payment__send_reminder', + json_build_object('registrationId', v_registration_id) + ); + v_count := v_count + 1; + end loop; + + if v_count > 0 then + update app_public.events as e + set last_payment_reminder_sent_at = now() + where e.id = admin_send_payment_reminders.event_id; + end if; + + return v_count; +end; +$$; + + +-- +-- Name: FUNCTION admin_send_payment_reminders(event_id uuid); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.admin_send_payment_reminders(event_id uuid) IS 'Emails a payment reminder to every finished, unpaid registration holding a spot in the event. Returns the number of reminders queued. Refused for 10 minutes after the last reminders were sent.'; + + +-- +-- Name: admin_unmark_registration_paid(uuid); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.admin_unmark_registration_paid(registration_id uuid) RETURNS boolean + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +declare + v_registration app_public.registrations; + v_deleted_count integer; +begin + select * into v_registration + from app_public.registrations as r + where r.id = admin_unmark_registration_paid.registration_id; + + if v_registration.id is null then + raise exception 'Registration was not found.' using errcode = 'NTFND'; + end if; + + if not app_private.current_user_can_manage_event_payments(v_registration.event_id) then + raise exception 'Access denied.' using errcode = 'DNIED'; + end if; + + if not app_public.feature_enabled('payments') then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + + delete from app_public.payments as p + where + p.registration_id = v_registration.id + and p.method = 'MANUAL' + and p.status = 'PAID'; + + get diagnostics v_deleted_count = row_count; + if v_deleted_count = 0 then + raise exception 'This registration has no manual payment.' using errcode = 'NTFND'; + end if; + + return true; +end; +$$; + + +-- +-- Name: FUNCTION admin_unmark_registration_paid(registration_id uuid); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.admin_unmark_registration_paid(registration_id uuid) IS 'Removes a manual payment recorded with adminMarkRegistrationPaid. Card payments cannot be undone this way.'; + + -- -- Name: admin_update_registration(uuid); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -1275,6 +2129,21 @@ end; $$; +-- +-- Name: check_is_developer(); Type: PROCEDURE; Schema: app_public; Owner: - +-- + +CREATE PROCEDURE app_public.check_is_developer() + LANGUAGE plpgsql + AS $$ +begin + if not app_public.current_user_is_developer() then + raise exception 'Access denied. Only developers are allowed to use this mutation.' using errcode = 'DNIED'; + end if; +end; +$$; + + -- -- Name: check_is_logged_in(text); Type: PROCEDURE; Schema: app_public; Owner: - -- @@ -1422,6 +2291,9 @@ CREATE TABLE app_public.events ( updated_by uuid, created_at timestamp with time zone DEFAULT now() NOT NULL, updated_at timestamp with time zone DEFAULT now() NOT NULL, + highlight_text app_public.translated_field, + unpaid_close_email_sent_at timestamp with time zone, + last_payment_reminder_sent_at timestamp with time zone, CONSTRAINT _cnstr_check_event_registration_time CHECK ((registration_start_time < registration_end_time)), CONSTRAINT _cnstr_check_event_time CHECK ((event_start_time < event_end_time)), CONSTRAINT _cnstr_check_events_open_quota_size CHECK ((open_quota_size >= 0)), @@ -1542,6 +2414,27 @@ COMMENT ON COLUMN app_public.events.owner_organization_id IS 'Identifier of the COMMENT ON COLUMN app_public.events.category_id IS 'Identifier of a related event category.'; +-- +-- Name: COLUMN events.highlight_text; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.events.highlight_text IS 'Text shown on the ribbon of a highlighted event.'; + + +-- +-- Name: COLUMN events.unpaid_close_email_sent_at; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.events.unpaid_close_email_sent_at IS 'When the close-of-registration payment email was sent. Set by the worker; cleared when registration_end_time moves later, so that the email goes out again at the new close.'; + + +-- +-- Name: COLUMN events.last_payment_reminder_sent_at; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.events.last_payment_reminder_sent_at IS 'When an organizer last sent payment reminders to all unpaid participants.'; + + -- -- Name: create_event(app_public.event_input, app_public.create_event_quotas[], app_public.create_event_questions[]); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -1568,6 +2461,7 @@ begin registration_start_time, registration_end_time, is_highlighted, + highlight_text, is_draft, header_image_file, open_quota_size, @@ -1584,6 +2478,7 @@ begin event.registration_start_time, event.registration_end_time, event.is_highlighted, + event.highlight_text, event.is_draft, event.header_image_file, event.open_quota_size, @@ -1663,6 +2558,9 @@ CREATE TABLE app_public.event_questions ( updated_by uuid, created_at timestamp with time zone DEFAULT now() NOT NULL, updated_at timestamp with time zone DEFAULT now() NOT NULL, + prefill app_public.question_prefill, + CONSTRAINT _cnstr_prefill_not_none CHECK ((prefill <> 'NONE'::app_public.question_prefill)), + CONSTRAINT _cnstr_prefill_text_only CHECK (((prefill IS NULL) OR (type = 'TEXT'::app_public.question_type))), CONSTRAINT _cnstr_validate_question_data CHECK (app_public.validate_question_data(type, data)) ); @@ -1723,6 +2621,13 @@ COMMENT ON COLUMN app_public.event_questions.is_required IS 'If true, the questi COMMENT ON COLUMN app_public.event_questions.data IS 'Question data.'; +-- +-- Name: COLUMN event_questions.prefill; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.event_questions.prefill IS 'Which registration profile field prefills the answer to this question, if any.'; + + -- -- Name: create_event_questions(uuid, app_public.create_event_questions[]); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -1745,8 +2650,8 @@ begin -- Create questions foreach v_input in array questions loop - insert into app_public.event_questions(event_id, position, type, label, is_required, data) - values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data) + insert into app_public.event_questions(event_id, position, type, label, is_required, data, prefill) + values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data, nullif(v_input.prefill, 'NONE')) returning * into v_question; v_ret := array_append(v_ret, v_question); @@ -1779,7 +2684,9 @@ CREATE TABLE app_public.quotas ( updated_by uuid, created_at timestamp with time zone DEFAULT now() NOT NULL, updated_at timestamp with time zone DEFAULT now() NOT NULL, + price_cents integer DEFAULT 0 NOT NULL, CONSTRAINT quotas_position_check CHECK (("position" >= 0)), + CONSTRAINT quotas_price_cents_check CHECK (((price_cents = 0) OR ((price_cents >= 25) AND (price_cents <= 1000000)))), CONSTRAINT quotas_size_check CHECK ((size > 0)) ); @@ -1819,6 +2726,13 @@ COMMENT ON COLUMN app_public.quotas.title IS 'Title for the quota.'; COMMENT ON COLUMN app_public.quotas.size IS 'Size of the quota.'; +-- +-- Name: COLUMN quotas.price_cents; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.quotas.price_cents IS 'Ticket price in cents. 0 means the quota is free; a paid price is at least 25 cents so that the total charge with the service fee reaches Stripe''s minimum, and at most 1 000 000 cents (10 000 €). Registrants pay the price in effect when they pay.'; + + -- -- Name: create_event_quotas(uuid, app_public.create_event_quotas[]); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -1840,10 +2754,17 @@ begin raise exception 'You must specify at least one quota' using errcode = 'DNIED'; end if; + -- A price can be set only while payments are on + if not app_public.feature_enabled('payments') + and exists(select 1 from unnest(quotas) as q where coalesce(q.price_cents, 0) <> 0) + then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + -- Create quotas foreach v_input in array quotas loop - insert into app_public.quotas(event_id, position, title, size) - values (event_id, v_input.position, v_input.title, v_input.size) + insert into app_public.quotas(event_id, position, title, size, price_cents) + values (event_id, v_input.position, v_input.title, v_input.size, coalesce(v_input.price_cents, 0)) returning * into v_quota; v_ret := array_append(v_ret, v_quota); @@ -1935,90 +2856,6 @@ end; $$; --- --- Name: registrations; Type: TABLE; Schema: app_public; Owner: - --- - -CREATE TABLE app_public.registrations ( - id uuid DEFAULT gen_random_uuid() NOT NULL, - event_id uuid NOT NULL, - quota_id uuid NOT NULL, - first_name app_public.constrained_name, - last_name app_public.constrained_name, - email app_public.email, - answers jsonb, - is_finished boolean DEFAULT false NOT NULL, - created_by uuid, - updated_by uuid, - created_at timestamp with time zone DEFAULT now() NOT NULL, - updated_at timestamp with time zone DEFAULT now() NOT NULL -); - - --- --- Name: TABLE registrations; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON TABLE app_public.registrations IS 'Main table for registrations.'; - - --- --- Name: COLUMN registrations.id; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.id IS 'Unique identifier for the registration.'; - - --- --- Name: COLUMN registrations.event_id; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.event_id IS 'Identifier of a related event.'; - - --- --- Name: COLUMN registrations.quota_id; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.quota_id IS 'Identifier of a related quota.'; - - --- --- Name: COLUMN registrations.first_name; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.first_name IS 'First name of the person registered to an event.'; - - --- --- Name: COLUMN registrations.last_name; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.last_name IS 'Last name of the person registered to an event.'; - - --- --- Name: COLUMN registrations.email; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.email IS '@omit -Email address of the person registered to an event.'; - - --- --- Name: COLUMN registrations.answers; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.answers IS 'Answers to event questions.'; - - --- --- Name: COLUMN registrations.is_finished; Type: COMMENT; Schema: app_public; Owner: - --- - -COMMENT ON COLUMN app_public.registrations.is_finished IS 'True if the registration is completed succesfully.'; - - -- -- Name: create_registration(text, uuid, uuid, text, text, public.citext, jsonb); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2121,6 +2958,38 @@ $$; COMMENT ON FUNCTION app_public.create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb) IS 'Register to an event. Checks that a valid registration token was suplied.'; +-- +-- Name: reminder_preferences; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.reminder_preferences ( + user_id uuid NOT NULL, + minutes_before integer NOT NULL, + delivery_method text NOT NULL, + CONSTRAINT reminder_preferences_delivery_method_check CHECK ((delivery_method = ANY (ARRAY['email'::text, 'telegram'::text, 'both'::text]))), + CONSTRAINT reminder_preferences_minutes_before_check CHECK (((minutes_before >= 1) AND (minutes_before <= 10080))) +); + + +-- +-- Name: TABLE reminder_preferences; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.reminder_preferences IS '@omit create,update,delete +Delivery and timing preferences for upcoming registration reminders.'; + + +-- +-- Name: current_reminder_preferences(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.current_reminder_preferences() RETURNS app_public.reminder_preferences + LANGUAGE sql STABLE + AS $$ + select * from app_public.reminder_preferences where user_id = app_public.current_user_id(); +$$; + + -- -- Name: current_session_id(); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2139,6 +3008,45 @@ $$; COMMENT ON FUNCTION app_public.current_session_id() IS 'Handy method to get the current session ID.'; +-- +-- Name: telegram_accounts; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.telegram_accounts ( + user_id uuid NOT NULL, + chat_id bigint NOT NULL, + username text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT telegram_accounts_chat_id_check CHECK ((chat_id > 0)) +); + + +-- +-- Name: TABLE telegram_accounts; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.telegram_accounts IS '@omit create,update,delete +Telegram accounts linked by their owners.'; + + +-- +-- Name: COLUMN telegram_accounts.chat_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.telegram_accounts.chat_id IS '@omit'; + + +-- +-- Name: current_telegram_account(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.current_telegram_account() RETURNS app_public.telegram_accounts + LANGUAGE sql STABLE + AS $$ + select * from app_public.telegram_accounts where user_id = app_public.current_user_id(); +$$; + + -- -- Name: current_user(); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2242,6 +3150,31 @@ $$; COMMENT ON FUNCTION app_public.current_user_is_admin() IS 'Returns true if the current user is admin, false otherwise.'; +-- +-- Name: current_user_is_developer(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.current_user_is_developer() RETURNS boolean + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select exists ( + select 1 + from app_public.users + where + id = app_public.current_user_id() + and is_admin = true + and is_developer = true) +$$; + + +-- +-- Name: FUNCTION current_user_is_developer(); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.current_user_is_developer() IS 'Returns true if the current user is both an admin and a developer, false otherwise.'; + + -- -- Name: current_user_is_owner_organization_member(uuid); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2329,16 +3262,165 @@ begin -- Delete registration and associated secrets (foreign key has on delete) delete from app_public.registrations where id = v_registration_id; - return true; -end; + return true; +end; +$$; + + +-- +-- Name: FUNCTION delete_registration("updateToken" text); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.delete_registration("updateToken" text) IS 'Delete event registration.'; + + +-- +-- Name: delete_registration_profile(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.delete_registration_profile() RETURNS boolean + LANGUAGE plpgsql + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +declare + v_user_id uuid := app_public.current_user_id(); +begin + if v_user_id is null then + raise exception 'You must log in to delete your registration profile' using errcode = 'LOGIN'; + end if; + + delete from app_public.registration_profiles where user_id = v_user_id; + return found; +end; +$$; + + +-- +-- Name: FUNCTION delete_registration_profile(); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.delete_registration_profile() IS 'Delete the values saved to prefill your event registrations.'; + + +-- +-- Name: disconnect_telegram(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.disconnect_telegram() RETURNS boolean + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; +$$; + + +-- +-- Name: enable_event_reminder(uuid, text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.enable_event_reminder(event_id uuid, language text DEFAULT 'fi'::text) RETURNS boolean + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; + if not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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; +$$; + + +-- +-- Name: enabled_features(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.enabled_features() RETURNS SETOF text + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select f.key + from app_public.feature_flags as f + where app_public.feature_enabled(f.key) + order by f.key; +$$; + + +-- +-- Name: FUNCTION enabled_features(); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.enabled_features() IS '@simpleCollections only +Keys of the features enabled for the current user.'; + + +-- +-- Name: events_payment_summary(app_public.events); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.events_payment_summary(e app_public.events) RETURNS app_public.event_payment_summary + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + with in_spot as ( + select + r.id, + app_public.registrations_payment_status(r) as payment_status + from app_public.registrations as r + join app_hidden.registrations_status_and_position as s on s.id = r.id + where + r.event_id = e.id + and r.is_finished is true + and s.status in ('IN_QUOTA', 'IN_OPEN_QUOTA') + ), + paid as ( + select p.method, p.ticket_amount_cents, p.registration_id + from app_public.payments as p + where p.event_id = e.id and p.status = 'PAID' + ) + select + case when not app_private.current_user_can_manage_event_payments(e.id) then null else + row( + (select count(*) from in_spot where payment_status in ('PAID', 'PAID_MANUALLY'))::integer, + (select count(*) from in_spot where payment_status = 'UNPAID')::integer, + (select count(*) from in_spot where payment_status in ('PAID', 'PAID_MANUALLY', 'UNPAID'))::integer, + (select coalesce(sum(ticket_amount_cents), 0) from paid)::integer, + -- Same formula as guildReceivesCents in @app/lib: Stripe keeps the + -- service fee and 1,5 % of the total, rounded to the cent (halves up). + -- Manual payments reach the guild in full. + (select coalesce(sum( + case + when method = 'MANUAL' or ticket_amount_cents = 0 then ticket_amount_cents + -- In numeric, so large amounts can't overflow integer maths + else floor((1000 * ticket_amount_cents::numeric - 15 * (ticket_amount_cents::numeric + 25)) / 1000 + 0.5) + end + ), 0) from paid)::integer, + (select count(*) from paid where method = 'STRIPE' and registration_id is null)::integer + )::app_public.event_payment_summary + end; $$; -- --- Name: FUNCTION delete_registration("updateToken" text); Type: COMMENT; Schema: app_public; Owner: - +-- Name: FUNCTION events_payment_summary(e app_public.events); Type: COMMENT; Schema: app_public; Owner: - -- -COMMENT ON FUNCTION app_public.delete_registration("updateToken" text) IS 'Delete event registration.'; +COMMENT ON FUNCTION app_public.events_payment_summary(e app_public.events) IS 'Payment totals for organizers: counts of registrations holding a spot (in quota or open quota) that are paid, unpaid and due, the ticket amount paid, the estimated amount the guild receives and the number of card payments not linked to a registration (deleted registrations, second payments), which organizers may refund by hand in Stripe. Null unless the current user may manage the event''s payments.'; -- @@ -2395,6 +3477,72 @@ $$; COMMENT ON FUNCTION app_public.events_signup_upcoming(e app_public.events) IS 'Designates whether event signup is upcoming or not.'; +-- +-- Name: feature_enabled(text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.feature_enabled(key text) RETURNS boolean + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select exists ( + select 1 + from app_public.feature_flags as f + where + f.key = feature_enabled.key + and ( + f.retired_at is not null + or ( + f.available + and ( + f.state = 'on' + or (f.state = 'admins_only' and app_public.current_user_is_admin()) + ) + ) + )) +$$; + + +-- +-- Name: FUNCTION feature_enabled(key text); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.feature_enabled(key text) IS '@omit +True when the feature is enabled for the current user. Unknown keys read as off.'; + + +-- +-- Name: feature_flag_events(text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.feature_flag_events(flag_key text DEFAULT NULL::text) RETURNS TABLE(id uuid, key text, old_state app_public.feature_state, new_state app_public.feature_state, actor_id uuid, actor_username text, actor_name text, created_at timestamp with time zone) + LANGUAGE plpgsql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +begin + -- Cannot use call app_public.check_is_developer(); in a non volatile function + if not app_public.current_user_is_developer() then + raise exception 'Access denied. Only developers are allowed to use this query.' using errcode = 'DNIED'; + end if; + + return query + select e.id, e.key, e.old_state, e.new_state, e.actor, u.username::text, u.name, e.created_at + from app_private.feature_flag_events as e + left join app_public.users as u on u.id = e.actor + where flag_key is null or e.key = flag_key + order by e.created_at desc, e.id; +end; +$$; + + +-- +-- Name: FUNCTION feature_flag_events(flag_key text); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.feature_flag_events(flag_key text) IS '@simpleCollections only +Feature flag state changes, newest first, optionally for one key. Only accessible to developers.'; + + -- -- Name: forgot_password(public.citext); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2784,6 +3932,32 @@ $$; COMMENT ON FUNCTION app_public.registrations_full_name(registration app_public.registrations) IS 'Returns the full name of a registered person.'; +-- +-- Name: registrations_payment_status(app_public.registrations); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.registrations_payment_status(registration app_public.registrations) RETURNS app_public.registration_payment_status + LANGUAGE sql STABLE SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ + select + case + when not app_private.current_user_can_manage_event_payments(registration.event_id) + then null + else app_private.registration_payment_status(registration) + end; +$$; + + +-- +-- Name: FUNCTION registrations_payment_status(registration app_public.registrations); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.registrations_payment_status(registration app_public.registrations) IS '@sortable +@filterable +Payment status of the registration. Null unless the current user may manage the event''s payments, because registrations are publicly readable.'; + + -- -- Name: registrations_position(app_public.registrations); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2921,6 +4095,32 @@ $$; COMMENT ON FUNCTION app_public.request_account_deletion() IS 'Begin the account deletion flow by requesting the confirmation email'; +-- +-- Name: request_telegram_link(); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.request_telegram_link() RETURNS text + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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; + if not app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; +$$; + + -- -- Name: resend_email_verification_code(uuid); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2952,6 +4152,64 @@ $$; COMMENT ON FUNCTION app_public.resend_email_verification_code(email_id uuid) IS 'If you didn''t receive the verification code for this email, we can resend it. We silently cap the rate of resends on the backend, so calls to this function may not result in another email being sent if it has been called recently.'; +-- +-- Name: save_reminder_preferences(integer, text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.save_reminder_preferences(minutes_before integer, delivery_method text) RETURNS app_public.reminder_preferences + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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 not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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 app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; +$$; + + -- -- Name: set_admin_status(uuid, boolean); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -2988,6 +4246,292 @@ $$; COMMENT ON FUNCTION app_public.set_admin_status(id uuid, is_admin boolean) IS 'Make an existing user admin. Only accessible to admin users.'; +-- +-- Name: set_event_registration_reminder(uuid, boolean, text, integer, text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.set_event_registration_reminder(event_id uuid, enabled boolean, language text DEFAULT 'fi'::text, minutes_before integer DEFAULT 30, delivery_method text DEFAULT 'email'::text) RETURNS boolean + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + 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 not app_public.feature_enabled('registration_reminders') then + raise exception 'Registration reminders are not available.' using errcode = 'FTOFF'; + 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 app_public.feature_enabled('telegram_reminders') then + raise exception 'Telegram reminders are not available.' using errcode = 'FTOFF'; + 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; +$$; + + +-- +-- Name: feature_flags; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.feature_flags ( + key text NOT NULL, + state app_public.feature_state DEFAULT 'off'::app_public.feature_state NOT NULL, + available boolean DEFAULT true NOT NULL, + description text NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + updated_by uuid, + retired_at timestamp with time zone, + CONSTRAINT feature_flags_key_check CHECK ((key ~ '^[a-z][a-z0-9_]*$'::text)) +); + + +-- +-- Name: TABLE feature_flags; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.feature_flags IS 'A feature that can be switched on or off at runtime. Rows are created by migrations.'; + + +-- +-- Name: COLUMN feature_flags.key; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.key IS 'Identifier of the feature, as used in code.'; + + +-- +-- Name: COLUMN feature_flags.state; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.state IS 'Who the feature is enabled for.'; + + +-- +-- Name: COLUMN feature_flags.available; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.available IS 'False when the server lacks the configuration the feature needs; the feature then reads as off whatever its state.'; + + +-- +-- Name: COLUMN feature_flags.description; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.description IS 'What the flag gates.'; + + +-- +-- Name: COLUMN feature_flags.updated_at; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.updated_at IS 'When the state was last changed.'; + + +-- +-- Name: COLUMN feature_flags.updated_by; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.updated_by IS 'Who last changed the state.'; + + +-- +-- Name: COLUMN feature_flags.retired_at; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.feature_flags.retired_at IS 'Set when the gates have been removed from code. A retired flag reads as on.'; + + +-- +-- Name: set_feature_flag(text, app_public.feature_state); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.set_feature_flag(key text, state app_public.feature_state) RETURNS app_public.feature_flags + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +#variable_conflict use_variable +declare + v_flag app_public.feature_flags; + v_old_state app_public.feature_state; +begin + call app_public.check_is_developer(); + + select * into v_flag + from app_public.feature_flags as f + where f.key = key + for update; + + if v_flag.key is null then + raise exception 'Unknown feature flag "%".', key using errcode = 'NTFND'; + end if; + + if v_flag.retired_at is not null then + raise exception 'Feature flag "%" is retired and cannot be changed.', key using errcode = 'DNIED'; + end if; + + if state <> 'off' and not v_flag.available then + raise exception 'Feature flag "%" is not available: the server lacks the configuration it needs.', key using errcode = 'FTUNA'; + end if; + + if v_flag.state = state then + return v_flag; + end if; + + v_old_state = v_flag.state; + + update app_public.feature_flags as f + set + state = state, + updated_at = now(), + updated_by = app_public.current_user_id() + where f.key = key + returning * into v_flag; + + insert into app_private.feature_flag_events (key, old_state, new_state, actor) + values (key, v_old_state, state, app_public.current_user_id()); + + return v_flag; +end; +$$; + + +-- +-- Name: FUNCTION set_feature_flag(key text, state app_public.feature_state); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.set_feature_flag(key text, state app_public.feature_state) IS 'Changes the state of an existing feature flag. Only accessible to developers.'; + + +-- +-- Name: registration_profiles; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.registration_profiles ( + user_id uuid NOT NULL, + telegram text, + dietary_restrictions text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT registration_profiles_dietary_restrictions_check CHECK ((length(dietary_restrictions) <= 1000)), + CONSTRAINT registration_profiles_telegram_check CHECK ((length(telegram) <= 64)) +); + + +-- +-- Name: TABLE registration_profiles; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.registration_profiles IS 'Values used to prefill event registration answers. Only visible to the user themselves.'; + + +-- +-- Name: COLUMN registration_profiles.user_id; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registration_profiles.user_id IS 'The user this registration profile belongs to.'; + + +-- +-- Name: COLUMN registration_profiles.telegram; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registration_profiles.telegram IS 'Telegram handle.'; + + +-- +-- Name: COLUMN registration_profiles.dietary_restrictions; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON COLUMN app_public.registration_profiles.dietary_restrictions IS 'Dietary restrictions and allergies.'; + + +-- +-- Name: set_registration_profile(text, text); Type: FUNCTION; Schema: app_public; Owner: - +-- + +CREATE FUNCTION app_public.set_registration_profile(telegram text DEFAULT NULL::text, dietary_restrictions text DEFAULT NULL::text) RETURNS app_public.registration_profiles + LANGUAGE plpgsql + SET search_path TO 'pg_catalog', 'public', 'pg_temp' + AS $$ +#variable_conflict use_variable +declare + v_user_id uuid := app_public.current_user_id(); + v_profile app_public.registration_profiles; +begin + if v_user_id is null then + raise exception 'You must log in to update your registration profile' using errcode = 'LOGIN'; + end if; + + if not app_public.feature_enabled('prefill_answers') then + raise exception 'Saving registration answers is not enabled' using errcode = 'FTOFF'; + end if; + + insert into app_public.registration_profiles(user_id, telegram, dietary_restrictions) + values (v_user_id, nullif(trim(telegram), ''), nullif(trim(dietary_restrictions), '')) + on conflict (user_id) do update + set + telegram = case + when telegram is null then registration_profiles.telegram + else excluded.telegram + end, + dietary_restrictions = case + when dietary_restrictions is null then registration_profiles.dietary_restrictions + else excluded.dietary_restrictions + end + returning * into v_profile; + + return v_profile; +end; +$$; + + +-- +-- Name: FUNCTION set_registration_profile(telegram text, dietary_restrictions text); Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON FUNCTION app_public.set_registration_profile(telegram text, dietary_restrictions text) IS 'Set the values used to prefill your event registrations. A null value keeps the saved one and an empty value clears it.'; + + -- -- Name: supported_languages(); Type: FUNCTION; Schema: app_public; Owner: - -- @@ -3232,6 +4776,10 @@ begin registration_start_time = coalesce(event.registration_start_time, registration_start_time), registration_end_time = coalesce(event.registration_end_time, registration_end_time), is_highlighted = coalesce(event.is_highlighted, is_highlighted), + highlight_text = case + when event.is_highlighted is null then highlight_text + else event.highlight_text + end, is_draft = coalesce(event.is_draft, is_draft), header_image_file = coalesce(event.header_image_file, header_image_file), open_quota_size = coalesce(event.open_quota_size, open_quota_size), @@ -3253,7 +4801,7 @@ $$; -- Name: FUNCTION update_event(id uuid, event app_public.event_input, quotas app_public.update_event_quotas[], questions app_public.update_event_questions[]); Type: COMMENT; Schema: app_public; Owner: - -- -COMMENT ON FUNCTION app_public.update_event(id uuid, event app_public.event_input, quotas app_public.update_event_quotas[], questions app_public.update_event_questions[]) IS 'Updates an event as well as any related quotas and questions with one mutation.'; +COMMENT ON FUNCTION app_public.update_event(id uuid, event app_public.event_input, quotas app_public.update_event_quotas[], questions app_public.update_event_questions[]) IS 'Updates an event as well as any related quotas and questions with one mutation. An omitted event attribute keeps its value, except `highlightText`, which is replaced (null clears it) whenever `isHighlighted` is given.'; -- @@ -3277,7 +4825,7 @@ begin select array( select id from app_public.event_questions as q where q.event_id = event_id - and q.id not in (select id from unnest(questions)) + and q.id not in (select id from unnest(questions) where id is not null) ) into v_question_ids_to_delete; @@ -3290,13 +4838,17 @@ begin if exists(select 1 from app_public.event_questions where id = v_input.id) then -- Update existing event questions by id update app_public.event_questions - set position = v_input.position, type = v_input.type, label = v_input.label, is_required = v_input.is_required, data = v_input.data + set position = v_input.position, type = v_input.type, label = v_input.label, is_required = v_input.is_required, data = v_input.data, + prefill = case + when v_input.type <> 'TEXT' or v_input.prefill = 'NONE' then null + else coalesce(v_input.prefill, prefill) + end where id = v_input.id returning * into v_question; else -- Create new questions that didn't exist before - insert into app_public.event_questions(event_id, position, type, label, is_required, data) - values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data) + insert into app_public.event_questions(event_id, position, type, label, is_required, data, prefill) + values (event_id, v_input.position, v_input.type, v_input.label, v_input.is_required, v_input.data, nullif(v_input.prefill, 'NONE')) returning * into v_question; end if; @@ -3339,10 +4891,17 @@ begin raise exception 'You must specify at least one quota' using errcode = 'DNIED'; end if; + -- A price can be set only while payments are on + if not app_public.feature_enabled('payments') + and exists(select 1 from unnest(quotas) as q where coalesce(q.price_cents, 0) <> 0) + then + raise exception 'Payments are not available.' using errcode = 'FTOFF'; + end if; + select array( select id from app_public.quotas as q where q.event_id = event_id - and q.id not in (select id from unnest(quotas)) + and q.id not in (select id from unnest(quotas) where id is not null) ) into v_quota_ids_to_delete; @@ -3354,14 +4913,18 @@ begin foreach v_input in array quotas loop if exists(select 1 from app_public.quotas where id = v_input.id) then -- Update existing event quotas by id - update app_public.quotas - set position = v_input.position, title = v_input.title, size = v_input.size - where id = v_input.id + update app_public.quotas as q + set + position = v_input.position, + title = v_input.title, + size = v_input.size, + price_cents = coalesce(v_input.price_cents, q.price_cents) + where q.id = v_input.id returning * into v_quota; else -- Create new quotas that didn't exist before - insert into app_public.quotas(event_id, position, title, size) - values (event_id, v_input.position, v_input.title, v_input.size) + insert into app_public.quotas(event_id, position, title, size, price_cents) + values (event_id, v_input.position, v_input.title, v_input.size, coalesce(v_input.price_cents, 0)) returning * into v_quota; end if; @@ -3392,6 +4955,7 @@ CREATE FUNCTION app_public.update_registration("updateToken" text, "firstName" t declare v_registration_secret app_private.registration_secrets; v_registration app_public.registrations; + v_event app_public.events; v_required_question_ids uuid[]; begin select * into v_registration_secret @@ -3402,6 +4966,13 @@ begin raise exception 'Registration matching token was not found.' using errcode = 'NTFND'; end if; + select * into v_event from app_public.events where id = v_registration_secret.event_id; + + if not app_public.current_user_is_admin() + and ((v_event is null) or not (select app_public.events_signup_open(v_event))) then + raise exception 'Updating a registration after event signup has closed is not allowed. Please contact the event organizers.' using errcode = 'DNIED'; + end if; + -- If the registration doesn't provide answers to all of the required questions it is invalid. -- This is double validated in the _200_registration_is_valid trigger. v_required_question_ids := array(select id from app_public.event_questions where event_id = v_registration_secret.event_id and is_required = True); @@ -3613,77 +5184,44 @@ COMMENT ON FUNCTION app_public.verify_email(user_email_id uuid, token text) IS ' -- --- Name: registrations_status_and_position; Type: MATERIALIZED VIEW; Schema: app_hidden; Owner: - --- - -CREATE MATERIALIZED VIEW app_hidden.registrations_status_and_position AS - WITH cte1 AS ( - SELECT r.id, - q.size, - e.id AS event_id, - q.id AS quota_id, - e.open_quota_size, - r.created_at, - row_number() OVER (PARTITION BY r.quota_id ORDER BY r.created_at) AS tmp_pos_quota - FROM ((app_public.registrations r - LEFT JOIN app_public.quotas q ON ((r.quota_id = q.id))) - LEFT JOIN app_public.events e ON ((r.event_id = e.id))) - ), cte2 AS ( - SELECT tmp.id, - tmp.size, - tmp.event_id, - tmp.quota_id, - tmp.open_quota_size, - tmp.created_at, - tmp.tmp_pos_quota, - tmp.tmp_status, - row_number() OVER (PARTITION BY tmp.event_id, tmp.tmp_status ORDER BY tmp.created_at) AS tmp_pos_status - FROM ( SELECT cte1.id, - cte1.size, - cte1.event_id, - cte1.quota_id, - cte1.open_quota_size, - cte1.created_at, - cte1.tmp_pos_quota, - CASE - WHEN (cte1.tmp_pos_quota <= cte1.size) THEN 'IN_QUOTA'::text - ELSE 'OPEN_OR_QUEUE'::text - END AS tmp_status - FROM cte1) tmp - ), cte3 AS ( - SELECT cte2.id, - cte2.size, - cte2.event_id, - cte2.quota_id, - cte2.open_quota_size, - cte2.created_at, - cte2.tmp_pos_quota, - cte2.tmp_status, - cte2.tmp_pos_status, - CASE - WHEN ((cte2.tmp_status = 'OPEN_OR_QUEUE'::text) AND (cte2.tmp_pos_status <= cte2.open_quota_size)) THEN 'IN_OPEN_QUOTA'::app_public.registration_status - WHEN (cte2.tmp_status = 'OPEN_OR_QUEUE'::text) THEN 'IN_QUEUE'::app_public.registration_status - ELSE 'IN_QUOTA'::app_public.registration_status - END AS status - FROM cte2 - ) - SELECT cte3.id, - cte3.event_id, - cte3.quota_id, - cte3.status, - CASE - WHEN (cte3.status = 'IN_QUOTA'::app_public.registration_status) THEN (row_number() OVER (PARTITION BY cte3.quota_id, cte3.status ORDER BY cte3.created_at))::integer - ELSE (row_number() OVER (PARTITION BY cte3.event_id, cte3.status ORDER BY cte3.created_at))::integer - END AS "position" - FROM cte3 - WITH NO DATA; +-- Name: registrations_status_and_position; Type: TABLE; Schema: app_hidden; Owner: - +-- + +CREATE TABLE app_hidden.registrations_status_and_position ( + id uuid NOT NULL, + event_id uuid, + quota_id uuid, + status app_public.registration_status, + "position" integer +); + + +-- +-- Name: TABLE registrations_status_and_position; Type: COMMENT; Schema: app_hidden; Owner: - +-- + +COMMENT ON TABLE app_hidden.registrations_status_and_position IS 'Rank and position of registrations, maintained per event by app_private.refresh_registration_positions.'; + + +-- +-- Name: feature_flag_events; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.feature_flag_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + key text NOT NULL, + old_state app_public.feature_state NOT NULL, + new_state app_public.feature_state NOT NULL, + actor uuid, + created_at timestamp with time zone DEFAULT now() NOT NULL +); -- --- Name: MATERIALIZED VIEW registrations_status_and_position; Type: COMMENT; Schema: app_hidden; Owner: - +-- Name: TABLE feature_flag_events; Type: COMMENT; Schema: app_private; Owner: - -- -COMMENT ON MATERIALIZED VIEW app_hidden.registrations_status_and_position IS 'Rank and position of registrations.'; +COMMENT ON TABLE app_private.feature_flag_events IS 'One row per feature flag state change.'; -- @@ -3711,6 +5249,70 @@ CREATE TABLE app_private.registration_secrets ( COMMENT ON TABLE app_private.registration_secrets IS 'The contents of this table should never be visible to the user. Contains private data related to event registrations.'; +-- +-- Name: stripe_events; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.stripe_events ( + id text NOT NULL, + type text NOT NULL, + processed_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: TABLE stripe_events; Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON TABLE app_private.stripe_events IS 'Ids of Stripe webhook events already handled, so that redelivered events are ignored.'; + + +-- +-- Name: telegram_link_tokens; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.telegram_link_tokens ( + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + expires_at timestamp with time zone NOT NULL +); + + +-- +-- Name: telegram_poll_state; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.telegram_poll_state ( + id boolean DEFAULT true NOT NULL, + next_offset bigint DEFAULT 0 NOT NULL, + CONSTRAINT telegram_poll_state_id_check CHECK (id) +); + + +-- +-- Name: telegram_preferences; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.telegram_preferences ( + chat_id bigint NOT NULL, + language text DEFAULT 'auto'::text NOT NULL, + detected_language text DEFAULT 'en'::text NOT NULL, + CONSTRAINT telegram_preferences_chat_id_check CHECK ((chat_id > 0)), + CONSTRAINT telegram_preferences_detected_language_check CHECK ((detected_language = ANY (ARRAY['fi'::text, 'en'::text]))), + CONSTRAINT telegram_preferences_language_check CHECK ((language = ANY (ARRAY['auto'::text, 'fi'::text, 'en'::text]))) +); + + +-- +-- Name: telegram_updates; Type: TABLE; Schema: app_private; Owner: - +-- + +CREATE TABLE app_private.telegram_updates ( + update_id bigint NOT NULL, + processed_at timestamp with time zone DEFAULT now() NOT NULL +); + + -- -- Name: unregistered_email_password_resets; Type: TABLE; Schema: app_private; Owner: - -- @@ -3864,6 +5466,35 @@ COMMENT ON COLUMN app_public.event_categories.owner_organization_id IS 'Identifi COMMENT ON COLUMN app_public.event_categories.color IS 'Color color the event category.'; +-- +-- Name: event_registration_reminders; Type: TABLE; Schema: app_public; Owner: - +-- + +CREATE TABLE app_public.event_registration_reminders ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + event_id uuid NOT NULL, + language text DEFAULT 'fi'::text NOT NULL, + minutes_before integer DEFAULT 30 NOT NULL, + delivery_method text DEFAULT 'email'::text NOT NULL, + email_sent_at timestamp with time zone, + telegram_sent_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL, + sent_at timestamp with time zone, + CONSTRAINT event_registration_reminders_delivery_method_check CHECK ((delivery_method = ANY (ARRAY['email'::text, 'telegram'::text, 'both'::text]))), + CONSTRAINT event_registration_reminders_language_check CHECK ((language = ANY (ARRAY['fi'::text, 'en'::text]))), + CONSTRAINT event_registration_reminders_minutes_before_check CHECK (((minutes_before >= 1) AND (minutes_before <= 10080))) +); + + +-- +-- Name: TABLE event_registration_reminders; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON TABLE app_public.event_registration_reminders IS '@omit create,update +Registration reminders requested by the current user, before registration opens.'; + + -- -- Name: organization_invitations; Type: TABLE; Schema: app_public; Owner: - -- @@ -3935,6 +5566,22 @@ COMMENT ON COLUMN app_public.user_authentications.identifier IS 'A unique identi COMMENT ON COLUMN app_public.user_authentications.details IS 'Additional profile details extracted from this login method'; +-- +-- Name: registrations_status_and_position registrations_status_and_position_pkey; Type: CONSTRAINT; Schema: app_hidden; Owner: - +-- + +ALTER TABLE ONLY app_hidden.registrations_status_and_position + ADD CONSTRAINT registrations_status_and_position_pkey PRIMARY KEY (id); + + +-- +-- Name: feature_flag_events feature_flag_events_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.feature_flag_events + ADD CONSTRAINT feature_flag_events_pkey PRIMARY KEY (id); + + -- -- Name: registration_secrets registration_secrets_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - -- @@ -3967,6 +5614,54 @@ ALTER TABLE ONLY app_private.sessions ADD CONSTRAINT sessions_pkey PRIMARY KEY (uuid); +-- +-- Name: stripe_events stripe_events_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.stripe_events + ADD CONSTRAINT stripe_events_pkey PRIMARY KEY (id); + + +-- +-- Name: telegram_link_tokens telegram_link_tokens_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_link_tokens + ADD CONSTRAINT telegram_link_tokens_pkey PRIMARY KEY (user_id); + + +-- +-- Name: telegram_link_tokens telegram_link_tokens_token_hash_key; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_link_tokens + ADD CONSTRAINT telegram_link_tokens_token_hash_key UNIQUE (token_hash); + + +-- +-- Name: telegram_poll_state telegram_poll_state_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_poll_state + ADD CONSTRAINT telegram_poll_state_pkey PRIMARY KEY (id); + + +-- +-- Name: telegram_preferences telegram_preferences_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_preferences + ADD CONSTRAINT telegram_preferences_pkey PRIMARY KEY (chat_id); + + +-- +-- Name: telegram_updates telegram_updates_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_updates + ADD CONSTRAINT telegram_updates_pkey PRIMARY KEY (update_id); + + -- -- Name: unregistered_email_password_resets unregistered_email_pkey; Type: CONSTRAINT; Schema: app_private; Owner: - -- @@ -4023,6 +5718,22 @@ ALTER TABLE ONLY app_public.event_questions ADD CONSTRAINT event_questions_pkey PRIMARY KEY (id); +-- +-- Name: event_registration_reminders event_registration_reminders_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.event_registration_reminders + ADD CONSTRAINT event_registration_reminders_pkey PRIMARY KEY (id); + + +-- +-- Name: event_registration_reminders event_registration_reminders_user_id_event_id_key; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.event_registration_reminders + ADD CONSTRAINT event_registration_reminders_user_id_event_id_key UNIQUE (user_id, event_id); + + -- -- Name: events events_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - -- @@ -4039,6 +5750,14 @@ ALTER TABLE ONLY app_public.events ADD CONSTRAINT events_slug_key UNIQUE (slug); +-- +-- Name: feature_flags feature_flags_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.feature_flags + ADD CONSTRAINT feature_flags_pkey PRIMARY KEY (key); + + -- -- Name: organization_invitations organization_invitations_organization_id_email_key; Type: CONSTRAINT; Schema: app_public; Owner: - -- @@ -4095,6 +5814,22 @@ ALTER TABLE ONLY app_public.organizations ADD CONSTRAINT organizations_slug_key UNIQUE (slug); +-- +-- Name: payments payments_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_pkey PRIMARY KEY (id); + + +-- +-- Name: payments payments_stripe_checkout_session_id_key; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_stripe_checkout_session_id_key UNIQUE (stripe_checkout_session_id); + + -- -- Name: quotas quotas_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - -- @@ -4103,6 +5838,14 @@ ALTER TABLE ONLY app_public.quotas ADD CONSTRAINT quotas_pkey PRIMARY KEY (id); +-- +-- Name: registration_profiles registration_profiles_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.registration_profiles + ADD CONSTRAINT registration_profiles_pkey PRIMARY KEY (user_id); + + -- -- Name: registrations registrations_email_event_id_key; Type: CONSTRAINT; Schema: app_public; Owner: - -- @@ -4119,6 +5862,30 @@ ALTER TABLE ONLY app_public.registrations ADD CONSTRAINT registrations_pkey PRIMARY KEY (id); +-- +-- Name: reminder_preferences reminder_preferences_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.reminder_preferences + ADD CONSTRAINT reminder_preferences_pkey PRIMARY KEY (user_id); + + +-- +-- Name: telegram_accounts telegram_accounts_chat_id_key; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.telegram_accounts + ADD CONSTRAINT telegram_accounts_chat_id_key UNIQUE (chat_id); + + +-- +-- Name: telegram_accounts telegram_accounts_pkey; Type: CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.telegram_accounts + ADD CONSTRAINT telegram_accounts_pkey PRIMARY KEY (user_id); + + -- -- Name: user_authentications uniq_user_authentications; Type: CONSTRAINT; Schema: app_public; Owner: - -- @@ -4167,17 +5934,24 @@ CREATE INDEX registrations_status_and_position_event_id_idx ON app_hidden.regist -- --- Name: registrations_status_and_position_id_idx; Type: INDEX; Schema: app_hidden; Owner: - +-- Name: registrations_status_and_position_quota_id_idx; Type: INDEX; Schema: app_hidden; Owner: - -- -CREATE UNIQUE INDEX registrations_status_and_position_id_idx ON app_hidden.registrations_status_and_position USING btree (id); +CREATE INDEX registrations_status_and_position_quota_id_idx ON app_hidden.registrations_status_and_position USING btree (quota_id); -- --- Name: registrations_status_and_position_quota_id_idx; Type: INDEX; Schema: app_hidden; Owner: - +-- Name: feature_flag_events_actor_idx; Type: INDEX; Schema: app_private; Owner: - -- -CREATE INDEX registrations_status_and_position_quota_id_idx ON app_hidden.registrations_status_and_position USING btree (quota_id); +CREATE INDEX feature_flag_events_actor_idx ON app_private.feature_flag_events USING btree (actor); + + +-- +-- Name: feature_flag_events_key_created_at_idx; Type: INDEX; Schema: app_private; Owner: - +-- + +CREATE INDEX feature_flag_events_key_created_at_idx ON app_private.feature_flag_events USING btree (key, created_at); -- @@ -4201,6 +5975,13 @@ CREATE INDEX registration_secrets_quota_id_idx ON app_private.registration_secre CREATE INDEX registration_secrets_registration_id_idx ON app_private.registration_secrets USING btree (registration_id); +-- +-- Name: sessions_mcp_oauth_sid_key; Type: INDEX; Schema: app_private; Owner: - +-- + +CREATE UNIQUE INDEX sessions_mcp_oauth_sid_key ON app_private.sessions USING btree (oauth_sid) WHERE (kind = 'mcp'::text); + + -- -- Name: sessions_user_id_idx; Type: INDEX; Schema: app_private; Owner: - -- @@ -4264,6 +6045,13 @@ CREATE INDEX event_questions_position_idx ON app_public.event_questions USING bt CREATE INDEX event_questions_updated_by_idx ON app_public.event_questions USING btree (updated_by); +-- +-- Name: event_registration_reminders_event_id_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX event_registration_reminders_event_id_idx ON app_public.event_registration_reminders USING btree (event_id); + + -- -- Name: events_category_id_idx; Type: INDEX; Schema: app_public; Owner: - -- @@ -4341,6 +6129,13 @@ CREATE INDEX events_registration_start_time_idx ON app_public.events USING btree CREATE INDEX events_updated_by_idx ON app_public.events USING btree (updated_by); +-- +-- Name: feature_flags_updated_by_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX feature_flags_updated_by_idx ON app_public.feature_flags USING btree (updated_by); + + -- -- Name: idx_user_emails_primary; Type: INDEX; Schema: app_public; Owner: - -- @@ -4383,6 +6178,48 @@ CREATE INDEX organizations_created_by_idx ON app_public.organizations USING btre CREATE INDEX organizations_updated_by_idx ON app_public.organizations USING btree (updated_by); +-- +-- Name: payments_created_by_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX payments_created_by_idx ON app_public.payments USING btree (created_by); + + +-- +-- Name: payments_event_id_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX payments_event_id_idx ON app_public.payments USING btree (event_id); + + +-- +-- Name: payments_one_paid_per_registration_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE UNIQUE INDEX payments_one_paid_per_registration_idx ON app_public.payments USING btree (registration_id) WHERE ((status = 'PAID'::app_public.payment_status) AND (registration_id IS NOT NULL)); + + +-- +-- Name: payments_quota_id_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX payments_quota_id_idx ON app_public.payments USING btree (quota_id); + + +-- +-- Name: payments_registration_id_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX payments_registration_id_idx ON app_public.payments USING btree (registration_id); + + +-- +-- Name: payments_stripe_payment_intent_id_idx; Type: INDEX; Schema: app_public; Owner: - +-- + +CREATE INDEX payments_stripe_payment_intent_id_idx ON app_public.payments USING btree (stripe_payment_intent_id); + + -- -- Name: quotas_created_by_idx; Type: INDEX; Schema: app_public; Owner: - -- @@ -4509,6 +6346,13 @@ CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.events FOR CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.organizations FOR EACH ROW EXECUTE FUNCTION app_private.tg__timestamps(); +-- +-- Name: payments _100_timestamps; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.payments FOR EACH ROW EXECUTE FUNCTION app_private.tg__timestamps(); + + -- -- Name: quotas _100_timestamps; Type: TRIGGER; Schema: app_public; Owner: - -- @@ -4516,6 +6360,13 @@ CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.organizatio CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.quotas FOR EACH ROW EXECUTE FUNCTION app_private.tg__timestamps(); +-- +-- Name: registration_profiles _100_timestamps; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _100_timestamps BEFORE INSERT OR UPDATE ON app_public.registration_profiles FOR EACH ROW EXECUTE FUNCTION app_private.tg__timestamps(); + + -- -- Name: registrations _100_timestamps; Type: TRIGGER; Schema: app_public; Owner: - -- @@ -4594,17 +6445,24 @@ CREATE TRIGGER _200_ownership_info BEFORE INSERT OR UPDATE ON app_public.registr -- --- Name: events _300_refresh_mat_view; Type: TRIGGER; Schema: app_public; Owner: - +-- Name: events _250_reset_unpaid_close_email; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _250_reset_unpaid_close_email BEFORE UPDATE OF registration_end_time ON app_public.events FOR EACH ROW WHEN ((new.registration_end_time > old.registration_end_time)) EXECUTE FUNCTION app_private.tg_events__reset_unpaid_close_email(); + + +-- +-- Name: events _300_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - -- -CREATE TRIGGER _300_refresh_mat_view AFTER INSERT OR DELETE OR UPDATE ON app_public.events FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_materialized_view(); +CREATE TRIGGER _300_refresh_registration_positions AFTER INSERT OR DELETE ON app_public.events FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); -- --- Name: quotas _300_refresh_mat_view; Type: TRIGGER; Schema: app_public; Owner: - +-- Name: quotas _300_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - -- -CREATE TRIGGER _300_refresh_mat_view AFTER INSERT OR DELETE OR UPDATE ON app_public.quotas FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_materialized_view(); +CREATE TRIGGER _300_refresh_registration_positions AFTER INSERT OR DELETE ON app_public.quotas FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); -- @@ -4614,6 +6472,20 @@ CREATE TRIGGER _300_refresh_mat_view AFTER INSERT OR DELETE OR UPDATE ON app_pub CREATE TRIGGER _300_registration_is_valid BEFORE INSERT ON app_public.registrations FOR EACH ROW EXECUTE FUNCTION app_private.tg__registration_is_valid(); +-- +-- Name: events _301_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _301_refresh_registration_positions AFTER UPDATE ON app_public.events FOR EACH ROW WHEN ((old.open_quota_size IS DISTINCT FROM new.open_quota_size)) EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); + + +-- +-- Name: quotas _301_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _301_refresh_registration_positions AFTER UPDATE ON app_public.quotas FOR EACH ROW WHEN (((old.size IS DISTINCT FROM new.size) OR (old.event_id IS DISTINCT FROM new.event_id))) EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); + + -- -- Name: registrations _400_gql_registration_updated; Type: TRIGGER; Schema: app_public; Owner: - -- @@ -4695,28 +6567,50 @@ CREATE TRIGGER _500_send_registration_email AFTER UPDATE ON app_public.registrat -- Name: user_emails _500_verify_account_on_verified; Type: TRIGGER; Schema: app_public; Owner: - -- -CREATE TRIGGER _500_verify_account_on_verified AFTER INSERT OR UPDATE OF is_verified ON app_public.user_emails FOR EACH ROW WHEN ((new.is_verified IS TRUE)) EXECUTE FUNCTION app_public.tg_user_emails__verify_account_on_verified(); +CREATE TRIGGER _500_verify_account_on_verified AFTER INSERT OR UPDATE OF is_verified ON app_public.user_emails FOR EACH ROW WHEN ((new.is_verified IS TRUE)) EXECUTE FUNCTION app_public.tg_user_emails__verify_account_on_verified(); + + +-- +-- Name: registrations _700_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _700_refresh_registration_positions AFTER INSERT OR DELETE ON app_public.registrations FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); + + +-- +-- Name: registrations _701_refresh_registration_positions; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _701_refresh_registration_positions AFTER UPDATE ON app_public.registrations FOR EACH ROW WHEN (((old.created_at IS DISTINCT FROM new.created_at) OR (old.quota_id IS DISTINCT FROM new.quota_id) OR (old.event_id IS DISTINCT FROM new.event_id))) EXECUTE FUNCTION app_private.tg__refresh_registration_positions(); + + +-- +-- Name: user_emails _900_send_verification_email; Type: TRIGGER; Schema: app_public; Owner: - +-- + +CREATE TRIGGER _900_send_verification_email AFTER INSERT ON app_public.user_emails FOR EACH ROW WHEN ((new.is_verified IS FALSE)) EXECUTE FUNCTION app_private.tg__add_job('user_emails__send_verification'); -- --- Name: registrations _700_refresh_mat_view; Type: TRIGGER; Schema: app_public; Owner: - +-- Name: events reschedule_registration_reminders; Type: TRIGGER; Schema: app_public; Owner: - -- -CREATE TRIGGER _700_refresh_mat_view AFTER INSERT OR DELETE OR UPDATE ON app_public.registrations FOR EACH ROW EXECUTE FUNCTION app_private.tg__refresh_materialized_view(); +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(); -- --- Name: registrations _800_process_registration_queue; Type: TRIGGER; Schema: app_public; Owner: - +-- Name: event_registration_reminders schedule_registration_reminder; Type: TRIGGER; Schema: app_public; Owner: - -- -CREATE TRIGGER _800_process_registration_queue BEFORE DELETE ON app_public.registrations FOR EACH ROW EXECUTE FUNCTION app_private.tg__process_queue(); +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(); -- --- Name: user_emails _900_send_verification_email; Type: TRIGGER; Schema: app_public; Owner: - +-- Name: feature_flag_events feature_flag_events_actor_fkey; Type: FK CONSTRAINT; Schema: app_private; Owner: - -- -CREATE TRIGGER _900_send_verification_email AFTER INSERT ON app_public.user_emails FOR EACH ROW WHEN ((new.is_verified IS FALSE)) EXECUTE FUNCTION app_private.tg__add_job('user_emails__send_verification'); +ALTER TABLE ONLY app_private.feature_flag_events + ADD CONSTRAINT feature_flag_events_actor_fkey FOREIGN KEY (actor) REFERENCES app_public.users(id) ON DELETE SET NULL; -- @@ -4751,6 +6645,14 @@ ALTER TABLE ONLY app_private.sessions ADD CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; +-- +-- Name: telegram_link_tokens telegram_link_tokens_user_id_fkey; Type: FK CONSTRAINT; Schema: app_private; Owner: - +-- + +ALTER TABLE ONLY app_private.telegram_link_tokens + ADD CONSTRAINT telegram_link_tokens_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; + + -- -- Name: user_authentication_secrets user_authentication_secrets_user_authentication_id_fkey; Type: FK CONSTRAINT; Schema: app_private; Owner: - -- @@ -4823,6 +6725,22 @@ ALTER TABLE ONLY app_public.event_questions ADD CONSTRAINT event_questions_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; +-- +-- Name: event_registration_reminders event_registration_reminders_event_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.event_registration_reminders + ADD CONSTRAINT event_registration_reminders_event_id_fkey FOREIGN KEY (event_id) REFERENCES app_public.events(id) ON DELETE CASCADE; + + +-- +-- Name: event_registration_reminders event_registration_reminders_user_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.event_registration_reminders + ADD CONSTRAINT event_registration_reminders_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; + + -- -- Name: events events_category_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - -- @@ -4855,6 +6773,21 @@ ALTER TABLE ONLY app_public.events ADD CONSTRAINT events_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; +-- +-- Name: feature_flags feature_flags_updated_by_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.feature_flags + ADD CONSTRAINT feature_flags_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; + + +-- +-- Name: CONSTRAINT feature_flags_updated_by_fkey ON feature_flags; Type: COMMENT; Schema: app_public; Owner: - +-- + +COMMENT ON CONSTRAINT feature_flags_updated_by_fkey ON app_public.feature_flags IS '@omit many'; + + -- -- Name: organization_invitations organization_invitations_organization_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - -- @@ -4903,6 +6836,38 @@ ALTER TABLE ONLY app_public.organizations ADD CONSTRAINT organizations_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; +-- +-- Name: payments payments_created_by_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_created_by_fkey FOREIGN KEY (created_by) REFERENCES app_public.users(id) ON DELETE SET NULL; + + +-- +-- Name: payments payments_event_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_event_id_fkey FOREIGN KEY (event_id) REFERENCES app_public.events(id) ON DELETE SET NULL; + + +-- +-- Name: payments payments_quota_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_quota_id_fkey FOREIGN KEY (quota_id) REFERENCES app_public.quotas(id) ON DELETE SET NULL; + + +-- +-- Name: payments payments_registration_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.payments + ADD CONSTRAINT payments_registration_id_fkey FOREIGN KEY (registration_id) REFERENCES app_public.registrations(id) ON DELETE SET NULL; + + -- -- Name: quotas quotas_created_by_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - -- @@ -4927,6 +6892,14 @@ ALTER TABLE ONLY app_public.quotas ADD CONSTRAINT quotas_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; +-- +-- Name: registration_profiles registration_profiles_user_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.registration_profiles + ADD CONSTRAINT registration_profiles_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; + + -- -- Name: registrations registrations_created_by_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - -- @@ -4959,6 +6932,22 @@ ALTER TABLE ONLY app_public.registrations ADD CONSTRAINT registrations_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES app_public.users(id) ON DELETE SET NULL; +-- +-- Name: reminder_preferences reminder_preferences_user_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.reminder_preferences + ADD CONSTRAINT reminder_preferences_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; + + +-- +-- Name: telegram_accounts telegram_accounts_user_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - +-- + +ALTER TABLE ONLY app_public.telegram_accounts + ADD CONSTRAINT telegram_accounts_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; + + -- -- Name: user_authentications user_authentications_user_id_fkey; Type: FK CONSTRAINT; Schema: app_public; Owner: - -- @@ -4975,6 +6964,25 @@ ALTER TABLE ONLY app_public.user_emails ADD CONSTRAINT user_emails_user_id_fkey FOREIGN KEY (user_id) REFERENCES app_public.users(id) ON DELETE CASCADE; +-- +-- Name: registrations_status_and_position; Type: ROW SECURITY; Schema: app_hidden; Owner: - +-- + +ALTER TABLE app_hidden.registrations_status_and_position ENABLE ROW LEVEL SECURITY; + +-- +-- Name: registrations_status_and_position select_all; Type: POLICY; Schema: app_hidden; Owner: - +-- + +CREATE POLICY select_all ON app_hidden.registrations_status_and_position FOR SELECT USING (true); + + +-- +-- Name: feature_flag_events; Type: ROW SECURITY; Schema: app_private; Owner: - +-- + +ALTER TABLE app_private.feature_flag_events ENABLE ROW LEVEL SECURITY; + -- -- Name: registration_secrets; Type: ROW SECURITY; Schema: app_private; Owner: - -- @@ -4987,6 +6995,12 @@ ALTER TABLE app_private.registration_secrets ENABLE ROW LEVEL SECURITY; ALTER TABLE app_private.sessions ENABLE ROW LEVEL SECURITY; +-- +-- Name: stripe_events; Type: ROW SECURITY; Schema: app_private; Owner: - +-- + +ALTER TABLE app_private.stripe_events ENABLE ROW LEVEL SECURITY; + -- -- Name: user_authentication_secrets; Type: ROW SECURITY; Schema: app_private; Owner: - -- @@ -5005,6 +7019,13 @@ ALTER TABLE app_private.user_email_secrets ENABLE ROW LEVEL SECURITY; ALTER TABLE app_private.user_secrets ENABLE ROW LEVEL SECURITY; +-- +-- Name: registration_profiles delete_own; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY delete_own ON app_public.registration_profiles FOR DELETE USING ((user_id = app_public.current_user_id())); + + -- -- Name: user_authentications delete_own; Type: POLICY; Schema: app_public; Owner: - -- @@ -5031,12 +7052,31 @@ ALTER TABLE app_public.event_categories ENABLE ROW LEVEL SECURITY; ALTER TABLE app_public.event_questions ENABLE ROW LEVEL SECURITY; +-- +-- Name: event_registration_reminders; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.event_registration_reminders ENABLE ROW LEVEL SECURITY; + -- -- Name: events; Type: ROW SECURITY; Schema: app_public; Owner: - -- ALTER TABLE app_public.events ENABLE ROW LEVEL SECURITY; +-- +-- Name: feature_flags; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.feature_flags ENABLE ROW LEVEL SECURITY; + +-- +-- Name: registration_profiles insert_own; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY insert_own ON app_public.registration_profiles FOR INSERT WITH CHECK ((user_id = app_public.current_user_id())); + + -- -- Name: user_emails insert_own; Type: POLICY; Schema: app_public; Owner: - -- @@ -5065,6 +7105,13 @@ CREATE POLICY manage_admin ON app_public.event_questions USING (app_public.curre CREATE POLICY manage_admin ON app_public.events USING (app_public.current_user_is_admin()); +-- +-- Name: organizations manage_admin; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY manage_admin ON app_public.organizations USING (app_public.current_user_is_admin()); + + -- -- Name: quotas manage_admin; Type: POLICY; Schema: app_public; Owner: - -- @@ -5125,18 +7172,57 @@ ALTER TABLE app_public.organization_memberships ENABLE ROW LEVEL SECURITY; ALTER TABLE app_public.organizations ENABLE ROW LEVEL SECURITY; +-- +-- Name: reminder_preferences own_reminder_preferences; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY own_reminder_preferences ON app_public.reminder_preferences USING ((user_id = app_public.current_user_id())); + + +-- +-- Name: event_registration_reminders own_reminders; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY own_reminders ON app_public.event_registration_reminders USING ((user_id = app_public.current_user_id())); + + +-- +-- Name: telegram_accounts own_telegram_account; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY own_telegram_account ON app_public.telegram_accounts USING ((user_id = app_public.current_user_id())); + + +-- +-- Name: payments; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.payments ENABLE ROW LEVEL SECURITY; + -- -- Name: quotas; Type: ROW SECURITY; Schema: app_public; Owner: - -- ALTER TABLE app_public.quotas ENABLE ROW LEVEL SECURITY; +-- +-- Name: registration_profiles; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.registration_profiles ENABLE ROW LEVEL SECURITY; + -- -- Name: registrations; Type: ROW SECURITY; Schema: app_public; Owner: - -- ALTER TABLE app_public.registrations ENABLE ROW LEVEL SECURITY; +-- +-- Name: reminder_preferences; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.reminder_preferences ENABLE ROW LEVEL SECURITY; + -- -- Name: event_categories select_all; Type: POLICY; Schema: app_public; Owner: - -- @@ -5186,6 +7272,20 @@ CREATE POLICY select_all ON app_public.registrations FOR SELECT USING (true); CREATE POLICY select_all ON app_public.users FOR SELECT USING (true); +-- +-- Name: feature_flags select_developer; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY select_developer ON app_public.feature_flags FOR SELECT USING (app_public.current_user_is_developer()); + + +-- +-- Name: payments select_event_permissions; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY select_event_permissions ON app_public.payments FOR SELECT USING ((app_public.current_user_is_admin() OR app_public.current_user_has_event_permissions(event_id))); + + -- -- Name: organization_memberships select_invited; Type: POLICY; Schema: app_public; Owner: - -- @@ -5200,6 +7300,13 @@ CREATE POLICY select_invited ON app_public.organization_memberships FOR SELECT U CREATE POLICY select_member ON app_public.organization_memberships FOR SELECT USING ((organization_id IN ( SELECT app_public.current_user_member_organization_ids() AS current_user_member_organization_ids))); +-- +-- Name: registration_profiles select_own; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY select_own ON app_public.registration_profiles FOR SELECT USING ((user_id = app_public.current_user_id())); + + -- -- Name: user_authentications select_own; Type: POLICY; Schema: app_public; Owner: - -- @@ -5214,6 +7321,12 @@ CREATE POLICY select_own ON app_public.user_authentications FOR SELECT USING ((u CREATE POLICY select_own ON app_public.user_emails FOR SELECT USING ((user_id = app_public.current_user_id())); +-- +-- Name: telegram_accounts; Type: ROW SECURITY; Schema: app_public; Owner: - +-- + +ALTER TABLE app_public.telegram_accounts ENABLE ROW LEVEL SECURITY; + -- -- Name: registrations update_all; Type: POLICY; Schema: app_public; Owner: - -- @@ -5221,6 +7334,13 @@ CREATE POLICY select_own ON app_public.user_emails FOR SELECT USING ((user_id = CREATE POLICY update_all ON app_public.registrations FOR UPDATE USING (true); +-- +-- Name: registration_profiles update_own; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY update_own ON app_public.registration_profiles FOR UPDATE USING ((user_id = app_public.current_user_id())); + + -- -- Name: organizations update_owner; Type: POLICY; Schema: app_public; Owner: - -- @@ -5259,100 +7379,205 @@ ALTER TABLE app_public.users ENABLE ROW LEVEL SECURITY; -- Name: SCHEMA app_hidden; Type: ACL; Schema: -; Owner: - -- -GRANT USAGE ON SCHEMA app_hidden TO ilmo_visitor; +GRANT USAGE ON SCHEMA app_hidden TO ilmo_visitor; + + +-- +-- Name: SCHEMA app_public; Type: ACL; Schema: -; Owner: - +-- + +GRANT USAGE ON SCHEMA app_public TO ilmo_visitor; + + +-- +-- Name: SCHEMA public; Type: ACL; Schema: -; Owner: - +-- + +REVOKE USAGE ON SCHEMA public FROM PUBLIC; +GRANT USAGE ON SCHEMA public TO ilmo_visitor; + + +-- +-- Name: FUNCTION check_language(_column jsonb); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.check_language(_column jsonb) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.check_language(_column jsonb) TO ilmo_visitor; + + +-- +-- Name: FUNCTION assert_valid_password(new_password text); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.assert_valid_password(new_password text) FROM PUBLIC; + + +-- +-- Name: FUNCTION connect_telegram(token text, chat_id bigint, username text); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.connect_telegram(token text, chat_id bigint, username text) FROM PUBLIC; + + +-- +-- Name: FUNCTION current_user_can_manage_event_payments(event_id uuid); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.current_user_can_manage_event_payments(event_id uuid) FROM PUBLIC; + + +-- +-- Name: FUNCTION disconnect_telegram(target_user uuid); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.disconnect_telegram(target_user uuid) FROM PUBLIC; + + +-- +-- Name: TABLE users; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT SELECT ON TABLE app_public.users TO ilmo_visitor; + + +-- +-- Name: COLUMN users.username; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT UPDATE(username) ON TABLE app_public.users TO ilmo_visitor; + + +-- +-- Name: COLUMN users.name; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT UPDATE(name) ON TABLE app_public.users TO ilmo_visitor; + + +-- +-- Name: COLUMN users.avatar_url; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT UPDATE(avatar_url) ON TABLE app_public.users TO ilmo_visitor; + + +-- +-- Name: FUNCTION link_or_register_user(f_user_id uuid, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.link_or_register_user(f_user_id uuid, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json) FROM PUBLIC; + + +-- +-- Name: FUNCTION login(username public.citext, password text); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.login(username public.citext, password text) FROM PUBLIC; + + +-- +-- Name: FUNCTION really_create_user(username public.citext, email text, name text, avatar_url text, password text, email_is_verified boolean, is_admin boolean); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.really_create_user(username public.citext, email text, name text, avatar_url text, password text, email_is_verified boolean, is_admin boolean) FROM PUBLIC; + + +-- +-- Name: FUNCTION refresh_registration_positions(p_event_id uuid); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.refresh_registration_positions(p_event_id uuid) FROM PUBLIC; -- --- Name: SCHEMA app_public; Type: ACL; Schema: -; Owner: - +-- Name: FUNCTION register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean); Type: ACL; Schema: app_private; Owner: - -- -GRANT USAGE ON SCHEMA app_public TO ilmo_visitor; +REVOKE ALL ON FUNCTION app_private.register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean) FROM PUBLIC; -- --- Name: SCHEMA public; Type: ACL; Schema: -; Owner: - +-- Name: TABLE registrations; Type: ACL; Schema: app_public; Owner: - -- -REVOKE USAGE ON SCHEMA public FROM PUBLIC; -GRANT USAGE ON SCHEMA public TO ilmo_visitor; +GRANT SELECT,DELETE ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: FUNCTION check_language(_column jsonb); Type: ACL; Schema: app_public; Owner: - +-- Name: COLUMN registrations.event_id; Type: ACL; Schema: app_public; Owner: - -- -REVOKE ALL ON FUNCTION app_public.check_language(_column jsonb) FROM PUBLIC; -GRANT ALL ON FUNCTION app_public.check_language(_column jsonb) TO ilmo_visitor; +GRANT INSERT(event_id) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: FUNCTION assert_valid_password(new_password text); Type: ACL; Schema: app_private; Owner: - +-- Name: COLUMN registrations.quota_id; Type: ACL; Schema: app_public; Owner: - -- -REVOKE ALL ON FUNCTION app_private.assert_valid_password(new_password text) FROM PUBLIC; +GRANT INSERT(quota_id) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: TABLE users; Type: ACL; Schema: app_public; Owner: - +-- Name: COLUMN registrations.first_name; Type: ACL; Schema: app_public; Owner: - -- -GRANT SELECT ON TABLE app_public.users TO ilmo_visitor; +GRANT INSERT(first_name),UPDATE(first_name) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: COLUMN users.username; Type: ACL; Schema: app_public; Owner: - +-- Name: COLUMN registrations.last_name; Type: ACL; Schema: app_public; Owner: - -- -GRANT UPDATE(username) ON TABLE app_public.users TO ilmo_visitor; +GRANT INSERT(last_name),UPDATE(last_name) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: COLUMN users.name; Type: ACL; Schema: app_public; Owner: - +-- Name: COLUMN registrations.email; Type: ACL; Schema: app_public; Owner: - -- -GRANT UPDATE(name) ON TABLE app_public.users TO ilmo_visitor; +GRANT INSERT(email) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: COLUMN users.avatar_url; Type: ACL; Schema: app_public; Owner: - +-- Name: COLUMN registrations.answers; Type: ACL; Schema: app_public; Owner: - -- -GRANT UPDATE(avatar_url) ON TABLE app_public.users TO ilmo_visitor; +GRANT INSERT(answers),UPDATE(answers) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: FUNCTION link_or_register_user(f_user_id uuid, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json); Type: ACL; Schema: app_private; Owner: - +-- Name: COLUMN registrations.is_finished; Type: ACL; Schema: app_public; Owner: - -- -REVOKE ALL ON FUNCTION app_private.link_or_register_user(f_user_id uuid, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json) FROM PUBLIC; +GRANT INSERT(is_finished) ON TABLE app_public.registrations TO ilmo_visitor; -- --- Name: FUNCTION login(username public.citext, password text); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION registration_payment_status(registration app_public.registrations); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.login(username public.citext, password text) FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.registration_payment_status(registration app_public.registrations) FROM PUBLIC; -- --- Name: FUNCTION really_create_user(username public.citext, email text, name text, avatar_url text, password text, email_is_verified boolean, is_admin boolean); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION reset_password(user_id uuid, reset_token text, new_password text); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.really_create_user(username public.citext, email text, name text, avatar_url text, password text, email_is_verified boolean, is_admin boolean) FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.reset_password(user_id uuid, reset_token text, new_password text) FROM PUBLIC; -- --- Name: FUNCTION register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION schedule_registration_reminder(reminder_id uuid); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean) FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.schedule_registration_reminder(reminder_id uuid) FROM PUBLIC; -- --- Name: FUNCTION reset_password(user_id uuid, reset_token text, new_password text); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION set_feature_available(key text, available boolean); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.reset_password(user_id uuid, reset_token text, new_password text) FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.set_feature_available(key text, available boolean) FROM PUBLIC; -- @@ -5377,24 +7602,31 @@ REVOKE ALL ON FUNCTION app_private.tg__ownership_info() FROM PUBLIC; -- --- Name: FUNCTION tg__process_queue(); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION tg__refresh_registration_positions(); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.tg__process_queue() FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.tg__refresh_registration_positions() FROM PUBLIC; -- --- Name: FUNCTION tg__refresh_materialized_view(); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION tg__registration_is_valid(); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.tg__refresh_materialized_view() FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.tg__registration_is_valid() FROM PUBLIC; -- --- Name: FUNCTION tg__registration_is_valid(); Type: ACL; Schema: app_private; Owner: - +-- Name: FUNCTION tg__reschedule_registration_reminders(); Type: ACL; Schema: app_private; Owner: - -- -REVOKE ALL ON FUNCTION app_private.tg__registration_is_valid() FROM PUBLIC; +REVOKE ALL ON FUNCTION app_private.tg__reschedule_registration_reminders() FROM PUBLIC; + + +-- +-- Name: FUNCTION tg__schedule_registration_reminder(); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.tg__schedule_registration_reminder() FROM PUBLIC; -- @@ -5404,6 +7636,13 @@ REVOKE ALL ON FUNCTION app_private.tg__registration_is_valid() FROM PUBLIC; REVOKE ALL ON FUNCTION app_private.tg__timestamps() FROM PUBLIC; +-- +-- Name: FUNCTION tg_events__reset_unpaid_close_email(); Type: ACL; Schema: app_private; Owner: - +-- + +REVOKE ALL ON FUNCTION app_private.tg_events__reset_unpaid_close_email() FROM PUBLIC; + + -- -- Name: FUNCTION tg_user_email_secrets__insert_with_user_email(); Type: ACL; Schema: app_private; Owner: - -- @@ -5450,6 +7689,45 @@ REVOKE ALL ON FUNCTION app_public.admin_list_users() FROM PUBLIC; GRANT ALL ON FUNCTION app_public.admin_list_users() TO ilmo_visitor; +-- +-- Name: TABLE payments; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT SELECT ON TABLE app_public.payments TO ilmo_visitor; + + +-- +-- Name: FUNCTION admin_mark_registration_paid(registration_id uuid); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.admin_mark_registration_paid(registration_id uuid) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.admin_mark_registration_paid(registration_id uuid) TO ilmo_visitor; + + +-- +-- Name: FUNCTION admin_preview_features(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.admin_preview_features() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.admin_preview_features() TO ilmo_visitor; + + +-- +-- Name: FUNCTION admin_send_payment_reminders(event_id uuid); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.admin_send_payment_reminders(event_id uuid) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.admin_send_payment_reminders(event_id uuid) TO ilmo_visitor; + + +-- +-- Name: FUNCTION admin_unmark_registration_paid(registration_id uuid); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.admin_unmark_registration_paid(registration_id uuid) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.admin_unmark_registration_paid(registration_id uuid) TO ilmo_visitor; + + -- -- Name: FUNCTION admin_update_registration(id uuid); Type: ACL; Schema: app_public; Owner: - -- @@ -5474,6 +7752,14 @@ REVOKE ALL ON PROCEDURE app_public.check_is_admin() FROM PUBLIC; GRANT ALL ON PROCEDURE app_public.check_is_admin() TO ilmo_visitor; +-- +-- Name: PROCEDURE check_is_developer(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON PROCEDURE app_public.check_is_developer() FROM PUBLIC; +GRANT ALL ON PROCEDURE app_public.check_is_developer() TO ilmo_visitor; + + -- -- Name: PROCEDURE check_is_logged_in(IN message text); Type: ACL; Schema: app_public; Owner: - -- @@ -5603,6 +7889,13 @@ GRANT INSERT(owner_organization_id),UPDATE(owner_organization_id) ON TABLE app_p GRANT INSERT(category_id),UPDATE(category_id) ON TABLE app_public.events TO ilmo_visitor; +-- +-- Name: COLUMN events.highlight_text; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(highlight_text),UPDATE(highlight_text) ON TABLE app_public.events TO ilmo_visitor; + + -- -- Name: FUNCTION create_event(event app_public.event_input, quotas app_public.create_event_quotas[], questions app_public.create_event_questions[]); Type: ACL; Schema: app_public; Owner: - -- @@ -5668,6 +7961,13 @@ GRANT INSERT(is_required),UPDATE(is_required) ON TABLE app_public.event_question GRANT INSERT(data),UPDATE(data) ON TABLE app_public.event_questions TO ilmo_visitor; +-- +-- Name: COLUMN event_questions.prefill; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(prefill),UPDATE(prefill) ON TABLE app_public.event_questions TO ilmo_visitor; + + -- -- Name: FUNCTION create_event_questions(event_id uuid, questions app_public.create_event_questions[]); Type: ACL; Schema: app_public; Owner: - -- @@ -5711,6 +8011,13 @@ GRANT INSERT(title),UPDATE(title) ON TABLE app_public.quotas TO ilmo_visitor; GRANT INSERT(size),UPDATE(size) ON TABLE app_public.quotas TO ilmo_visitor; +-- +-- Name: COLUMN quotas.price_cents; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(price_cents),UPDATE(price_cents) ON TABLE app_public.quotas TO ilmo_visitor; + + -- -- Name: FUNCTION create_event_quotas(event_id uuid, quotas app_public.create_event_quotas[]); Type: ACL; Schema: app_public; Owner: - -- @@ -5756,75 +8063,49 @@ GRANT ALL ON FUNCTION app_public.create_organization(slug public.citext, name te -- --- Name: TABLE registrations; Type: ACL; Schema: app_public; Owner: - --- - -GRANT SELECT,DELETE ON TABLE app_public.registrations TO ilmo_visitor; - - --- --- Name: COLUMN registrations.event_id; Type: ACL; Schema: app_public; Owner: - --- - -GRANT INSERT(event_id) ON TABLE app_public.registrations TO ilmo_visitor; - - --- --- Name: COLUMN registrations.quota_id; Type: ACL; Schema: app_public; Owner: - --- - -GRANT INSERT(quota_id) ON TABLE app_public.registrations TO ilmo_visitor; - - --- --- Name: COLUMN registrations.first_name; Type: ACL; Schema: app_public; Owner: - --- - -GRANT INSERT(first_name),UPDATE(first_name) ON TABLE app_public.registrations TO ilmo_visitor; - - --- --- Name: COLUMN registrations.last_name; Type: ACL; Schema: app_public; Owner: - +-- Name: FUNCTION create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb); Type: ACL; Schema: app_public; Owner: - -- -GRANT INSERT(last_name),UPDATE(last_name) ON TABLE app_public.registrations TO ilmo_visitor; +REVOKE ALL ON FUNCTION app_public.create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb) TO ilmo_visitor; -- --- Name: COLUMN registrations.email; Type: ACL; Schema: app_public; Owner: - +-- Name: TABLE reminder_preferences; Type: ACL; Schema: app_public; Owner: - -- -GRANT INSERT(email) ON TABLE app_public.registrations TO ilmo_visitor; +GRANT SELECT ON TABLE app_public.reminder_preferences TO ilmo_visitor; -- --- Name: COLUMN registrations.answers; Type: ACL; Schema: app_public; Owner: - +-- Name: FUNCTION current_reminder_preferences(); Type: ACL; Schema: app_public; Owner: - -- -GRANT INSERT(answers),UPDATE(answers) ON TABLE app_public.registrations TO ilmo_visitor; +REVOKE ALL ON FUNCTION app_public.current_reminder_preferences() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.current_reminder_preferences() TO ilmo_visitor; -- --- Name: COLUMN registrations.is_finished; Type: ACL; Schema: app_public; Owner: - +-- Name: FUNCTION current_session_id(); Type: ACL; Schema: app_public; Owner: - -- -GRANT INSERT(is_finished) ON TABLE app_public.registrations TO ilmo_visitor; +REVOKE ALL ON FUNCTION app_public.current_session_id() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.current_session_id() TO ilmo_visitor; -- --- Name: FUNCTION create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb); Type: ACL; Schema: app_public; Owner: - +-- Name: TABLE telegram_accounts; Type: ACL; Schema: app_public; Owner: - -- -REVOKE ALL ON FUNCTION app_public.create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb) FROM PUBLIC; -GRANT ALL ON FUNCTION app_public.create_registration("registrationToken" text, "eventId" uuid, "quotaId" uuid, "firstName" text, "lastName" text, email public.citext, answers jsonb) TO ilmo_visitor; +GRANT SELECT ON TABLE app_public.telegram_accounts TO ilmo_visitor; -- --- Name: FUNCTION current_session_id(); Type: ACL; Schema: app_public; Owner: - +-- Name: FUNCTION current_telegram_account(); Type: ACL; Schema: app_public; Owner: - -- -REVOKE ALL ON FUNCTION app_public.current_session_id() FROM PUBLIC; -GRANT ALL ON FUNCTION app_public.current_session_id() TO ilmo_visitor; +REVOKE ALL ON FUNCTION app_public.current_telegram_account() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.current_telegram_account() TO ilmo_visitor; -- @@ -5867,6 +8148,14 @@ REVOKE ALL ON FUNCTION app_public.current_user_is_admin() FROM PUBLIC; GRANT ALL ON FUNCTION app_public.current_user_is_admin() TO ilmo_visitor; +-- +-- Name: FUNCTION current_user_is_developer(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.current_user_is_developer() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.current_user_is_developer() TO ilmo_visitor; + + -- -- Name: FUNCTION current_user_is_owner_organization_member(owner_organization_id uuid); Type: ACL; Schema: app_public; Owner: - -- @@ -5899,6 +8188,46 @@ REVOKE ALL ON FUNCTION app_public.delete_registration("updateToken" text) FROM P GRANT ALL ON FUNCTION app_public.delete_registration("updateToken" text) TO ilmo_visitor; +-- +-- Name: FUNCTION delete_registration_profile(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.delete_registration_profile() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.delete_registration_profile() TO ilmo_visitor; + + +-- +-- Name: FUNCTION disconnect_telegram(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.disconnect_telegram() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.disconnect_telegram() TO ilmo_visitor; + + +-- +-- Name: FUNCTION enable_event_reminder(event_id uuid, language text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.enable_event_reminder(event_id uuid, language text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.enable_event_reminder(event_id uuid, language text) TO ilmo_visitor; + + +-- +-- Name: FUNCTION enabled_features(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.enabled_features() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.enabled_features() TO ilmo_visitor; + + +-- +-- Name: FUNCTION events_payment_summary(e app_public.events); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.events_payment_summary(e app_public.events) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.events_payment_summary(e app_public.events) TO ilmo_visitor; + + -- -- Name: FUNCTION events_signup_closed(e app_public.events); Type: ACL; Schema: app_public; Owner: - -- @@ -5923,6 +8252,22 @@ REVOKE ALL ON FUNCTION app_public.events_signup_upcoming(e app_public.events) FR GRANT ALL ON FUNCTION app_public.events_signup_upcoming(e app_public.events) TO ilmo_visitor; +-- +-- Name: FUNCTION feature_enabled(key text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.feature_enabled(key text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.feature_enabled(key text) TO ilmo_visitor; + + +-- +-- Name: FUNCTION feature_flag_events(flag_key text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.feature_flag_events(flag_key text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.feature_flag_events(flag_key text) TO ilmo_visitor; + + -- -- Name: FUNCTION forgot_password(email public.citext); Type: ACL; Schema: app_public; Owner: - -- @@ -6009,6 +8354,14 @@ REVOKE ALL ON FUNCTION app_public.registrations_full_name(registration app_publi GRANT ALL ON FUNCTION app_public.registrations_full_name(registration app_public.registrations) TO ilmo_visitor; +-- +-- Name: FUNCTION registrations_payment_status(registration app_public.registrations); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.registrations_payment_status(registration app_public.registrations) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.registrations_payment_status(registration app_public.registrations) TO ilmo_visitor; + + -- -- Name: FUNCTION registrations_position(registration app_public.registrations); Type: ACL; Schema: app_public; Owner: - -- @@ -6041,6 +8394,14 @@ REVOKE ALL ON FUNCTION app_public.request_account_deletion() FROM PUBLIC; GRANT ALL ON FUNCTION app_public.request_account_deletion() TO ilmo_visitor; +-- +-- Name: FUNCTION request_telegram_link(); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.request_telegram_link() FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.request_telegram_link() TO ilmo_visitor; + + -- -- Name: FUNCTION resend_email_verification_code(email_id uuid); Type: ACL; Schema: app_public; Owner: - -- @@ -6049,6 +8410,14 @@ REVOKE ALL ON FUNCTION app_public.resend_email_verification_code(email_id uuid) GRANT ALL ON FUNCTION app_public.resend_email_verification_code(email_id uuid) TO ilmo_visitor; +-- +-- Name: FUNCTION save_reminder_preferences(minutes_before integer, delivery_method text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.save_reminder_preferences(minutes_before integer, delivery_method text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.save_reminder_preferences(minutes_before integer, delivery_method text) TO ilmo_visitor; + + -- -- Name: FUNCTION set_admin_status(id uuid, is_admin boolean); Type: ACL; Schema: app_public; Owner: - -- @@ -6057,6 +8426,65 @@ REVOKE ALL ON FUNCTION app_public.set_admin_status(id uuid, is_admin boolean) FR GRANT ALL ON FUNCTION app_public.set_admin_status(id uuid, is_admin boolean) TO ilmo_visitor; +-- +-- Name: FUNCTION set_event_registration_reminder(event_id uuid, enabled boolean, language text, minutes_before integer, delivery_method text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.set_event_registration_reminder(event_id uuid, enabled boolean, language text, minutes_before integer, delivery_method text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.set_event_registration_reminder(event_id uuid, enabled boolean, language text, minutes_before integer, delivery_method text) TO ilmo_visitor; + + +-- +-- Name: TABLE feature_flags; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT SELECT ON TABLE app_public.feature_flags TO ilmo_visitor; + + +-- +-- Name: FUNCTION set_feature_flag(key text, state app_public.feature_state); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.set_feature_flag(key text, state app_public.feature_state) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.set_feature_flag(key text, state app_public.feature_state) TO ilmo_visitor; + + +-- +-- Name: TABLE registration_profiles; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT SELECT,DELETE ON TABLE app_public.registration_profiles TO ilmo_visitor; + + +-- +-- Name: COLUMN registration_profiles.user_id; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(user_id) ON TABLE app_public.registration_profiles TO ilmo_visitor; + + +-- +-- Name: COLUMN registration_profiles.telegram; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(telegram),UPDATE(telegram) ON TABLE app_public.registration_profiles TO ilmo_visitor; + + +-- +-- Name: COLUMN registration_profiles.dietary_restrictions; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT INSERT(dietary_restrictions),UPDATE(dietary_restrictions) ON TABLE app_public.registration_profiles TO ilmo_visitor; + + +-- +-- Name: FUNCTION set_registration_profile(telegram text, dietary_restrictions text); Type: ACL; Schema: app_public; Owner: - +-- + +REVOKE ALL ON FUNCTION app_public.set_registration_profile(telegram text, dietary_restrictions text) FROM PUBLIC; +GRANT ALL ON FUNCTION app_public.set_registration_profile(telegram text, dietary_restrictions text) TO ilmo_visitor; + + -- -- Name: FUNCTION supported_languages(); Type: ACL; Schema: app_public; Owner: - -- @@ -6227,6 +8655,13 @@ GRANT INSERT(owner_organization_id),UPDATE(owner_organization_id) ON TABLE app_p GRANT INSERT(color),UPDATE(color) ON TABLE app_public.event_categories TO ilmo_visitor; +-- +-- Name: TABLE event_registration_reminders; Type: ACL; Schema: app_public; Owner: - +-- + +GRANT SELECT,DELETE ON TABLE app_public.event_registration_reminders TO ilmo_visitor; + + -- -- Name: TABLE organization_memberships; Type: ACL; Schema: app_public; Owner: - -- diff --git a/docker-compose.yml b/docker-compose.yml index 8f7d07c93..06cf5412c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -25,6 +25,21 @@ services: log_directory=/var/lib/postgresql/data/logs -c log_rotation_age=60 -c log_truncate_on_rotation=on -c log_filename=server_log.hour.%H%M + # Optional local SSO + MCP auth: `docker compose --profile keycloak up -d`. + # The realm is imported from the fixture when the container is created; + # `docker compose --profile keycloak up -d --force-recreate keycloak` reloads it. + keycloak: + profiles: ["keycloak"] + image: quay.io/keycloak/keycloak:26.0 + command: start-dev --import-realm --http-port=8190 + environment: + KC_BOOTSTRAP_ADMIN_USERNAME: admin + KC_BOOTSTRAP_ADMIN_PASSWORD: admin + volumes: + - ./docker/keycloak/realm-dev.json:/opt/keycloak/data/import/realm-dev.json:ro + ports: + - "8190:8190" + volumes: db-volume: cache-volume: diff --git a/docker/keycloak/realm-dev.json b/docker/keycloak/realm-dev.json new file mode 100644 index 000000000..9eff7e9a3 --- /dev/null +++ b/docker/keycloak/realm-dev.json @@ -0,0 +1,163 @@ +{ + "realm": "ilmo-dev", + "enabled": true, + "sslRequired": "none", + "registrationAllowed": false, + "resetPasswordAllowed": false, + "rememberMe": false, + "verifyEmail": false, + "loginWithEmailAllowed": true, + "duplicateEmailsAllowed": false, + "bruteForceProtected": false, + "accessTokenLifespan": 300, + "ssoSessionIdleTimeout": 1800, + "ssoSessionMaxLifespan": 36000, + "roles": { + "realm": [ + { + "name": "ilmo-admin", + "description": "Maps to app_public.users.is_admin; the name is ILMO_ADMIN_ROLE in @app/server/src/utils/keycloak.ts" + } + ] + }, + "clients": [ + { + "clientId": "ilmo-dev", + "name": "ilmokilke (dev)", + "enabled": true, + "protocol": "openid-connect", + "publicClient": false, + "bearerOnly": false, + "secret": "ilmo-dev-secret", + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "frontchannelLogout": false, + "redirectUris": ["http://localhost:5678/auth/keycloak/callback"], + "webOrigins": ["http://localhost:5678"], + "attributes": { + "pkce.code.challenge.method": "S256", + "post.logout.redirect.uris": "http://localhost:5678/" + }, + "protocolMappers": [ + { + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "claim.name": "realm_access.roles", + "jsonType.label": "String", + "multivalued": "true", + "access.token.claim": "true", + "id.token.claim": "true", + "userinfo.token.claim": "false" + } + }, + { + "name": "locale", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "user.attribute": "locale", + "claim.name": "locale", + "jsonType.label": "String", + "multivalued": "false", + "aggregate.attrs": "false", + "access.token.claim": "true", + "id.token.claim": "true", + "userinfo.token.claim": "false" + } + } + ] + }, + { + "clientId": "ilmo-mcp", + "name": "ilmokilke MCP (dev)", + "description": "Public client for MCP clients. Access tokens carry the /mcp resource as audience.", + "enabled": true, + "protocol": "openid-connect", + "publicClient": true, + "bearerOnly": false, + "consentRequired": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "frontchannelLogout": false, + "redirectUris": [ + "http://localhost:33418/callback", + "http://localhost:6274/oauth/callback", + "http://localhost:6274/oauth/callback/debug" + ], + "webOrigins": ["http://localhost:6274"], + "attributes": { + "pkce.code.challenge.method": "S256", + "consent.screen.text": "Ilmon MCP-palvelin voi lukea tapahtumia ja ilmoittaa sinut tapahtumiin puolestasi. / The ilmo MCP server can read events and register you to events on your behalf." + }, + "protocolMappers": [ + { + "name": "mcp audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "consentRequired": false, + "config": { + "included.custom.audience": "http://localhost:5678/mcp", + "access.token.claim": "true", + "id.token.claim": "false" + } + } + ] + } + ], + "users": [ + { + "username": "dev-member", + "enabled": true, + "emailVerified": true, + "email": "dev-member@example.com", + "firstName": "Dev", + "lastName": "Member", + "attributes": { + "locale": ["fi"] + }, + "requiredActions": [], + "credentials": [ + { + "type": "password", + "value": "dev-member-password", + "temporary": false + } + ], + "realmRoles": ["default-roles-ilmo-dev"] + }, + { + "username": "dev-admin", + "enabled": true, + "emailVerified": true, + "email": "dev-admin@example.com", + "firstName": "Dev", + "lastName": "Admin", + "attributes": { + "locale": ["en"] + }, + "requiredActions": [], + "realmRoles": ["default-roles-ilmo-dev", "ilmo-admin"], + "credentials": [ + { + "type": "password", + "value": "dev-admin-password", + "temporary": false + } + ] + } + ], + "scopeMappings": [ + { + "client": "ilmo-mcp", + "roles": ["ilmo-admin"] + } + ] +} diff --git a/docs/keycloak-sso.md b/docs/keycloak-sso.md index 0f0d2d707..7fc42241d 100644 --- a/docs/keycloak-sso.md +++ b/docs/keycloak-sso.md @@ -62,6 +62,28 @@ would land on them is refused and their `is_admin` is left alone. Organization membership is unrelated to Keycloak and stays in ilmo's own database. +## Developer access + +The realm role `ilmo-developer` lets an admin switch runtime feature flags. It +is meant for the few people who deploy and operate ilmo, not for every admin. +Create and assign it in the membership-registry UI exactly like `ilmo-admin`. +The existing realm-roles mapper already sends it; no new mapper is needed. + +Ilmo stamps `users.is_developer` from the ID token on every SSO login, in the +same transaction and with the same rules as `is_admin`: the role is granted and +revoked at the member's next login, and a token without a `realm_access.roles` +claim leaves the column untouched. Developer rights apply only together with +admin rights, so a developer also needs `ilmo-admin`. + +Unlike admin, the developer permission has no in-app toggle: an admin could +otherwise grant it to themselves. Local and break-glass accounts never pass +through Keycloak, so they are developers only if an operator sets the column +directly: + +```sql +update app_public.users set is_developer = true where username = '...'; +``` + ## Account linking A first SSO login binds to an existing ilmo account in two ways. When the @@ -123,6 +145,11 @@ Finally copy the client secret into the ilmo secret store as For local development, register a second client in membership-registry's dev Keycloak with redirect URI `http://localhost:5678/auth/keycloak/callback` and point `KEYCLOAK_ISSUER` at `http://localhost:8180/realms/membership-registry`. +The repository also ships a self-contained dev realm, started with +`docker compose --profile keycloak up -d`; see `docs/mcp.md`. + +The MCP server at `/mcp` uses a second, public client, `ilmo-mcp`. Its setup is +in `docs/mcp.md`. ## Break-glass login diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 000000000..e29842f27 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,165 @@ +# MCP server + +Ilmo serves a [Model Context Protocol](https://modelcontextprotocol.io) server +at `https://ilmo.prodeko.org/mcp`. It lets an AI assistant such as Claude list +events and register the signed-in member to them. Members sign in with their +Prodeko account through Keycloak, the same login the web app uses. + +Tools: + +- `list_events` — published events whose registration is open or upcoming. +- `get_event` — one event with its description, quotas and registration + questions. +- `register_to_event` — registers to a quota. Answers are validated before a + spot is claimed, and a failed registration releases the spot it claimed. + +Admins also get: + +- `list_event_options` — organizations and their event categories, with the ids + `create_event` needs. +- `create_event` — creates an event with its quotas and questions. The event is + always an unpublished draft; an admin reviews and publishes it in the admin + UI, which the result links to. + +Admin tools are listed and run only when the access token carries the +`ilmo-admin` realm role, so revoking the role in membership-registry takes +effect on the next request. The database's own `users.is_admin` check applies on +top, and MCP never writes that flag: an admin must have signed in to the web app +since getting the role. + +Editing or cancelling a registration, and editing or publishing an event, are +not available over MCP. + +## Using it + +### claude.ai, Claude Desktop and mobile + +Settings → Connectors → **Add custom connector**: + +| Field | Value | +| -------------- | ----------------------------------------------------------- | +| Name | `Ilmo` | +| URL | `https://ilmo.prodeko.org/mcp` (exactly, no trailing slash) | +| Authentication | **Sign in now** | +| OAuth client | **Use your own OAuth client**, client ID `ilmo-mcp` | +| Client secret | empty | +| Transport | Streamable HTTP | + +Connect, sign in with the Prodeko account and accept the consent screen. The +sign-in lasts 30 days, after which Claude asks to sign in again. + +### Claude Code + +```sh +claude mcp add --transport http ilmo https://ilmo.prodeko.org/mcp \ + --client-id ilmo-mcp --callback-port 33418 +``` + +Then run `/mcp`, choose ilmo → Authenticate. The callback port is fixed because +Keycloak matches redirect URIs exactly. + +## Registering the Keycloak client + +The MCP server needs its own client, `ilmo-mcp`, in the `membership-registry` +realm. It is separate from the web client `ilmokilke`: it is public, because MCP +clients run on members' machines or in Claude's service and cannot keep a +secret, and its access tokens carry the MCP resource as their audience so that +`/mcp` accepts no token issued to another client of the realm. + +The labels below are those of the Keycloak 26 admin console. + +1. **Realm settings → Sessions**: Offline Session Max Limited **Enabled**, with + Offline Session Max longer than 30 days. Without this flag Keycloak ignores + the client-level maximum below. The flag applies to every client's offline + tokens, so check that no other client needs offline tokens without a lifespan + before turning it on. +2. **Realm settings → User registration → Default roles** must contain + `offline_access`. Claude requests that scope, and the code exchange fails + with "Offline tokens not allowed for the user or client" for a member without + the role. Roles are owned by membership-registry; add it there. +3. **Clients → Create client** + - General settings: Client type OpenID Connect, Client ID `ilmo-mcp`, Name + `Ilmokilke MCP`, Always Display in Console on (members can revoke it from + the account console). + - Capability config: Client authentication **off**, Authorization off, only + **Standard Flow** enabled, PKCE method **S256**. + - Login settings: Home URL `https://ilmo.prodeko.org`; Valid redirect URIs + `https://claude.ai/api/mcp/auth_callback` (claude.ai, Desktop, mobile) and + `http://localhost:33418/callback` (Claude Code); Web origins empty. +4. **Settings → Login settings**: Consent required **on**, Display client on + screen on, Client consent screen text "Ilmon MCP-palvelin voi lukea + tapahtumia ja ilmoittaa sinut tapahtumiin puolestasi. / The ilmo MCP server + can read events and register you to events on your behalf." +5. **Advanced → Advanced settings**: Client Offline Session Idle **30 days**, + Client Offline Session Max **30 days**. +6. **Client scopes → `ilmo-mcp-dedicated` → Configure a new mapper → Audience**: + Included Custom Audience `https://ilmo.prodeko.org/mcp`, Add to access token + on, Add to ID token off. A hardcoded audience is used instead of Audience + Resolve because the latter adds client IDs only, from client roles, and with + Full scope allowed would put ilmo's audience into other clients' tokens too. +7. **Client scopes**: `basic`, `email`, `profile`, `roles` as Default and + `offline_access` as Optional. +8. **Client scopes → `ilmo-mcp-dedicated` → Scope**: if Full scope allowed is + off, **Assign role** → realm role `ilmo-admin`. Without it admins' tokens + omit the role and the admin tools stay hidden. Do not turn Full scope allowed + on instead; it would put every realm role into these tokens. +9. **Client scopes → Evaluate**: pick a member, add `offline_access` to the + scope parameter and open Generated access token. It must contain + `"aud": "https://ilmo.prodeko.org/mcp"`, `"typ": "Bearer"`, `sid`, `email` + and `"email_verified": true`; ilmo refuses tokens without them. For an admin, + `realm_access.roles` must also contain `ilmo-admin`. + +If a WAF or IP filter sits in front of `id.prodeko.org` or `ilmo.prodeko.org`, +allow Anthropic's egress range `160.79.104.0/21`: claude.ai fetches Keycloak's +discovery document and tokens from its servers. + +Ilmo itself needs no new configuration beyond `KEYCLOAK_ISSUER`. The MCP routes +are registered whenever it is set, and they answer 404 until a developer turns +the `mcp_server` feature flag on. Until the client exists every request is then +simply answered with 401. + +## How it works + +- `/mcp` is a stateless Streamable HTTP endpoint (`mcp/routes.ts`, a module in + the external route registry, `externalRoutes.ts`). Requests without a valid + token get 401 with a `resource_metadata` pointer to + `/.well-known/oauth-protected-resource/mcp`, which names Keycloak as the + authorization server. +- The token's signature, issuer, audience, expiry and `typ` are verified against + Keycloak's JWKS (`mcp/auth.ts`). +- The token's `sub` resolves to the ilmo user through + `app_public.user_authentications`. A member who has never signed in is created + with `link_or_register_user`, like the web SSO callback does; an already + linked identity skips it, because that function overwrites the stored id token + the web logout relies on. Break-glass accounts are refused. +- Each Keycloak session (`sid`) maps to one `app_private.sessions` row of kind + `mcp`. Tools run the regular GraphQL operations as that session, so RLS, + ownership columns, rate limiting, the registration queue and the confirmation + email behave exactly as on the web. The session id never leaves the server. + Rows idle for an hour are deleted by `sessions__delete_inactive_mcp_sessions` + and recreated on the next request. +- `claimRegistrationToken` is rate limited per user for signed-in requests (per + IP for anonymous ones), so members whose requests all come from Claude's IP + range do not share one limit. + +## Local development + +`docker compose --profile keycloak up -d` starts a Keycloak with the realm in +`docker/keycloak/realm-dev.json`: the web client `ilmo-dev`, the MCP client +`ilmo-mcp` and the users `dev-member` / `dev-member-password` and `dev-admin` / +`dev-admin-password`. Set + +```sh +KEYCLOAK_ISSUER=http://localhost:8190/realms/ilmo-dev +``` + +in `.env` and turn the `mcp_server` flag on to enable `/mcp`; web SSO stays off +until `KEYCLOAK_CLIENT_ID` and `KEYCLOAK_CLIENT_SECRET` are set as well. Then +add the server to Claude Code with `http://localhost:5678/mcp` and the flags +above. + +claude.ai cannot reach `localhost`. Testing it locally needs public tunnels to +both ilmo and Keycloak, with `ROOT_URL`, `KEYCLOAK_ISSUER`, Keycloak's hostname +and the client's audience and redirect URIs switched to the tunnel URLs for the +duration of the test. Turn `ENABLE_CYPRESS_COMMANDS` off and replace the +Keycloak admin password before opening a tunnel. diff --git a/docs/payments.md b/docs/payments.md new file mode 100644 index 000000000..26a6e84e1 --- /dev/null +++ b/docs/payments.md @@ -0,0 +1,229 @@ +# Stripe payments + +Ilmo can charge for event quotas through Stripe Checkout (cards, Apple Pay and +Google Pay). Two things decide whether payments are on: + +- **Configuration.** Both of these environment variables must be set for the + server (the worker never calls Stripe): + + | Variable | Value | + | ----------------------- | ------------------------------------------------------- | + | `STRIPE_SECRET_KEY` | Stripe secret API key, `sk_test_...` (or `sk_live_...`) | + | `STRIPE_WEBHOOK_SECRET` | Signing secret of the webhook endpoint, `whsec_...` | + + At startup the server records whether they are present in the `available` + column of the `payments` feature flag (`requiresEnv` in + `@app/lib/src/featureFlags.ts`; `paymentsConfigured()` in + `@app/lib/src/payments.ts`). Without them the flag reads as off and cannot be + switched on, and the webhook route is not registered. + +- **The `payments` feature flag** (off, admins only, or on), switched by a + developer. While it is off no payment UI is shown and nobody can start a + payment; see [Turning payments off](#turning-payments-off). + +An event is paid when one of its quotas has a ticket price; there is no separate +payment setting. Payment opens when the event's registration closes: nobody pays +while registration is open. Ilmo never refunds anything; see +[Refunds](#refunds). + +Money is always stored as integer cents. A participant pays the quota's ticket +price at the time of payment plus a 0,25 € service fee; Stripe keeps 0,25 € + +1,5 %. + +## Testing locally with your own Stripe test-mode keys + +You need a Stripe account (a free personal one is fine; it stays in test mode) +and the [Stripe CLI](https://docs.stripe.com/stripe-cli). + +1. **Get a test-mode secret key.** In the Stripe dashboard, switch to _Test + mode_ and open _Developers → API keys_ + (https://dashboard.stripe.com/test/apikeys). Copy the _Secret key_ + (`sk_test_...`). + +2. **Forward webhooks to your machine.** Log the CLI in once and start the + forwarder, limited to the two events Ilmo handles (`HANDLED_STRIPE_EVENTS` in + `@app/server/src/payments/webhook.ts`): + + ```sh + stripe login + stripe listen \ + --events checkout.session.completed,checkout.session.expired \ + --forward-to localhost:5678/api/stripe/webhook + ``` + + It prints `Your webhook signing secret is whsec_...`. Keep it running while + you test; the secret stays the same between runs of `stripe listen` for the + same account. If your `PORT` is not 5678, change the URL to match. + +3. **Set the variables in `.env`.** `pnpm setup` asks for the keys (optional) + whenever `.env` has no `STRIPE_SECRET_KEY` line yet, for example the first + time it creates `.env`. Otherwise edit `.env`: + + ```sh + STRIPE_SECRET_KEY=sk_test_... + STRIPE_WEBHOOK_SECRET=whsec_... # the one printed by `stripe listen` + ``` + +4. **Restart** `pnpm dev` (or the server) so that it picks up the new + environment, then switch the `payments` feature flag on (as a developer, with + the `setFeatureFlag` mutation, or with + `select app_public.set_feature_flag('payments', 'on')` in a developer's + session). + +5. **Create a paid event.** Log in as an admin (or a member of the organizing + organization) and go to _Admin → Create event_ (`/admin/event/create`): + + - _Quotas_ tab: set a _Ticket price_ for at least one quota. 0 € is free; + otherwise the price must be between 0,25 € and 10 000 €. "Guild receives ≈" + shows what is left after Stripe's fees. + - Make sure registration is open now, and save without _Save as draft_. + +6. **Register.** Open the event, pick the paid quota and register. The form says + what the ticket costs and that the payment link is emailed when registration + closes; nothing is paid now. The confirmation email says the same. + +7. **Close registration and pay.** Edit the event and move the registration end + time to a moment ago (or wait for it). Within a minute the worker's + `event__send_unpaid_on_close` task emails everyone with a spot who has not + paid their own payment link, `/pay/`. Open it and press _Pay_, + which takes you to Stripe Checkout. Pay with the test card **4242 4242 4242 + 4242**, any future expiry date, any CVC and any postal code. Stripe sends you + back to `/pay/`, which shows a "Confirming your payment with + Stripe" notice until the `checkout.session.completed` webhook arrives (watch + the `stripe listen` terminal), then _Payment received_. The registration's + update page and the admin _Registrations_ tab show it as paid. Other useful + test cards: `4000 0000 0000 9995` (declined), `4000 0025 0000 3155` (asks for + 3-D Secure). + + While registration is open the pay page says when payment opens, and + `createCheckoutSession` fails with `PAYMENT_NOT_OPEN`. That also holds when + registration is reopened after it has closed: payments already made stay + paid, the others wait. Moving the registration end time later resets the + close email, so it goes out again when registration closes the next time. + +8. **Check the emails.** In development the worker sends email through + ethereal.email; the worker log prints the login and a preview URL for every + message (confirmation, payment link on close, reminder, payment received). + +### Refunds + +Ilmo never refunds a payment and never cancels a registration for not paying. +Refunds are made by hand in the Stripe dashboard +(https://dashboard.stripe.com/payments); each payment's metadata in Stripe +(`registration_id`, `event_id`, `quota_id`, `payment_id`, `event_slug`) links it +to Ilmo. A refund made in Stripe does not change anything in Ilmo: the payment +stays paid there. + +- **Deleting a paid registration** is allowed, by the participant (only while + registration is open, so after it has been reopened) and by an admin. Both + confirmations warn that nothing is refunded automatically. The payment is + kept, no longer linked to a registration. +- **Payments Ilmo did not expect** are recorded as paid but not linked to a + registration, and the server logs an error saying to refund them in Stripe if + needed: a second payment for a registration that is already paid, a payment + whose amount differs from what the payment row expects, and a payment + completed after its registration was deleted. A paid Checkout Session with no + payment row at all is only logged; the message says whether this Ilmo created + it (its `ilmo_url` metadata equals this instance's `ROOT_URL`). +- **Changing a price** after some have paid is allowed. Paid registrations stay + paid; unpaid ones pay the new price. + +The payment summary in an event's _Registrations_ tab shows how many card +payments are not linked to a registration, with a hint to refund them in Stripe +when needed. + +### Other admin tools + +The _Registrations_ tab of a paid event shows the paid/unpaid summary, an All / +Unpaid / Paid filter, a _Send reminder to N unpaid_ button (emails the payment +link to everyone with a spot who has not paid) and, in each row's "⋯" menu, +_Mark as paid_ / _Undo manual payment_ for money collected outside Stripe. The +CSV download includes the payment status and price. + +## Automated tests + +The test suites never contact Stripe. + +- Jest: `pnpm test`. The server tests mock the Stripe client and set the Stripe + variables themselves; the server and worker tests switch the `payments` flag + with `setFeatureFlag`. Every other test runs with the flag off. +- Cypress: `@app/e2e/cypress/e2e/payments_admin.spec.ts` and + `payments_register.spec.ts` need a server started with Stripe configured + (dummy values are enough) and a worker. The specs switch the `payments` flag + on with the `setFeatureFlags` server command: + + ```sh + STRIPE_SECRET_KEY=sk_test_dummy STRIPE_WEBHOOK_SECRET=whsec_dummy \ + pnpm --filter @app/server run start + pnpm --filter @app/worker run start + cd @app/e2e && pnpm run run:local + ``` + + The specs close registration with the `closeEventRegistration` Cypress server + command, stub `createCheckoutSession` and the Checkout page, and complete + payments with the `completeStripeCheckout` command + (`@app/server/src/middleware/installCypressServerCommand.ts`, only available + with `ENABLE_CYPRESS_COMMANDS=1` outside production), which posts a + `checkout.session.completed` event signed with `STRIPE_WEBHOOK_SECRET` to the + real webhook route. The sharded Cypress job in `.github/workflows/e2e.yml` + appends the dummy values to `.env`. + +## Staging and production setup + +Do this once per Stripe account (use test mode for staging): + +1. **API key:** _Developers → API keys_. Use the secret key, or a restricted key + with write access to Checkout Sessions only (Ilmo creates, retrieves and + expires Checkout Sessions; it reads nothing else and makes no refunds), as + `STRIPE_SECRET_KEY`. Live keys (`sk_live_...`, `rk_live_...`) belong in the + production environment only; staging and development use test-mode keys. +2. **Webhook endpoint:** _Developers → Webhooks → Add endpoint_: + - Endpoint URL: `/api/stripe/webhook`, e.g. + `https://ilmo.prodeko.org/api/stripe/webhook`. + - Events to send: exactly `checkout.session.completed` and + `checkout.session.expired`. + - Copy the endpoint's _Signing secret_ (`whsec_...`) to + `STRIPE_WEBHOOK_SECRET`. +3. **Email receipts on:** _Settings → Customer emails_ (Business → Customer + emails), turn on _Successful payments_, and _Refunds_ for the refunds you + make by hand. Ilmo relies on Stripe's receipt in addition to its own payment + received email. +4. **MobilePay off:** _Settings → Payment methods_, turn MobilePay (and any + other non-card method) off. Checkout already asks only for cards + (`allowed_payment_method_types: ["card"]`), so this keeps the dashboard + consistent with what Ilmo offers. Apple Pay and Google Pay come with cards. +5. **Statement descriptor:** _Settings → Business → Public details_, set a + descriptor participants will recognise (e.g. `PRODEKO`). +6. Set the two variables for the server and restart it. + +## Turning payments off + +Switch the `payments` feature flag off. Nothing is deleted: quotas keep their +prices, and payments stay in the database. A flag closes the ways in, never the +ways out. While it is off: + +- no payment UI is shown and events act as free; +- the database refuses setting non-zero quota prices (errcode `FTOFF`) and the + organizer payment actions (mark paid, undo, send reminders); +- `createCheckoutSession` fails with `PAYMENTS_DISABLED`; the pay page still + shows a payment already made; +- payment reminders and the close-of-registration email are skipped. A send + missed while the flag was off stays missed: the close email only covers events + whose registration closed after the flag was last switched; +- the webhook keeps answering, so payments started before the switch still + settle and the payment received email still goes out. + +To stop taking payments for a single event instead, set the prices of its quotas +to 0 €. Payments already made stay paid. + +**Removing the Stripe keys** makes the flag unavailable and also stops what the +flag leaves running: the webhook route `/api/stripe/webhook` is not registered, +so payments in progress are not recorded until the keys are back (Stripe retries +undelivered events for a few days). Keep any such period short. + +## Keeping keys secret + +Never commit `.env`. Real Stripe keys never go in `.env.ci`, the GitHub +workflows or any other file in the repository; CI uses only the dummy values +`sk_test_dummy` / `whsec_dummy`. Set production keys in the production +environment only. diff --git a/docs/registration-reminders.md b/docs/registration-reminders.md new file mode 100644 index 000000000..f7d4915bf --- /dev/null +++ b/docs/registration-reminders.md @@ -0,0 +1,80 @@ +# Registration reminders + +Signed-in users can request one reminder per upcoming published event. Reminders +are sent before **registration opens**, not before the event starts. + +The first click on **Set up reminders** opens a two-step flow on the event page: +choose email, Telegram, or both (connecting Telegram in place if needed), then +choose a lead time and click **Save**. A verified primary email is required for +email delivery; Telegram requires a linked chat. Telegram is offered when the +bot is configured. Linking can be checked manually or by returning to the +browser tab after pressing Start in Telegram. + +Preferences are saved to the user's account across devices. Afterwards, **Set +reminder** enables each event in one click. **Change reminder settings** leads +to settings, where users can change defaults, manage Telegram, and remove +existing reminders. Saving preferences does not subscribe to new events. It +updates and reschedules the user's upcoming unsent reminders; sent and past +reminders retain their history. Already delivered channels are not resent. If a +delivery channel becomes unavailable, the next opt-in asks the user to repair +their settings. Existing users without saved preferences are also guided through +setup; their existing reminders are preserved. + +Lead-time presets are 5, 10, 15 or 30 minutes, 1 hour, or 1 day before opening. +Previously saved custom lead times remain available when editing defaults. +Subscribing inside that window schedules an immediate reminder. Delivery uses +the existing email transport, so local delivery still follows +`@app/worker/email.local.json` and its recipient allowlist. + +### Multiple reminders + +Each event has one reminder: a single clear opt-in and status is simpler, and +avoids duplicate immediate messages when several selected times have already +passed. Several reminder times per event (for example, 30 and 15 minutes) would +need separate delivery records per time, grouped cancellation, and a policy for +elapsed reminders. + +## Scheduling and delivery + +The database schedules a Graphile Worker job when a reminder is created. Editing +the registration opening time reschedules pending jobs; marking an event as a +draft pauses them, and republishing schedules them again. Removing a reminder, +event, or account removes its pending jobs. Sent reminders are not resent when +the event is edited. + +The worker reads the current event details and verified primary email +immediately before sending. It skips deleted, hidden, expired, or already-sent +reminders and reschedules jobs that are now too early. Emails show the opening +time in Finland's time zone, including daylight saving changes. Row locks +serialize delivery and cancellation. A cancellation cannot retract an email +already being sent. + +Normal retries skip reminders recorded as sent. SMTP and PostgreSQL cannot +commit atomically: a process crash after SMTP acceptance but before recording +success could still produce a duplicate. Delivery timing also depends on the +worker and email provider. Reminders do not reserve places or register users for +events. + +## Trying it locally + +1. Apply committed migrations with `pnpm db migrate`, regenerate GraphQL, and + run the usual `pnpm dev`. +2. Sign in with an account whose verified primary email is an allowed local test + recipient if real email delivery is enabled. +3. Create a published test event with registration opening in five minutes and + closing later, before the event starts. +4. Open the event and complete **Set up reminders**, choosing a 30-minute lead + time. Since the opening time is inside the reminder window, the worker should + send it shortly. +5. Check **My reminders** for the sent status and inspect the email's opening + time and event link. + +To test scheduling and cancellation without immediate delivery, set registration +to open an hour from now. Enable a reminder, change the opening time, or remove +the reminder before it becomes due. + +Database and worker tests cover account isolation, authentication and +verification, uniqueness, cancellation, rescheduling, hiding/deleting events, +late subscriptions, delivery idempotence, retries, and Finland time-zone +conversion. The database tests use the separate test database and mock delivery; +they do not send live email. diff --git a/docs/reminder-operations.md b/docs/reminder-operations.md new file mode 100644 index 000000000..eb02069f7 --- /dev/null +++ b/docs/reminder-operations.md @@ -0,0 +1,134 @@ +# Running registration reminders in production + +This feature runs in the existing Ilmo server, Graphile Worker and PostgreSQL. +It does not require a new Azure service. Email is sent through the existing +SendGrid transport; Telegram is sent through the Bot API. + +## Database migration + +The schema is in the committed migrations +`@app/db/migrations/committed/000013-add-registration-reminders.sql` (reminders, +preferences and scheduling) and `000014-add-telegram-reminders.sql` (Telegram +linking, bot language and polling state), with the feature flag rows +`registration_reminders` and `telegram_reminders`. + +This is a schema migration, not a local data export. Production users choose +preferences and link their own Telegram accounts. The SQL initializes a polling +offset. + +## Feature flags + +Both features are off until switched on in `app_public.feature_flags` (see the +feature flag registry in `@app/lib/src/featureFlags.ts`): + +- `registration_reminders`: the reminder button, settings page and menu link, + enabling reminders and saving preferences (FTOFF while off), and the + `reminder__send_registration` task. A reminder that comes due while the flag + is off is not sent later. Cancelling a reminder always works: while the flag + is off, the settings page still lists a user's reminders and linked Telegram + account so they can be removed and disconnected, and offers nothing else. +- `telegram_reminders`: also needs `registration_reminders`. The server marks it + unavailable without `TELEGRAM_BOT_TOKEN`. Gates the Telegram channel and link + codes (FTOFF while off), the webhook (404), polling, and the + `reminder__send_telegram` and `telegram__reply` tasks. Disconnecting always + works. + +Apply committed migrations once with the new application image and the +production connection settings, before starting its server and worker: + +```sh +pnpm db migrate +``` + +Do not run `setup`, `setup:db`, `reset`, or `watch` against production. Ensure +the Graphile Worker database schema is installed before this application's +migration. Use the normal database backup process before deployment. An older +application image can leave the additive reminder tables in place; stopping the +new worker also stops notification delivery. A sent notification cannot be +recalled. + +## Production configuration + +| Variable | Container | Purpose | +| --------------------------------------- | ----------------- | ---------------------------------------------------------------- | +| `TELEGRAM_BOT_TOKEN` | Server and worker | Bot API credential; store as a secret | +| `TELEGRAM_BOT_USERNAME` | Server | Public bot username, without `@` | +| `TELEGRAM_UPDATE_MODE=webhook` | Server | Receive bot commands over HTTPS | +| `TELEGRAM_WEBHOOK_SECRET` | Server | Random 1–256-character secret using letters, digits, `_` and `-` | +| `ROOT_URL` | Server and worker | Public HTTPS application URL | +| `SENDGRID_USERNAME`, `SENDGRID_API_KEY` | Worker | Existing email delivery credentials | + +Keep the development bot separate from production. Runtime bot configuration is +read by the server; the image build does not need the bot token. + +After starting the new server and worker, register the webhook from the server +container's application directory, with its production environment loaded: + +```sh +node -r @app/config/env.js scripts/telegram-webhook.mjs set +node -r @app/config/env.js scripts/telegram-webhook.mjs status +``` + +The HTTPS reverse proxy must forward `/telegram/webhook` and preserve the +`X-Telegram-Bot-Api-Secret-Token` header. Registering the webhook also enables +the `callback_query` updates needed by language buttons. Do not run a local +poller against the production bot. + +## Deployment pipeline checks + +A push to `main` runs CI and end-to-end tests before the production workflow +builds `prodekoregistry.azurecr.io/ilmo/ilmo:sha-` and calls +`/srv/www/ilmo/deploy.sh` over SSH. That VM script is not in this repository. + +Verify that the VM script: + +- Deploys the same new image to both the server and worker. +- Applies committed migrations before starting the new application. +- Loads the production variables above into the correct containers. +- Keeps the worker running and captures its failures in logs/monitoring. + +The checked-in production Compose file still names the older separate server and +worker images. Confirm which Compose file the VM actually uses before +deployment; do not assume editing this repository's Compose file changes the +running setup. + +## Validation and smoke test + +Run `pnpm lint`, `pnpm test --ci --runInBand`, and `pnpm build` with local +services running. CI also exercises the Docker image and Cypress browser tests. +Automated Telegram tests mock outbound requests and send no real notifications. + +On a staging deployment, with both flags switched on: + +1. Sign in with a test account and open a published event whose registration + opens in the future. Complete setup and link the test bot by pressing Start. +2. Select a lead time longer than the remaining time until registration opens; + this makes the reminder due immediately. Confirm the Telegram message + arrives. +3. Run `/language`, choose the other language, and check a newly due reminder. + Changes also apply to reminders scheduled before changing language. +4. Enable another event in one click, reload, and confirm it remains enabled. +5. Cancel a reminder before it is due and confirm no message arrives. +6. If testing both channels, use a verified primary email and confirm each + channel delivers once. Changing bot language must not change email language. +7. Check worker logs for delivery failures and delayed jobs. A few seconds of + delay is acceptable; sustained backlog or repeated failures needs attention. + +## Maintenance + +- Event button: `@app/client/src/components/EventReminder.tsx`. +- Setup flow: `@app/client/src/components/ReminderPreferences.tsx`. +- Saved settings and reminder list: + `@app/client/src/pages/settings/reminders.tsx`. +- Website wording: `@app/client/src/translations/{fi,en,se}/reminders.json`. +- Bot replies, language names and language resolution: + `@app/lib/src/telegram.ts`. +- Bot command processing: `@app/server/src/telegram.ts`. +- Delivery checks, message text and event links: + `@app/worker/src/tasks/reminder__send_registration.ts`. +- Email appearance: `@app/worker/templates/registration_reminder.mjml.njk`. + +Change source files, update the corresponding tests, and use the normal pull +request process. Message wording is maintained in code, not BotFather. See also +[registration reminders](registration-reminders.md) and +[Telegram reminders](telegram-reminders.md). diff --git a/docs/telegram-reminders.md b/docs/telegram-reminders.md new file mode 100644 index 000000000..ac226f36b --- /dev/null +++ b/docs/telegram-reminders.md @@ -0,0 +1,119 @@ +# Telegram reminders + +The configured default bot username is **IlmoReminderBot**. No new third-party +packages are needed; the backend uses Telegram's HTTPS Bot API. + +## Local setup + +1. Create a bot with Telegram's BotFather and save `TELEGRAM_BOT_TOKEN` in your + local `.env`. Optionally set `TELEGRAM_BOT_USERNAME` (without `@`); it + defaults to `IlmoReminderBot`. Do not commit tokens or copy them into + logs/chat. +2. Apply migrations, regenerate GraphQL, and build as usual. Restart `pnpm dev` + after changing environment variables. The development server starts one + long-polling connection automatically when the token is configured. No public + address or tunnel is required for receiving bot updates. +3. In reminder setup or **Settings → My reminders**, click **Connect Telegram**. + Telegram opens automatically. Sign in to Telegram if needed and press **START + BOT** (or **Start**). Return to Ilmo; the connection is checked + automatically. If the browser blocks the new tab, use **Open Telegram**. + Expired links can be replaced with **Generate a new link**. +4. On a future event, complete **Set up reminders** and choose **Telegram** or + **Both**, then a lead time. Future events use your saved preferences with one + click. Email requires a verified primary email; Telegram alone does not. +5. To test immediately, use an event whose registration starts in 5 minutes and + select a 10-minute reminder. The message includes the opening time in Finland + and a link. Local HTTP event links are plain text because Telegram inline + buttons may reject local URLs. They work only while the phone can reach the + development machine; production HTTPS links use a button. + +The poller refuses to run over an existing webhook. Only one poller per database +runs, enforced with a PostgreSQL advisory lock. Polling offsets are durable. Use +a separate test bot/database from production to avoid competing consumers. + +The bot API requests run on the machine hosting Ilmo: the developer's laptop +locally, and the application server in production. A phone is only a Telegram +client; a hotspot merely supplies the laptop's internet connection. If Telegram +opens but commands receive no replies, check that the backend can reach +`api.telegram.org` through its network/DNS and that the worker is running. The +local poller retries transient startup connection failures automatically; it +does not overwrite an existing webhook or change network settings. + +## Production + +Store `TELEGRAM_BOT_TOKEN`, `TELEGRAM_BOT_USERNAME`, and a randomly generated +`TELEGRAM_WEBHOOK_SECRET` in the deployment's secret configuration. The webhook +secret may contain 1–256 ASCII letters, digits, underscores, and hyphens. Use an +HTTPS `ROOT_URL`. Production defaults to `TELEGRAM_UPDATE_MODE=webhook` and +requires the secret. After deployment, run: + +```sh +node -r @app/config/env.js scripts/telegram-webhook.mjs set +``` + +The script reads credentials through the normal configuration loader and does +not print them. `status` reports whether a webhook exists; `delete` removes it +without discarding pending updates. Set `TELEGRAM_UPDATE_MODE=polling` +explicitly if production uses a single long-running polling process instead. +Polling and webhooks cannot run simultaneously for the same bot. Ensure the +backend and Graphile Worker remain running; Telegram itself does not run our +code. + +## Bot language + +Send `/language` to the bot and select **English**, **Suomi**, or **Automatic**. +The text commands `/language en`, `/language fi`, and `/language auto` work too. +The welcome and successful linking replies mention this command. There is no +required language-selection step when linking. + +Automatic is the default. It uses the latest language hint received from +Telegram: Finnish (`fi` or `fi-*`) uses Finnish; other languages use English. If +Telegram omits the hint, the last detected language is retained, or English is +used for a new chat. Explicit choices always override automatic detection. +Telegram language changes become visible when the user next interacts with the +bot; the bot cannot detect a client setting change without an update. + +All new bot replies and Telegram reminders resolve the preference at delivery +time. Changing it also affects reminders that were scheduled earlier. Event +names fall back to an available translation if necessary. Email reminders keep +the language saved with the reminder. + +Preferences are stored privately per Telegram chat, including before linking, +and survive `/stop` and reconnecting. Chat identifiers and preferences are not +exposed through GraphQL. Language buttons only affect the private chat's owner; +updates and selections are deduplicated just like linking updates. + +For existing production webhooks, rerun the webhook `set` command after +deployment to enable `callback_query` updates for the language buttons. Local +polling picks up the additional update type on restart. No BotFather changes are +required; adding `/language` to the BotFather command menu is optional. + +## Linking, cancellation, and retries + +Link codes are random, single-use, expire after 15 minutes, and are stored only +as hashes. Requesting a new code replaces the old one. A chat cannot be silently +moved between Ilmo accounts. Usernames are display-only; the numeric +private-chat identifier determines delivery. Group messages are ignored. The +GraphQL API never exposes bot tokens, chat identifiers, or other users' links. + +Settings **Disconnect Telegram**, bot `/stop`, and bot-block updates unlink the +account. Pending Telegram-only reminders are removed. Reminders using both +channels keep email delivery. Deleting an account or event cascades to reminders +and jobs. Hidden events pause reminders; opening-time edits reschedule them, and +late jobs do not send after registration opens. Telegram delivery rechecks the +link before sending. Already-started deliveries cannot be recalled. + +Email and Telegram use separate Graphile jobs/checkpoints, so a retry on one +channel does not repeat the other. Telegram jobs share a serial queue, are paced +below the free broadcast limit, honor rate-limit retry delays, and unlink chats +when delivery is forbidden (for example, the bot is blocked). Each successful +channel is recorded before its job completes. As with SMTP, a process crash +between provider acceptance and the database commit can still cause a duplicate. +Webhook and polling updates are deduplicated transactionally; replies are queued +in the same transaction as account changes. + +Automated tests mock all outbound messages. A real end-to-end test requires the +user to press **Start** in Telegram and then set a reminder in Ilmo. + +References: [Telegram Bot API](https://core.telegram.org/bots/api), +[account linking](https://core.telegram.org/bots/features#deep-linking). diff --git a/jest.config.base.ts b/jest.config.base.ts index b6a32ad61..a837e93ab 100644 --- a/jest.config.base.ts +++ b/jest.config.base.ts @@ -1,3 +1,8 @@ +// scripts/test.mjs sets IN_TESTS for `pnpm test`; set it here too so that +// running jest directly (one package, one file) behaves the same. Jest's +// workers inherit the environment of the process that loads this config. +process.env.IN_TESTS = process.env.IN_TESTS || "1" + module.exports = (dir) => { const pkg = require(`${dir}/package.json`) diff --git a/jest.config.ts b/jest.config.ts index a6309fca3..29e535024 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -1,3 +1,6 @@ export default { projects: ["/@app/*/jest.config.ts"], + // Restart the test worker after a test file leaves it above this size, so + // the heap stays bounded however many files run (see scripts/test.mjs). + workerIdleMemoryLimit: "2GB", } diff --git a/package.json b/package.json index d0a24e6f6..f0af03049 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "start": "node ./scripts/start.mjs", "test": "node scripts/test.mjs", "test:watch": "node scripts/test.mjs --watch", + "stress": "bash stress/run.sh", "lint": "tsc -b && pnpm prettier:all --check && pnpm eslint .", "lint:fix": "pnpm eslint --fix . && pnpm prettier:all --write && jsonsort @app/client/src/translations", "eslint": "eslint", @@ -31,7 +32,8 @@ "lib": "pnpm --filter @app/lib", "server": "pnpm --filter @app/server", "worker": "pnpm --filter @app/worker", - "postinstall": "npx next telemetry disable" + "postinstall": "npx next telemetry disable", + "prepare": "husky || true" }, "packageManager": "pnpm@10.34.5", "author": "Prodeko webbitiimi ", @@ -78,9 +80,11 @@ "globals": "^15.14.0", "graphql": "^16.5.0", "graphql-config": "^4.3.3", + "husky": "^9.1.7", "inquirer": "^9.1.0", "jest": "^29.7.0", "json-sort-cli": "^2.0.15", + "lint-staged": "^17.6.0", "nodemon": "^2.0.19", "npm-check-updates": "^16.0.5", "prettier": "3.4.2", @@ -92,6 +96,13 @@ "type-fest": "^2.18.0", "typescript": "5.7.3" }, + "lint-staged": { + "*.{js,jsx,ts,tsx}": [ + "eslint --fix --no-warn-ignored", + "prettier --write" + ], + "*.{graphql,md}": "prettier --write" + }, "pnpm": { "overrides": { "dayjs": "^1.11.20", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d935534db..2cc67ea03 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -131,6 +131,9 @@ importers: graphql-config: specifier: ^4.3.3 version: 4.5.0(@types/node@22.19.17)(bufferutil@4.1.0)(encoding@0.1.13)(graphql@15.10.2)(utf-8-validate@5.0.10) + husky: + specifier: ^9.1.7 + version: 9.1.7 inquirer: specifier: ^9.1.0 version: 9.3.8(@types/node@22.19.17) @@ -140,6 +143,9 @@ importers: json-sort-cli: specifier: ^2.0.15 version: 2.1.11 + lint-staged: + specifier: ^17.6.0 + version: 17.6.0 nodemon: specifier: ^2.0.19 version: 2.0.22 @@ -272,6 +278,9 @@ importers: antd-img-crop: specifier: ^4.21.0 version: 4.30.0(antd@5.29.3(date-fns@2.30.0)(moment@2.30.1)(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react-dom@18.2.0(react@18.2.0))(react@18.2.0) + canvas-confetti: + specifier: ^1.9.4 + version: 1.9.4 dayjs: specifier: ^1.11.20 version: 1.11.20 @@ -342,6 +351,9 @@ importers: specifier: ^4.2.2 version: 4.2.2(@urql/core@5.2.0(graphql@15.10.2))(react@18.2.0) devDependencies: + '@types/canvas-confetti': + specifier: ^1.9.0 + version: 1.9.0 '@types/nprogress': specifier: ^0.2.0 version: 0.2.3 @@ -360,6 +372,9 @@ importers: '@app/db': dependencies: + cross-env: + specifier: ^7.0.3 + version: 7.0.3 graphile-migrate: specifier: ^1.4.0 version: 1.4.1 @@ -370,6 +385,9 @@ importers: '@app/graphql': specifier: workspace:* version: link:../graphql + '@app/lib': + specifier: workspace:* + version: link:../lib '@faker-js/faker': specifier: ^9.3.0 version: 9.9.0 @@ -565,9 +583,9 @@ importers: '@graphile/pg-pubsub': specifier: ^4.12.3 version: 4.14.1(graphile-build@4.14.1(graphql@15.10.2))(graphql@15.10.2)(postgraphile@4.14.1(bufferutil@4.1.0)(utf-8-validate@5.0.10)) - '@graphile/subscriptions-lds': - specifier: ^4.12.3 - version: 4.14.1(bufferutil@4.1.0)(postgraphile-core@4.14.1(graphql@15.10.2)(pg@8.20.0))(utf-8-validate@5.0.10) + '@modelcontextprotocol/sdk': + specifier: ^1.32.1 + version: 1.32.2(zod@4.6.7) '@types/graphql-upload': specifier: ^8.0.11 version: 8.0.12 @@ -628,6 +646,9 @@ importers: ioredis: specifier: ^5.2.2 version: 5.10.1 + jose: + specifier: ^5.10.0 + version: 5.10.0 lodash: specifier: ^4.17.21 version: 4.18.1 @@ -670,12 +691,18 @@ importers: source-map-support: specifier: ^0.5.21 version: 0.5.21 + stripe: + specifier: ^23.0.0 + version: 23.2.0(@types/node@18.19.130) tslib: specifier: ^2.6.0 version: 2.8.1 uuid: specifier: ^8.3.2 version: 8.3.2 + zod: + specifier: ^4.6.7 + version: 4.6.7 devDependencies: '@faker-js/faker': specifier: ^9.3.0 @@ -692,6 +719,9 @@ importers: '@types/pg': specifier: ^8.11.10 version: 8.20.0 + graphql-subscriptions: + specifier: ^1.2.1 + version: 1.2.1(graphql@15.10.2) jest: specifier: ^29.7.0 version: 29.7.0(@types/node@18.19.130)(babel-plugin-macros@3.1.0)(ts-node@10.9.2(@types/node@18.19.130)(typescript@5.9.3)) @@ -717,6 +747,9 @@ importers: chalk: specifier: ^4.1.2 version: 4.1.2 + cross-env: + specifier: ^7.0.3 + version: 7.0.3 dayjs: specifier: ^1.11.20 version: 1.11.20 @@ -754,9 +787,15 @@ importers: '@types/nunjucks': specifier: ^3.2.1 version: 3.2.6 + '@types/pg': + specifier: ^8.11.10 + version: 8.20.0 mkdirp: specifier: ^1.0.4 version: 1.0.4 + pg: + specifier: ^8.7.3 + version: 8.20.0 packages: @@ -1694,10 +1733,6 @@ packages: '@graphile-contrib/pg-simplify-inflector@6.1.0': resolution: {integrity: sha512-3eI2FP4ulu/fxwkJBNXhR6XEzqVz4wJWFr4LfeyUNNArUtLFx0DpP6YdcARCYgwLExFcIQNE8fnul3JKiciYIw==} - '@graphile/lds@4.14.1': - resolution: {integrity: sha512-JDsQ8Z05kkO6GGPDZ3nCkNLLvd1BR83/ps9Ipu17+nMKJqQLXgmcLvl8J9Xc9EKvPBNS5zL+dG06pXc7TWau5w==} - hasBin: true - '@graphile/logger@0.2.0': resolution: {integrity: sha512-jjcWBokl9eb1gVJ85QmoaQ73CQ52xAaOCF29ukRbYNl6lY+ts0ErTaDYOBlejcbUs2OpaiqYLO5uDhyLFzWw4w==} @@ -1718,11 +1753,6 @@ packages: graphql: 15.x postgraphile: ^4.4.0-beta.10 - '@graphile/subscriptions-lds@4.14.1': - resolution: {integrity: sha512-rl1gt3eALKdIA2xGm+h6tdTPFJoM9XL//LDcIrG13D4RAjlSsWDLAFrXpx73cYjWRIttsB0KbbuaeS/QPEka0A==} - peerDependencies: - postgraphile-core: '>4.3.1 <5' - '@graphql-codegen/add@5.0.3': resolution: {integrity: sha512-SxXPmramkth8XtBlAHu4H4jYcYXM/o3p01+psU+0NADQowA8jtYkK6MW5rV6T+CxkEaNZItfSmZRPgIuypcqnA==} peerDependencies: @@ -2136,6 +2166,12 @@ packages: peerDependencies: react: '*' + '@hono/node-server@2.1.11': + resolution: {integrity: sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 || ^5.0.0-0 + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -2437,6 +2473,16 @@ packages: resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==} engines: {node: '>=8'} + '@modelcontextprotocol/sdk@1.32.2': + resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} + engines: {node: '>=18'} + peerDependencies: + '@cfworker/json-schema': ^4.1.1 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + '@cfworker/json-schema': + optional: true + '@next/bundle-analyzer@16.2.4': resolution: {integrity: sha512-EAA9xTDv0P1IiUcZaASJJPkNDjRvL7OMTha6XN8MBzALYGfn7I52Mn7vRiyjVfNrtUPi2qiacY+eFVXe3lKCXA==} @@ -3248,6 +3294,9 @@ packages: '@types/cacheable-request@6.0.3': resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==} + '@types/canvas-confetti@1.9.0': + resolution: {integrity: sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg==} + '@types/connect@3.4.38': resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} @@ -3454,9 +3503,6 @@ packages: '@types/tedious@4.0.14': resolution: {integrity: sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==} - '@types/ws@6.0.4': - resolution: {integrity: sha512-PpPrX7SZW9re6+Ha8ojZG4Se8AZXgf0GK6zmfqEuCsY49LFDNXO3SByp44X3dFEqtB73lkCDAdUazhAjVPiNwg==} - '@types/ws@7.4.7': resolution: {integrity: sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww==} @@ -3677,6 +3723,10 @@ packages: abstract-logging@2.0.1: resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==} + accepts@2.0.0: + resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} + engines: {node: '>= 0.6'} + acorn-import-attributes@1.9.5: resolution: {integrity: sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==} peerDependencies: @@ -4111,6 +4161,10 @@ packages: resolution: {integrity: sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + body-parser@2.4.0: + resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} + engines: {node: '>=18'} + boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -4244,6 +4298,9 @@ packages: caniuse-lite@1.0.30001791: resolution: {integrity: sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==} + canvas-confetti@1.9.4: + resolution: {integrity: sha512-yxQbJkAVrFXWNbTUjPqjF7G+g6pDotOUHGbkZq2NELZUMDpiJ85rIEazVb8GTaAptNW2miJAXbs1BtioA251Pw==} + capital-case@1.0.4: resolution: {integrity: sha512-ds37W8CytHgwnhGGTi88pcPyR15qoNkOpYwmMMfnWqqWgESapLqvDx6huFjQ5vqWSn2Z06173XNA7LtMOeUh1A==} @@ -4484,16 +4541,28 @@ packages: resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} engines: {node: '>= 0.6'} + content-disposition@2.0.1: + resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} + engines: {node: '>=18'} + content-type@1.0.5: resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} engines: {node: '>= 0.6'} + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + convert-source-map@1.9.0: resolution: {integrity: sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==} convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + cookie-signature@1.2.2: + resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} + engines: {node: '>=6.6.0'} + cookie@0.4.2: resolution: {integrity: sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==} engines: {node: '>= 0.6'} @@ -4502,6 +4571,10 @@ packages: resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==} engines: {node: '>= 0.6'} + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} @@ -4518,6 +4591,10 @@ packages: core-util-is@1.0.2: resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==} + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + cosmiconfig@7.1.0: resolution: {integrity: sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==} engines: {node: '>=10'} @@ -4543,6 +4620,11 @@ packages: create-require@1.1.1: resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} + cross-env@7.0.3: + resolution: {integrity: sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==} + engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'} + hasBin: true + cross-fetch@3.2.0: resolution: {integrity: sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==} @@ -5140,6 +5222,10 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + eventemitter2@6.4.7: resolution: {integrity: sha512-tYUSVOGeQPKt/eC1ABfhHy5Xd96N3oIijJvN3O9+TsC28T5V9yX9oEfEK5faP0EFSNVOG97qtAS68GBrQB2hDg==} @@ -5153,6 +5239,14 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + execa@4.1.0: resolution: {integrity: sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA==} engines: {node: '>=10'} @@ -5184,6 +5278,16 @@ packages: exponential-backoff@3.1.3: resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==} + express-rate-limit@8.7.5: + resolution: {integrity: sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==} + engines: {node: '>= 16'} + peerDependencies: + express: '>= 4.11' + + express@5.3.0: + resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==} + engines: {node: '>= 18'} + extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} @@ -5295,6 +5399,10 @@ packages: resolution: {integrity: sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==} engines: {node: '>= 0.8'} + finalhandler@2.1.1: + resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} + engines: {node: '>= 18.0.0'} + find-cache-dir@4.0.0: resolution: {integrity: sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg==} engines: {node: '>=14.16'} @@ -5355,10 +5463,18 @@ packages: forwarded-parse@2.1.2: resolution: {integrity: sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==} + forwarded@0.2.0: + resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} + engines: {node: '>= 0.6'} + fp-and-or@0.1.4: resolution: {integrity: sha512-+yRYRhpnFPWXSly/6V4Lw9IfOV26uu30kynGJ03PW+MnjOEQe45RZ141QcS0aJehYBYA50GfCDnsRbFJdhssRw==} engines: {node: '>=10'} + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + fs-capacitor@6.2.0: resolution: {integrity: sha512-nKcE1UduoSKX27NSZlg879LdQc94OtbOsEmKMN2MBNudXREvijRKx2GEBsTMTfws+BrbkJoEuynbGSVRSpauvw==} engines: {node: '>=10'} @@ -5734,6 +5850,10 @@ packages: resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==} engines: {node: '>=0.10.0'} + hono@4.13.19: + resolution: {integrity: sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==} + engines: {node: '>=16.9.0'} + hosted-git-info@4.1.0: resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} engines: {node: '>=10'} @@ -5824,6 +5944,11 @@ packages: humanize-ms@1.2.1: resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==} + husky@9.1.7: + resolution: {integrity: sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==} + engines: {node: '>=18'} + hasBin: true + iconv-lite@0.4.24: resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} engines: {node: '>=0.10.0'} @@ -5836,6 +5961,10 @@ packages: resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==} engines: {node: '>=0.10.0'} + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} @@ -5944,6 +6073,10 @@ packages: resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} engines: {node: '>= 12'} + ipaddr.js@1.9.1: + resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} + engines: {node: '>= 0.10'} + ipaddr.js@2.3.0: resolution: {integrity: sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==} engines: {node: '>= 10'} @@ -6086,6 +6219,9 @@ packages: resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} engines: {node: '>=0.10.0'} + is-promise@4.0.0: + resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} + is-reference@1.2.1: resolution: {integrity: sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==} @@ -6412,6 +6548,9 @@ packages: json-schema-traverse@1.0.0: resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + json-schema-typed@8.0.2: + resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + json-schema@0.4.0: resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} @@ -6523,6 +6662,11 @@ packages: lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + lint-staged@17.6.0: + resolution: {integrity: sha512-nOhBfYkZEwkFtNzD5pK9s9LkcWoxJ+whLzEnhqi9nl7zTB5n7tg8+9iYgMGx2Wm3VlLu8cbNj0RACzY+nWi5iQ==} + engines: {node: '>=22.22.1'} + hasBin: true + listr2@3.14.0: resolution: {integrity: sha512-TyWI8G99GX9GjE54cJ+RrNMcIFBfwMPxc3XTFiAYGN4s10hWROGtOg7+O6u6LE3mNkyld7RSLE6nrKBvTfcs3g==} engines: {node: '>=10.0.0'} @@ -6696,6 +6840,10 @@ packages: resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==} engines: {node: '>= 0.6'} + media-typer@1.1.1: + resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==} + engines: {node: '>= 0.8'} + mensch@0.3.4: resolution: {integrity: sha512-IAeFvcOnV9V0Yk+bFhYR07O3yNina9ANIN5MoXBKYJ/RLYPurd2d0yw14MDhpr9/momp0WofT1bPUh3hkzdi/g==} @@ -6703,6 +6851,10 @@ packages: resolution: {integrity: sha512-Cl0yeeIrko6d94KpUo1M+0X1sB14ikoaqlIGuTH1fW4I+E3+YljL54/hb/BWmVfrV9tTV9zU04+xjw08Fh2WkA==} engines: {node: '>=14.16'} + merge-descriptors@2.0.0: + resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} + engines: {node: '>=18'} + merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} @@ -6735,6 +6887,10 @@ packages: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + mime@2.6.0: resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} engines: {node: '>=4.0.0'} @@ -6993,6 +7149,10 @@ packages: resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} engines: {node: '>= 0.6'} + negotiator@1.1.0: + resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} + engines: {node: '>=18'} + neo-async@2.6.2: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} @@ -7425,6 +7585,9 @@ packages: resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} engines: {node: 18 || 20 || >=22} + path-to-regexp@8.4.2: + resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} + path-type@4.0.0: resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} engines: {node: '>=8'} @@ -7490,6 +7653,10 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + pify@2.3.0: resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==} engines: {node: '>=0.10.0'} @@ -7516,6 +7683,10 @@ packages: resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} engines: {node: '>= 6'} + pkce-challenge@5.0.1: + resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} + engines: {node: '>=16.20.0'} + pkg-dir@4.2.0: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} @@ -7647,6 +7818,10 @@ packages: proto-list@1.2.4: resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} + engines: {node: '>= 0.10'} + proxy-from-env@1.0.0: resolution: {integrity: sha512-F2JHgJQ1iqwnHDcQjVBsq3n/uoaFL+iPW/eAeL7kVxy/2RrWaN4WroKjjvbsoRtv0ftelNyC01bjRhn/bhcf4A==} @@ -7694,6 +7869,10 @@ packages: resolution: {integrity: sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==} engines: {node: '>=0.6'} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} + engines: {node: '>=0.6'} + querystringify@2.2.0: resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} @@ -7718,10 +7897,18 @@ packages: resolution: {integrity: sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==} engines: {node: '>=0.12'} + range-parser@1.3.0: + resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} + engines: {node: '>= 0.6'} + raw-body@2.5.3: resolution: {integrity: sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==} engines: {node: '>= 0.8'} + raw-body@3.0.2: + resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} + engines: {node: '>= 0.10'} + rc-cascader@3.34.0: resolution: {integrity: sha512-KpXypcvju9ptjW9FaN2NFcA2QH9E9LHKq169Y0eWtH4e/wHQ5Wh5qZakAgvb8EKZ736WZ3B0zLLOBsrsja5Dag==} peerDependencies: @@ -8256,6 +8443,10 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + router@2.3.0: + resolution: {integrity: sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==} + engines: {node: '>= 18'} + run-async@2.4.1: resolution: {integrity: sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==} engines: {node: '>=0.12.0'} @@ -8351,9 +8542,17 @@ packages: engines: {node: '>=10'} hasBin: true + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + sentence-case@3.0.4: resolution: {integrity: sha512-8LS0JInaQMCRoQ7YUytAo/xUu5W2XnQxV2HI/6uM6U7CITS1RqPElr30V6uIqyMKM9lJGRVFy5/4CuzcixNYSg==} + serve-static@2.2.1: + resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} + engines: {node: '>= 18'} + set-blocking@2.0.0: resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} @@ -8411,6 +8610,10 @@ packages: resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} engines: {node: '>= 0.4'} + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -8613,6 +8816,10 @@ packages: streamx@2.25.0: resolution: {integrity: sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==} + string-argv@0.3.2: + resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} + engines: {node: '>=0.6.19'} + string-convert@0.2.1: resolution: {integrity: sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==} @@ -8693,6 +8900,15 @@ packages: resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==} engines: {node: '>=14.16'} + stripe@23.2.0: + resolution: {integrity: sha512-0W0J4yA9qFO2rnF61v8Y62OiO2SmAR+Cv04VJaFUMpCxiq8lG5bxEYbeSMSpMDR9ofFZGd+Z/iUIgSFbOolmUw==} + engines: {node: '>=20'} + peerDependencies: + '@types/node': '>=20' + peerDependenciesMeta: + '@types/node': + optional: true + strnum@2.2.3: resolution: {integrity: sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg==} @@ -8826,6 +9042,10 @@ packages: tiny-warning@1.0.3: resolution: {integrity: sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==} + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + tinyglobby@0.2.16: resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} engines: {node: '>=12.0.0'} @@ -9010,6 +9230,10 @@ packages: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} + type-is@2.1.0: + resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} + engines: {node: '>= 18'} + typed-array-buffer@1.0.3: resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} engines: {node: '>= 0.4'} @@ -9191,6 +9415,10 @@ packages: resolution: {integrity: sha512-Z6Uz+TYwEqE7ZN50gwn+1LCVo9ZVrpxRPOhOLnncYkY1ZzOYtrX8Fwf/rFktZ8R5mJms6EZf5TqNOMeZmnPq9Q==} engines: {node: '>=12'} + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + verror@1.10.0: resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==} engines: {'0': node >=0.6.0} @@ -9392,6 +9620,11 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yargs-parser@18.1.3: resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} engines: {node: '>=6'} @@ -9435,6 +9668,14 @@ packages: resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==} engines: {node: '>=18'} + zod-to-json-schema@3.25.2: + resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} + peerDependencies: + zod: ^3.25.28 || ^4 + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + snapshots: '@0no-co/graphql.web@1.2.0(graphql@15.10.2)': @@ -10718,18 +10959,6 @@ snapshots: '@graphile-contrib/pg-simplify-inflector@6.1.0': {} - '@graphile/lds@4.14.1(bufferutil@4.1.0)(utf-8-validate@5.0.10)': - dependencies: - '@types/pg': 8.20.0 - '@types/ws': 6.0.4 - pg: 8.20.0 - tslib: 2.8.1 - ws: 7.5.10(bufferutil@4.1.0)(utf-8-validate@5.0.10) - transitivePeerDependencies: - - bufferutil - - pg-native - - utf-8-validate - '@graphile/logger@0.2.0': {} '@graphile/lru@4.11.0': @@ -10753,18 +10982,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@graphile/subscriptions-lds@4.14.1(bufferutil@4.1.0)(postgraphile-core@4.14.1(graphql@15.10.2)(pg@8.20.0))(utf-8-validate@5.0.10)': - dependencies: - '@graphile/lds': 4.14.1(bufferutil@4.1.0)(utf-8-validate@5.0.10) - '@types/ws': 6.0.4 - postgraphile-core: 4.14.1(graphql@15.10.2)(pg@8.20.0) - tslib: 2.8.1 - ws: 7.5.10(bufferutil@4.1.0)(utf-8-validate@5.0.10) - transitivePeerDependencies: - - bufferutil - - pg-native - - utf-8-validate - '@graphql-codegen/add@5.0.3(graphql@15.10.2)': dependencies: '@graphql-codegen/plugin-helpers': 5.1.1(graphql@15.10.2) @@ -11504,6 +11721,10 @@ snapshots: dependencies: react: 18.2.0 + '@hono/node-server@2.1.11(hono@4.13.19)': + dependencies: + hono: 4.13.19 + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -11879,6 +12100,28 @@ snapshots: '@lukeed/ms@2.0.2': {} + '@modelcontextprotocol/sdk@1.32.2(zod@4.6.7)': + dependencies: + '@hono/node-server': 2.1.11(hono@4.13.19) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.1 + express: 5.3.0 + express-rate-limit: 8.7.5(express@5.3.0) + hono: 4.13.19 + jose: 6.2.8 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.6.7 + zod-to-json-schema: 3.25.2(zod@4.6.7) + transitivePeerDependencies: + - supports-color + '@next/bundle-analyzer@16.2.4(bufferutil@4.1.0)(utf-8-validate@5.0.10)': dependencies: webpack-bundle-analyzer: 4.10.1(bufferutil@4.1.0)(utf-8-validate@5.0.10) @@ -12366,7 +12609,7 @@ snapshots: dependencies: '@types/estree': 1.0.8 estree-walker: 2.0.2 - picomatch: 4.0.4 + picomatch: 4.0.7 optionalDependencies: rollup: 4.60.2 @@ -12742,6 +12985,8 @@ snapshots: '@types/node': 18.19.130 '@types/responselike': 1.0.3 + '@types/canvas-confetti@1.9.0': {} + '@types/connect@3.4.38': dependencies: '@types/node': 18.19.130 @@ -12974,10 +13219,6 @@ snapshots: dependencies: '@types/node': 18.19.130 - '@types/ws@6.0.4': - dependencies: - '@types/node': 18.19.130 - '@types/ws@7.4.7': dependencies: '@types/node': 18.19.130 @@ -13297,6 +13538,11 @@ snapshots: abstract-logging@2.0.1: {} + accepts@2.0.0: + dependencies: + mime-types: 3.0.2 + negotiator: 1.1.0 + acorn-import-attributes@1.9.5(acorn@8.16.0): dependencies: acorn: 8.16.0 @@ -13809,6 +14055,20 @@ snapshots: transitivePeerDependencies: - supports-color + body-parser@2.4.0: + dependencies: + bytes: 3.1.2 + content-type: 2.1.0 + debug: 4.4.3(supports-color@8.1.1) + http-errors: 2.0.1 + iconv-lite: 0.7.3 + on-finished: 2.4.1 + qs: 6.17.1 + raw-body: 3.0.2 + type-is: 2.1.0 + transitivePeerDependencies: + - supports-color + boolbase@1.0.0: {} boxen@7.1.1: @@ -13991,6 +14251,8 @@ snapshots: caniuse-lite@1.0.30001791: {} + canvas-confetti@1.9.4: {} + capital-case@1.0.4: dependencies: no-case: 3.0.4 @@ -14254,16 +14516,24 @@ snapshots: dependencies: safe-buffer: 5.2.1 + content-disposition@2.0.1: {} + content-type@1.0.5: {} + content-type@2.1.0: {} + convert-source-map@1.9.0: {} convert-source-map@2.0.0: {} + cookie-signature@1.2.2: {} + cookie@0.4.2: {} cookie@0.5.0: {} + cookie@0.7.2: {} + cookie@1.1.1: {} copy-to-clipboard@3.3.3: @@ -14278,6 +14548,11 @@ snapshots: core-util-is@1.0.2: {} + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + cosmiconfig@7.1.0: dependencies: '@types/parse-json': 4.0.2 @@ -14334,6 +14609,10 @@ snapshots: create-require@1.1.1: {} + cross-env@7.0.3: + dependencies: + cross-spawn: 7.0.6 + cross-fetch@3.2.0(encoding@0.1.13): dependencies: node-fetch: 2.7.0(encoding@0.1.13) @@ -15056,6 +15335,8 @@ snapshots: esutils@2.0.3: {} + etag@1.8.1: {} + eventemitter2@6.4.7: {} eventemitter3@3.1.2: {} @@ -15068,6 +15349,12 @@ snapshots: events@3.3.0: {} + eventsource-parser@3.1.1: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.1 + execa@4.1.0: dependencies: cross-spawn: 7.0.6 @@ -15114,6 +15401,47 @@ snapshots: exponential-backoff@3.1.3: {} + express-rate-limit@8.7.5(express@5.3.0): + dependencies: + debug: 4.4.3(supports-color@8.1.1) + express: 5.3.0 + ip-address: 10.2.0 + transitivePeerDependencies: + - supports-color + + express@5.3.0: + dependencies: + accepts: 2.0.0 + body-parser: 2.4.0 + content-disposition: 2.0.1 + content-type: 2.1.0 + cookie: 0.7.2 + cookie-signature: 1.2.2 + debug: 4.4.3(supports-color@8.1.1) + depd: 2.0.0 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + finalhandler: 2.1.1 + fresh: 2.0.0 + http-errors: 2.0.1 + merge-descriptors: 2.0.0 + mime-types: 3.0.2 + on-finished: 2.4.1 + once: 1.4.0 + parseurl: 1.3.3 + proxy-addr: 2.0.8 + qs: 6.17.1 + range-parser: 1.3.0 + router: 2.3.0 + send: 1.2.1 + serve-static: 2.2.1 + statuses: 2.0.2 + type-is: 2.1.0 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + extend@3.0.2: {} extract-files@11.0.0: {} @@ -15220,6 +15548,10 @@ snapshots: optionalDependencies: picomatch: 4.0.4 + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + fetch-blob@3.2.0: dependencies: node-domexception: 1.0.0 @@ -15251,6 +15583,17 @@ snapshots: transitivePeerDependencies: - supports-color + finalhandler@2.1.1: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + encodeurl: 2.0.0 + escape-html: 1.0.3 + on-finished: 2.4.1 + parseurl: 1.3.3 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + find-cache-dir@4.0.0: dependencies: common-path-prefix: 3.0.0 @@ -15318,8 +15661,12 @@ snapshots: forwarded-parse@2.1.2: {} + forwarded@0.2.0: {} + fp-and-or@0.1.4: {} + fresh@2.0.0: {} + fs-capacitor@6.2.0: {} fs-capacitor@8.0.0: {} @@ -15804,6 +16151,8 @@ snapshots: dependencies: parse-passwd: 1.0.0 + hono@4.13.19: {} + hosted-git-info@4.1.0: dependencies: lru-cache: 6.0.0 @@ -15943,6 +16292,8 @@ snapshots: dependencies: ms: 2.1.3 + husky@9.1.7: {} + iconv-lite@0.4.24: dependencies: safer-buffer: 2.1.2 @@ -15956,6 +16307,10 @@ snapshots: dependencies: safer-buffer: 2.1.2 + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + ieee754@1.2.1: {} ignore-by-default@1.0.1: {} @@ -16086,6 +16441,8 @@ snapshots: ip-address@10.2.0: {} + ipaddr.js@1.9.1: {} + ipaddr.js@2.3.0: {} is-absolute@1.0.0: @@ -16211,6 +16568,8 @@ snapshots: is-plain-object@5.0.0: {} + is-promise@4.0.0: {} + is-reference@1.2.1: dependencies: '@types/estree': 1.0.8 @@ -16817,6 +17176,8 @@ snapshots: json-schema-traverse@1.0.0: {} + json-schema-typed@8.0.2: {} + json-schema@0.4.0: {} json-sort-cli@2.1.11: @@ -16949,6 +17310,14 @@ snapshots: lines-and-columns@1.2.4: {} + lint-staged@17.6.0: + dependencies: + picomatch: 4.0.7 + string-argv: 0.3.2 + tinyexec: 1.3.1 + optionalDependencies: + yaml: 2.9.1 + listr2@3.14.0(enquirer@2.4.1): dependencies: cli-truncate: 2.1.0 @@ -17136,6 +17505,8 @@ snapshots: media-typer@0.3.0: {} + media-typer@1.1.1: {} + mensch@0.3.4: {} meow@11.0.0: @@ -17153,6 +17524,8 @@ snapshots: type-fest: 3.13.1 yargs-parser: 21.1.1 + merge-descriptors@2.0.0: {} + merge-stream@2.0.0: {} merge2@1.4.1: {} @@ -17174,6 +17547,10 @@ snapshots: dependencies: mime-db: 1.52.0 + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + mime@2.6.0: {} mime@3.0.0: {} @@ -17611,6 +17988,10 @@ snapshots: negotiator@0.6.4: {} + negotiator@1.1.0: + dependencies: + content-type: 2.1.0 + neo-async@2.6.2: {} net@1.0.2: {} @@ -18135,6 +18516,8 @@ snapshots: lru-cache: 11.3.5 minipass: 7.1.3 + path-to-regexp@8.4.2: {} + path-type@4.0.0: {} pend@1.2.0: {} @@ -18194,6 +18577,8 @@ snapshots: picomatch@4.0.4: {} + picomatch@4.0.7: {} + pify@2.3.0: {} pinkie-promise@2.0.1: @@ -18224,6 +18609,8 @@ snapshots: pirates@4.0.7: {} + pkce-challenge@5.0.1: {} + pkg-dir@4.2.0: dependencies: find-up: 4.1.0 @@ -18379,6 +18766,11 @@ snapshots: proto-list@1.2.4: {} + proxy-addr@2.0.8: + dependencies: + forwarded: 0.2.0 + ipaddr.js: 1.9.1 + proxy-from-env@1.0.0: {} proxy-from-env@1.1.0: {} @@ -18420,6 +18812,11 @@ snapshots: dependencies: side-channel: 1.1.0 + qs@6.17.1: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + querystringify@2.2.0: {} queue-microtask@1.2.3: {} @@ -18437,6 +18834,8 @@ snapshots: discontinuous-range: 1.0.0 ret: 0.1.15 + range-parser@1.3.0: {} + raw-body@2.5.3: dependencies: bytes: 3.1.2 @@ -18444,6 +18843,13 @@ snapshots: iconv-lite: 0.4.24 unpipe: 1.0.0 + raw-body@3.0.2: + dependencies: + bytes: 3.1.2 + http-errors: 2.0.1 + iconv-lite: 0.7.2 + unpipe: 1.0.0 + rc-cascader@3.34.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0): dependencies: '@babel/runtime': 7.29.2 @@ -19113,6 +19519,16 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.2 fsevents: 2.3.3 + router@2.3.0: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + depd: 2.0.0 + is-promise: 4.0.0 + parseurl: 1.3.3 + path-to-regexp: 8.4.2 + transitivePeerDependencies: + - supports-color + run-async@2.4.1: {} run-async@3.0.0: {} @@ -19210,12 +19626,37 @@ snapshots: semver@7.7.4: {} + send@1.2.1: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.1 + range-parser: 1.3.0 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + sentence-case@3.0.4: dependencies: no-case: 3.0.4 tslib: 2.8.1 upper-case-first: 2.0.2 + serve-static@2.2.1: + dependencies: + encodeurl: 2.0.0 + escape-html: 1.0.3 + parseurl: 1.3.3 + send: 1.2.1 + transitivePeerDependencies: + - supports-color + set-blocking@2.0.0: {} set-cookie-parser@2.7.2: {} @@ -19323,6 +19764,14 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + signal-exit@3.0.7: {} signal-exit@4.1.0: {} @@ -19558,6 +20007,8 @@ snapshots: - bare-abort-controller - react-native-b4a + string-argv@0.3.2: {} + string-convert@0.2.1: {} string-env-interpolation@1.0.1: {} @@ -19655,6 +20106,10 @@ snapshots: strip-json-comments@5.0.3: {} + stripe@23.2.0(@types/node@18.19.130): + optionalDependencies: + '@types/node': 18.19.130 + strnum@2.2.3: {} styled-jsx@5.1.6(@babel/core@7.29.0)(babel-plugin-macros@3.1.0)(react@18.2.0): @@ -19793,10 +20248,12 @@ snapshots: tiny-warning@1.0.3: {} + tinyexec@1.3.1: {} + tinyglobby@0.2.16: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 title-case@3.0.3: dependencies: @@ -19957,6 +20414,12 @@ snapshots: media-typer: 0.3.0 mime-types: 2.1.35 + type-is@2.1.0: + dependencies: + content-type: 2.1.0 + media-typer: 1.1.1 + mime-types: 3.0.2 + typed-array-buffer@1.0.3: dependencies: call-bound: 1.0.4 @@ -20143,6 +20606,8 @@ snapshots: value-or-promise@1.0.12: {} + vary@1.1.2: {} + verror@1.10.0: dependencies: assert-plus: 1.0.0 @@ -20382,6 +20847,9 @@ snapshots: yaml@2.8.4: {} + yaml@2.9.1: + optional: true + yargs-parser@18.1.3: dependencies: camelcase: 5.3.1 @@ -20437,3 +20905,9 @@ snapshots: yocto-queue@1.2.2: {} yoctocolors-cjs@2.1.3: {} + + zod-to-json-schema@3.25.2(zod@4.6.7): + dependencies: + zod: 4.6.7 + + zod@4.6.7: {} diff --git a/scripts/_setup_utils.mjs b/scripts/_setup_utils.mjs index 9e56b4acd..e9ab288f0 100644 --- a/scripts/_setup_utils.mjs +++ b/scripts/_setup_utils.mjs @@ -1,17 +1,17 @@ import { promises as fsp } from "fs" import { platform } from "os" -import { URL } from "url" +import { fileURLToPath, URL } from "url" -import { safeRandomHexString,safeRandomString } from "./lib/random.mjs" +import { safeRandomHexString, safeRandomString } from "./lib/random.mjs" if (parseInt(process.version.slice(1).split(".")[0], 10) < 20) { throw new Error("This project requires Node.js >= 20.0.0") } -export { readDotenv,withDotenvUpdater } from "./lib/dotenv.mjs" +export { readDotenv, withDotenvUpdater } from "./lib/dotenv.mjs" export { runSync } from "./lib/run.mjs" export function dirname(meta) { - return new URL(".", meta.url).pathname + return fileURLToPath(new URL(".", meta.url)) } const __dirname = dirname(import.meta) @@ -137,6 +137,32 @@ export function updateDotenv(add, answers) { # Client secret from the Keycloak admin console:` ) + add( + "STRIPE_SECRET_KEY", + null, + `\ +# Stripe payments. Leave these blank to keep payments unavailable. With both +# secrets set, developers switch payments on and off with the \`payments\` +# feature flag; without them the flag cannot be switched on. +# +# Webhook endpoint: ${rootUrl}/api/stripe/webhook +# Events to send: checkout.session.completed, +# checkout.session.expired +# +# Use test-mode keys (sk_test_...) outside production. Locally, run +# \`stripe listen --events checkout.session.completed,checkout.session.expired --forward-to ${rootUrl}/api/stripe/webhook\` +# and use the whsec_... secret it prints. Step by step: docs/payments.md +# +# Stripe secret API key (sk_test_... or sk_live_...):` + ) + + add( + "STRIPE_WEBHOOK_SECRET", + null, + `\ +# Signing secret of the webhook endpoint above (whsec_...):` + ) + add( "GRAPHILE_TURBO", "1", @@ -145,10 +171,27 @@ export function updateDotenv(add, answers) { ) add( - "LD_TABLE_PATTERN", - "app_public.*", + "DATABASE_POOL_MAX_ROOT", + "2", + `\ +# Postgres connection budget. The server's owner pool (DATABASE_POOL_MAX_ROOT), +# its PostGraphile pool (DATABASE_POOL_MAX_AUTH, one connection of which is held +# for LISTEN) and the worker (WORKER_POOL_MAX) together must fit in the +# connections the database server has free. A request that cannot get a +# connection within DATABASE_POOL_ACQUIRE_TIMEOUT_MS fails.` + ) + + add("DATABASE_POOL_MAX_AUTH", "5") + + add("DATABASE_POOL_ACQUIRE_TIMEOUT_MS", "5000") + + add( + "WORKER_POOL_MAX", + "2", `\ -# Allows us to ignore changes in tables you don't care about. Used in conjunction with @graphile/subscriptions-lds` +# The worker's start scripts expand WORKER_POOL_MAX in the shell before this +# file is loaded, so it takes effect only when set in the process environment +# (for example through the env_file of the worker's docker compose service).` ) add( diff --git a/scripts/check-migrations.mjs b/scripts/check-migrations.mjs new file mode 100755 index 000000000..7f0bb747e --- /dev/null +++ b/scripts/check-migrations.mjs @@ -0,0 +1,85 @@ +#!/usr/bin/env node +// Guards against the two migration mistakes that make parallel pull requests +// collide. Uses only Node built-ins so CI can run it without installing. +// +// node scripts/check-migrations.mjs current +// Fails when two files in @app/db/migrations/current/ share a numeric +// prefix, or when a file there has no numeric prefix. +// +// node scripts/check-migrations.mjs committed +// Fails when the changes since the merge base with touch +// @app/db/migrations/committed/. +import { execFileSync } from "child_process" +import { readdirSync } from "fs" +import path from "path" +import { fileURLToPath } from "url" + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + ".." +) +const CURRENT_DIR = "@app/db/migrations/current" +const COMMITTED_DIR = "@app/db/migrations/committed" + +// Mirrors how graphile-migrate reads current/: dotfiles and non-SQL files are +// ignored, and the prefix is compared as a number, so 1-a.sql and 01-b.sql clash. +function checkCurrent() { + const files = readdirSync(path.join(repoRoot, CURRENT_DIR)) + .filter((file) => !file.startsWith(".") && file.endsWith(".sql")) + .sort() + const byPrefix = new Map() + const errors = [] + for (const file of files) { + const match = /^(\d+)(-[-_a-zA-Z0-9]*)?\.sql$/.exec(file) + const prefix = match ? parseInt(match[1], 10) : 0 + if (prefix < 1) { + errors.push( + `${CURRENT_DIR}/${file}: name must be NN-.sql with a positive number NN` + ) + continue + } + byPrefix.set(prefix, [...(byPrefix.get(prefix) ?? []), file]) + } + for (const [prefix, clashing] of byPrefix) { + if (clashing.length > 1) { + errors.push( + `${CURRENT_DIR}: ${clashing.join(", ")} share the prefix ${prefix}; renumber one of them` + ) + } + } + if (errors.length > 0) { + errors.forEach((error) => console.error(`::error::${error}`)) + process.exit(1) + } + console.log(`${CURRENT_DIR}: ${files.length} file(s), prefixes are unique`) +} + +function checkCommitted(baseRef) { + if (!baseRef) { + console.error("Usage: check-migrations.mjs committed ") + process.exit(2) + } + const changed = execFileSync( + "git", + ["diff", "--name-status", `${baseRef}...HEAD`, "--", COMMITTED_DIR], + { cwd: repoRoot, encoding: "utf8" } + ).trim() + if (changed) { + console.error( + `::error::This pull request changes committed migrations. Put work in progress in ${CURRENT_DIR}/NN-.sql instead; maintainers commit migrations (see CONTRIBUTING.md).` + ) + console.error(changed) + process.exit(1) + } + console.log(`${COMMITTED_DIR}: unchanged since ${baseRef}`) +} + +const [command, ...args] = process.argv.slice(2) +if (command === "current") { + checkCurrent() +} else if (command === "committed") { + checkCommitted(args[0]) +} else { + console.error("Usage: check-migrations.mjs current | committed ") + process.exit(2) +} diff --git a/scripts/lib/run.mjs b/scripts/lib/run.mjs index 8a1a0bab3..fb1bab057 100644 --- a/scripts/lib/run.mjs +++ b/scripts/lib/run.mjs @@ -4,6 +4,7 @@ export const runSync = (cmd, args, options = {}) => { const result = spawnSync(cmd, args, { stdio: ["inherit", "inherit", "inherit"], windowsHide: true, + shell: process.platform === "win32", ...options, env: { ...process.env, diff --git a/scripts/setup_env.mjs b/scripts/setup_env.mjs index d3b642dc4..288e5276d 100644 --- a/scripts/setup_env.mjs +++ b/scripts/setup_env.mjs @@ -16,6 +16,7 @@ runMain(async () => { await checkGit() const config = (await readDotenv()) || {} const mergeAnswers = (cb) => (answers) => cb({ ...config, ...answers }) + const askStripe = !("STRIPE_SECRET_KEY" in config) && !!process.stdin.isTTY const questions = [ { type: "input", @@ -59,8 +60,45 @@ runMain(async () => { default: "redis://127.0.0.1:6379", when: !("REDIS_URL" in config), }, + // Stripe payments are optional. Asked only once (when .env has no + // STRIPE_SECRET_KEY line yet) and only in an interactive terminal, so CI + // and re-runs never stop here. See docs/payments.md. + { + type: "confirm", + name: "SETUP_STRIPE_PAYMENTS", + message: + "Enable Stripe payments with your own Stripe test-mode keys? (optional, see docs/payments.md; you can add them to .env later)", + default: false, + when: askStripe, + }, + { + type: "password", + mask: "*", + name: "STRIPE_SECRET_KEY", + message: + "Stripe secret key (sk_test_..., from https://dashboard.stripe.com/test/apikeys; leave empty to skip):", + validate: (key) => + !key || /^(sk|rk)_test_\S+$/.test(key) + ? true + : "Use a test-mode key starting with sk_test_ (or rk_test_)", + when: (answers) => askStripe && answers.SETUP_STRIPE_PAYMENTS, + }, + { + type: "password", + mask: "*", + name: "STRIPE_WEBHOOK_SECRET", + message: + "Stripe webhook signing secret (whsec_..., printed by `stripe listen`; leave empty to skip):", + validate: (secret) => + !secret || /^whsec_\S+$/.test(secret) + ? true + : "The signing secret starts with whsec_", + when: (answers) => askStripe && answers.SETUP_STRIPE_PAYMENTS, + }, ] const answers = await inquirer.prompt(questions) + // Only decides whether the Stripe questions are asked; not an env var + delete answers.SETUP_STRIPE_PAYMENTS await withDotenvUpdater(answers, (add) => updateDotenv(add, { diff --git a/scripts/telegram-webhook.mjs b/scripts/telegram-webhook.mjs new file mode 100644 index 000000000..b745c01c7 --- /dev/null +++ b/scripts/telegram-webhook.mjs @@ -0,0 +1,32 @@ +// Run with: node -r @app/config/env.js scripts/telegram-webhook.mjs [set|status|delete] +import telegram from "../@app/lib/dist/cjs/telegram.js" + +try { + const action = process.argv[2] || "status" + if (action === "set") { + const root = new URL(process.env.ROOT_URL) + if (root.protocol !== "https:") + throw new Error("Webhook mode requires an HTTPS ROOT_URL") + const secret = process.env.TELEGRAM_WEBHOOK_SECRET + if (!secret || !/^[A-Za-z0-9_-]{1,256}$/.test(secret)) + throw new Error("Configure a valid TELEGRAM_WEBHOOK_SECRET first") + await telegram.telegramRequest("setWebhook", { + url: new URL("/telegram/webhook", root).href, + secret_token: secret, + allowed_updates: ["message", "my_chat_member", "callback_query"], + }) + console.log("Telegram webhook configured") + } else if (action === "delete") { + await telegram.telegramRequest("deleteWebhook", {}) + console.log("Telegram webhook removed; polling may now be started") + } else if (action === "status") { + const info = await telegram.telegramRequest("getWebhookInfo", {}) + console.log( + info.url ? "Telegram webhook is active" : "No Telegram webhook configured" + ) + console.log("Pending updates:", info.pending_update_count) + } else throw new Error("Usage: telegram-webhook.mjs [set|status|delete]") +} catch (error) { + console.error(error.message) + process.exitCode = 1 +} diff --git a/scripts/test.mjs b/scripts/test.mjs index e0a274718..af58b7fdb 100755 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -3,6 +3,7 @@ import { execSync, spawnSync as rawSpawnSync } from "child_process" import concurrently from "concurrently" +import pg from "pg" import "@app/config/env.js" @@ -58,6 +59,32 @@ process.env.NODE_ENV = "test" // Don't log graphile-worker job successes in tests process.env.NO_LOG_SUCCESS = true +// Every feature flag is off by default, which is what CI runs. As a local, +// on-demand option, TEST_FEATURE_FLAGS=on switches every flag on and available +// after the test database is rebuilt; test cleanup resets the flags to the +// same baseline, see resetFeatureFlags in @app/__tests__/helpers.ts. +const featureFlagBaseline = process.env.TEST_FEATURE_FLAGS || "off" +if (!["off", "on"].includes(featureFlagBaseline)) { + throw new Error( + `TEST_FEATURE_FLAGS must be "off" or "on", not "${featureFlagBaseline}"` + ) +} + +async function switchAllFeatureFlagsOn() { + const client = new pg.Client({ + connectionString: process.env.TEST_DATABASE_URL, + }) + await client.connect() + try { + const { rowCount } = await client.query( + "update app_public.feature_flags set state = 'on', available = true" + ) + console.log(`TEST_FEATURE_FLAGS=on: switched ${rowCount} flag(s) on`) + } finally { + await client.end() + } +} + const cmdArgs = process.argv.slice(2) const watchMode = cmdArgs.find( (arg) => arg === "--watch" || arg === "--watchAll" @@ -69,12 +96,19 @@ if (delayArg > -1) { if (isNaN(delaySeconds)) { throw new Error("Did not get a valid delay argument in seconds.") } - setTimeout(main, delaySeconds * 1000) + setTimeout(runMain, delaySeconds * 1000) } else { - main() + runMain() +} + +function runMain() { + main().catch((e) => { + console.error(e) + process.exit(1) + }) } -function main() { +async function main() { const opts = { stdio: "inherit", cwd: process.cwd(), @@ -83,6 +117,9 @@ function main() { // Reset the test database execSync("pnpm --filter @app/db run gm reset --shadow --erase", opts) execSync("pnpm --filter @app/db run watch --once --shadow", opts) + if (featureFlagBaseline === "on") { + await switchAllFeatureFlagsOn() + } if (watchMode) { // We're in watch mode, so keep watching the `current.sql` file @@ -104,8 +141,26 @@ function main() { } ) } else { - // Run once, so just run the tests - const argsWithoutDelayArg = cmdArgs.filter((arg) => arg !== "--delay") - spawnSync("jest", ["-i", ...argsWithoutDelayArg], opts) + // Run once, so just run the tests. The tests share one database and + // must run one file at a time. Jest's in-band mode (-i, --runInBand) + // keeps every file in this one process, whose heap grows with each file + // until Node runs out of memory, so run the files in a single worker + // instead: jest restarts it when it passes workerIdleMemoryLimit + // (jest.config.ts). Both flags are accepted and mean the same here. The + // worker's heap limit is raised above that threshold so that the file + // which crosses it can still finish. + const jestArgs = cmdArgs.filter( + (arg) => arg !== "--delay" && arg !== "-i" && arg !== "--runInBand" + ) + spawnSync("jest", ["--maxWorkers=1", ...jestArgs], { + ...opts, + env: { + ...process.env, + npm_config_loglevel: "silent", + NODE_OPTIONS: [process.env.NODE_OPTIONS, "--max-old-space-size=4096"] + .filter(Boolean) + .join(" "), + }, + }) } } diff --git a/stress/.env.stress b/stress/.env.stress new file mode 100644 index 000000000..401b91fb6 --- /dev/null +++ b/stress/.env.stress @@ -0,0 +1,33 @@ +# Environment for the stress stack. Mirrors the production env template in +# infra-prodeko (ansible/roles/ilmo/templates/env.production.j2) minus +# external integrations (SendGrid, Azure storage/translate, Keycloak, OAuth). +NODE_ENV=production +TZ=Europe/Helsinki +ROOT_URL=http://localhost:5678 +PORT=5678 +GRAPHILE_TURBO=1 +NEXT_TRANSLATE_PATH=../client +DATABASE_HOST=db +DATABASE_NAME=ilmo +DATABASE_OWNER=ilmo +DATABASE_OWNER_PASSWORD=stress +DATABASE_AUTHENTICATOR=ilmo_authenticator +DATABASE_AUTHENTICATOR_PASSWORD=stress +DATABASE_VISITOR=ilmo_visitor +DATABASE_URL=postgres://ilmo:stress@db/ilmo +AUTH_DATABASE_URL=postgres://ilmo_authenticator:stress@db/ilmo +ROOT_DATABASE_URL=postgres://postgres:postgres@db/template1 +SHADOW_DATABASE_URL=postgres://ilmo:stress@db/ilmo_shadow +REDIS_URL=redis://redis:6379 +SECRET=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +JWT_SECRET=stress-jwt-secret-stress-jwt-secret +PRIVACY_URL=http://localhost:5678/privacy +DATABASE_POOL_MAX_ROOT=2 +DATABASE_POOL_MAX_AUTH=5 +DATABASE_POOL_ACQUIRE_TIMEOUT_MS=5000 +WORKER_POOL_MAX=2 +AZURE_DB_OWNER=ilmo +# Required at startup; never called by the registration flow. +AZURE_TRANSLATE_API_URL=http://localhost:9/translate +AZURE_TRANSLATE_SUBSCRIPTION_KEY=stress +AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=http;AccountName=stress;AccountKey=c3RyZXNz;BlobEndpoint=http://localhost:9/stress; diff --git a/stress/.gitignore b/stress/.gitignore new file mode 100644 index 000000000..7acfe2b85 --- /dev/null +++ b/stress/.gitignore @@ -0,0 +1,2 @@ +results/ +.cache/ diff --git a/stress/README.md b/stress/README.md new file mode 100644 index 000000000..a28a12d97 --- /dev/null +++ b/stress/README.md @@ -0,0 +1,83 @@ +# Registration stress test + +This simulates a contested registration opening against a production build of +ilmo. It runs under production-like limits: + +- **Postgres:** `wal_level=replica`, with 10 connection slots for the ilmo roles + (`max_connections=13`, `superuser_reserved_connections=3`). +- **Database owner:** not a superuser, so it can't use the reserved slots. +- **Server:** pinned to two cores with `taskset`. + +## Running + +Build an image of the source tree you want to test, then run a scenario: + +```bash +stress/build-image.sh . ilmo-stress:latest +pnpm stress worst +``` + +| Scenario | Bots | Quotas | +| -------- | ---- | ------------ | +| `worst` | 400 | 5 × 5 spots | +| `common` | 200 | 3 × 20 spots | + +`--image ` picks the image (default `ilmo-stress:latest`) and `--vus ` +overrides the bot count. Use `--vus 5` for a quick smoke test. + +To compare against another commit, export it first: + +```bash +mkdir -p /tmp/ilmo- && git archive | tar -x -C /tmp/ilmo- +stress/build-image.sh /tmp/ilmo- ilmo-stress: +``` + +`build-image.sh` builds the app's own Dockerfile. It feeds sharp's native +binaries in from `stress/.cache` because the GitHub download times out on slow +links. + +## What a bot does + +Each bot does the following: + +1. Loads the event page some time before opening. +2. Holds the page's websocket subscriptions (`EventPage`, `CurrentTime`). +3. At opening, plus 0–1 s, runs the register page's query, subscribes to + `EventRegistrations` and claims a registration token. +4. Waits 5–20 s, then submits the form. + +10% of bots share one client IP, like a guild room, and the rest each get their +own. + +## Results + +Each run writes to `stress/results/