Compare commits

31 Commits
ezpz ... master

Author SHA1 Message Date
d3a4554b0d fix: links 2026-04-06 18:05:29 +02:00
71b85d6874 chore: fmt 2026-04-01 14:42:24 +02:00
7b3d5461ef feat: kamp page 2026-04-01 14:18:07 +02:00
56942275b8 feat: add homepage selector 2026-03-29 16:28:12 +02:00
845624dfd3 feat(admin): improve export to put guests in their own row 2026-03-19 10:31:12 +01:00
ee0e9e68a9 feat(admin): add birthdate & postcode 2026-03-19 10:28:07 +01:00
f113770348 feat(registration): add birthdate & postcode 2026-03-19 10:15:45 +01:00
19d784b2e5 feat(drinkkaart): implement QR scan and balance deduction interface
Convert /drinkkaart route from a redirect to a full admin scanning interface.
Add flow: scan QR → resolve user → select amount → confirm deduction → success.
Refactor QrScanner to use Html5Qrcode API for better control and cleanup.
Update event date/time to April 24, 2026 at 19:30.

BREAKING CHANGE: /drinkkaart now requires admin role and provides scanner UI
instead of redirecting to /account.
2026-03-15 14:47:36 +01:00
0d99f7c5f5 feat(registration): add watcher capacity limits and update pricing
Add 70-person capacity limit for watchers with real-time availability checks.
Update drink card pricing to €5 per person (was €5 base + €2 per guest).
Add feature flag to bypass registration countdown.
Show under-review notice for performer registrations.
Update FAQ performance duration from 5-7 to 5 minutes.
2026-03-14 19:37:52 +01:00
3a2e403ee9 Update event date to 24 april, add venue, add Ichtus Antwerpen as co-sponsor
- Change event date from 18 to 24 april across all pages, hero, meta and constants
- Add venue (Lange Winkelstraat 5, 2000 Antwerpen) to contact page, Q&A, and transactional emails
- Add LOCATION constant to packages/api/src/constants.ts
- Add Ichtus Antwerpen (ichtusantwerpen.com) as co-sponsor in footer and contact page
- Add location info card to confirmation, update, payment reminder and payment confirmation emails
2026-03-11 18:17:40 +01:00
e5d2b13b21 feat(email): route all email sends through Cloudflare Queue
Introduces a CF Queue binding (kk-email-queue) to decouple email
delivery from request handlers, preventing slow responses and
providing automatic retries. All send*Email calls now go through
the queue when the binding is available, with direct-send fallbacks
for local dev. Reminder fan-outs mark DB rows optimistically before
enqueueing to prevent re-enqueue on subsequent cron ticks.
2026-03-11 17:13:35 +01:00
7f431c0091 fix: email 2026-03-11 16:34:51 +01:00
17aa8956a7 feat(log): improve logging for emails 2026-03-11 14:23:39 +01:00
5e5efcaf6f feat: simplify mails and add reminders 2026-03-11 13:39:27 +01:00
0c8e827cda feat: set opening date! 2026-03-11 12:37:01 +01:00
42156209d8 fix(signup): when signing up for the event and already logged in, set the email of the account 2026-03-11 12:29:37 +01:00
569ee4ec40 fix(admin): fix search (or vs and), remove sticky header 2026-03-11 12:03:08 +01:00
29250f8694 fix: resolve biome lint warnings in admin page (useless fragment, non-null assertion) 2026-03-11 11:55:00 +01:00
f214660ab2 feat: redesign admin page with dense ops-tool aesthetic and expandable rows
- Replace generic card layout with near-black background and monospace data display
- Add expandable rows for guest details, notes/questions, and performer details
- Fix duplicate stat cards (artiesten/bezoekers were shown twice)
- Fix gift revenue card showing wrong value (stats.today → totalGiftRevenue)
- Fix mobile card view to use accessible <button> for expandable rows
- Remove unused Users and Card component imports
2026-03-11 11:52:26 +01:00
ba0804db30 fix: performers shouldnt see payment badge 2026-03-11 11:47:54 +01:00
d25f4aa813 feat: show real attendee count with guests in admin, expandable guest details, fix CSV export 2026-03-11 11:37:51 +01:00
8a6d3035cb fix: small issues 2026-03-11 11:29:11 +01:00
0a849bd9c5 fix: Hide payment badge for performers with no payment obligation
Performers have nothing to pay unless they added a voluntary gift.
Only show PaymentBadge when registrationType is 'watcher' or giftAmount
> 0.
2026-03-11 11:27:19 +01:00
17c6315dad Simplify registration flow: mandatory signup redirect, payment emails, payment reminder cron
- EventRegistrationForm/WatcherForm/PerformerForm: remove session/login nudge/SuccessScreen;
  both roles redirect to /login?signup=1&email=<email>&next=/account after submit
- SuccessScreen.tsx deleted (no longer used)
- account.tsx: add 'Betaal nu' CTA via checkoutMutation (shown when watcher + paymentStatus pending)
- DB schema: add paymentReminderSentAt column to registration table
- Migration: 0008_payment_reminder_sent_at.sql
- email.ts: update registrationConfirmationHtml / sendConfirmationEmail with signupUrl param;
  add sendPaymentReminderEmail and sendPaymentConfirmationEmail functions
- routers/index.ts: wire payment reminder into runSendReminders() — queries watchers
  with paymentStatus pending, paymentReminderSentAt IS NULL, createdAt <= now-3days
- mollie.ts webhook: call sendPaymentConfirmationEmail after marking registration paid
2026-03-11 11:17:24 +01:00
e59a588a9d feat: confetti
Closes #5
2026-03-11 10:45:40 +01:00
dfc8ace186 feat: add password reset flow
- Add /forgot-password and /reset-password routes (Dutch UI)
- Wire sendResetPassword into emailAndPassword config (not a plugin)
- Send styled HTML email via nodemailer with 1-hour expiry
- Add 'Wachtwoord vergeten?' link on login page
- Update routeTree.gen.ts with new routes
2026-03-11 09:43:32 +01:00
439bbc5545 feat(web): set test open date 2026-03-11 09:22:01 +01:00
89043c60a3 feat(web): add Cloudflare Worker server entry with scheduled reminders
Sets up the server handler using TanStack React Start and implements
a scheduled event handler to run reminder tasks via Cloudflare cron triggers.
2026-03-10 16:29:56 +01:00
7eabe88d30 feat: reminder email opt-in 1 hour before registration opens 2026-03-10 15:48:41 +01:00
d180a33d6e feat: hoe inschrijven 2026-03-10 14:31:36 +01:00
cf47f25a4d feat: gate registration behind 16 March 2026 19:00 opening date
- Add REGISTRATION_OPENS_AT const in lib/opening.ts as single source of truth
- Add useRegistrationOpen hook with live 1s countdown ticker
- Add CountdownBanner component (DD/HH/MM/SS) with canvas-confetti on open
- EventRegistrationForm shows countdown instead of form while closed
- Login page hides/disables signup while closed; login always available
- WatcherForm AccountModal guards signUp call as defence-in-depth

Closes #2
2026-03-10 13:18:30 +01:00
64 changed files with 6820 additions and 2615 deletions

View File

@@ -30,6 +30,7 @@
"@tanstack/react-start": "^1.141.1",
"@tanstack/router-plugin": "^1.141.1",
"better-auth": "catalog:",
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dotenv": "catalog:",
@@ -51,11 +52,13 @@
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.17.1",
"@tanstack/router-core": "^1.141.1",
"@kk/config": "workspace:*",
"@tanstack/react-query-devtools": "^5.91.1",
"@tanstack/react-router-devtools": "^1.141.1",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0",
"@types/canvas-confetti": "^1.9.0",
"@types/qrcode": "^1.5.6",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@@ -8,11 +8,14 @@ import { Header } from "./Header";
export function SiteHeader() {
const { data: session } = authClient.useSession();
const routerState = useRouterState();
const isHomepage = routerState.location.pathname === "/";
const pathname = routerState.location.pathname;
const isHomepage = pathname === "/";
const isKamp = pathname === "/kamp";
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
if (isKamp) return;
if (!isHomepage) {
setIsVisible(true);
return;
@@ -25,7 +28,9 @@ export function SiteHeader() {
handleScroll();
window.addEventListener("scroll", handleScroll, { passive: true });
return () => window.removeEventListener("scroll", handleScroll);
}, [isHomepage]);
}, [isHomepage, isKamp]);
if (isKamp) return null;
if (!session?.user) {
return <Header isGuest isVisible={isVisible} isHomepage={isHomepage} />;

View File

@@ -5,14 +5,16 @@ import { Input } from "@/components/ui/input";
interface QrScannerProps {
onScan: (token: string) => void;
onCancel: () => void;
/** When true the scanner takes up more vertical space (mobile full-screen mode) */
fullHeight?: boolean;
}
export function QrScanner({ onScan, onCancel }: QrScannerProps) {
const scannerDivId = "qr-reader-container";
export function QrScanner({ onScan, onCancel, fullHeight }: QrScannerProps) {
const videoContainerId = "qr-video-container";
const scannerRef = useRef<unknown>(null);
const [hasError, setHasError] = useState(false);
const [manualToken, setManualToken] = useState("");
// Keep a stable ref to onScan so the effect never re-runs due to identity changes
// Keep a stable ref so the effect never re-runs due to callback identity changes
const onScanRef = useRef(onScan);
useEffect(() => {
onScanRef.current = onScan;
@@ -22,32 +24,34 @@ export function QrScanner({ onScan, onCancel }: QrScannerProps) {
let stopped = false;
import("html5-qrcode")
.then(({ Html5QrcodeScanner }) => {
.then(({ Html5Qrcode }) => {
if (stopped) return;
const scanner = new Html5QrcodeScanner(
scannerDivId,
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
false,
);
const scanner = new Html5Qrcode(videoContainerId);
scannerRef.current = scanner;
scanner.render(
(decodedText: string) => {
scanner.clear().catch(console.error);
onScanRef.current(decodedText);
},
(error: string) => {
// Suppress routine "not found" scan errors
if (!error.includes("No QR code found")) {
console.debug("QR scan error:", error);
scanner
.start(
{ facingMode: "environment" },
{ fps: 15, qrbox: { width: 240, height: 240 } },
(decodedText: string) => {
// Stop immediately so we don't fire multiple times
scanner
.stop()
.catch(console.error)
.finally(() => {
if (!stopped) onScanRef.current(decodedText);
});
},
// Per-frame error (QR not found) — suppress
() => {},
)
.catch((err: unknown) => {
if (!stopped) {
console.error("Camera start failed:", err);
setHasError(true);
}
},
);
});
})
.catch((err) => {
console.error("Failed to load html5-qrcode:", err);
@@ -57,27 +61,40 @@ export function QrScanner({ onScan, onCancel }: QrScannerProps) {
return () => {
stopped = true;
if (scannerRef.current) {
(scannerRef.current as { clear: () => Promise<void> })
.clear()
.catch(console.error);
(
scannerRef.current as {
stop: () => Promise<void>;
clear: () => Promise<void>;
}
)
.stop()
.catch(() => {})
.finally(() => {
(scannerRef.current as { clear: () => Promise<void> })
?.clear?.()
.catch(() => {});
});
}
};
}, []); // empty deps — runs once on mount, cleans up on unmount
}, []); // runs once on mount
const handleManualSubmit = () => {
const token = manualToken.trim();
if (token) {
onScan(token);
}
if (token) onScan(token);
};
const containerHeight = fullHeight ? "h-64 sm:h-80" : "h-52";
return (
<div className="space-y-4">
{!hasError ? (
<div id={scannerDivId} className="overflow-hidden rounded-xl" />
<div
id={videoContainerId}
className={`w-full overflow-hidden rounded-xl bg-black ${containerHeight} [&_#qr-shaded-region]:!border-white/30 [&>video]:h-full [&>video]:w-full [&>video]:object-cover`}
/>
) : (
<div className="rounded-xl border border-white/10 bg-white/5 p-4 text-center">
<p className="mb-2 text-sm text-white/60">
<div className="rounded-xl border border-white/10 bg-white/5 p-6 text-center">
<p className="text-sm text-white/60">
Camera niet beschikbaar. Plak het QR-token hieronder.
</p>
</div>

View File

@@ -0,0 +1,260 @@
import { useState } from "react";
import { REGISTRATION_OPENS_AT } from "@/lib/opening";
import { useRegistrationOpen } from "@/lib/useRegistrationOpen";
import { client } from "@/utils/orpc";
function pad(n: number): string {
return String(n).padStart(2, "0");
}
interface UnitBoxProps {
value: string;
label: string;
}
function UnitBox({ value, label }: UnitBoxProps) {
return (
<div className="flex flex-col items-center gap-1">
<div className="flex w-14 items-center justify-center rounded-sm bg-white/10 px-2 py-2 font-['Intro',sans-serif] text-3xl text-white tabular-nums sm:w-auto sm:px-4 sm:py-3 sm:text-5xl md:text-6xl lg:text-7xl">
{value}
</div>
<span className="font-['Intro',sans-serif] text-[9px] text-white/50 uppercase tracking-widest sm:text-xs">
{label}
</span>
</div>
);
}
// Reminder opt-in form — sits at the very bottom of the banner
function ReminderForm() {
const [email, setEmail] = useState("");
const [status, setStatus] = useState<
"idle" | "loading" | "subscribed" | "already_subscribed" | "error"
>("idle");
const [errorMessage, setErrorMessage] = useState("");
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!email || status === "loading") return;
setStatus("loading");
try {
const result = await client.subscribeReminder({ email });
if (!result.ok && result.reason === "already_open") {
setStatus("idle");
return;
}
setStatus("subscribed");
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : "Er ging iets mis.");
setStatus("error");
}
}
const reminderTime = REGISTRATION_OPENS_AT.toLocaleTimeString("nl-BE", {
hour: "2-digit",
minute: "2-digit",
});
return (
<div
className="w-full"
style={{
animation: "reminderFadeIn 0.6s ease both",
animationDelay: "0.3s",
}}
>
<style>{`
@keyframes reminderFadeIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes reminderCheck {
from { opacity: 0; transform: scale(0.7); }
to { opacity: 1; transform: scale(1); }
}
`}</style>
{/* Hairline divider */}
<div
className="mx-auto mb-6 h-px w-24"
style={{
background:
"linear-gradient(to right, transparent, rgba(255,255,255,0.15), transparent)",
}}
/>
{status === "subscribed" || status === "already_subscribed" ? (
<div
className="flex flex-col items-center gap-2"
style={{
animation: "reminderCheck 0.4s cubic-bezier(0.34,1.56,0.64,1) both",
}}
>
{/* Checkmark glyph */}
<div
className="flex h-8 w-8 items-center justify-center rounded-full"
style={{
background: "rgba(255,255,255,0.12)",
border: "1px solid rgba(255,255,255,0.2)",
}}
>
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
aria-label="Vinkje"
role="img"
>
<path
d="M2.5 7L5.5 10L11.5 4"
stroke="white"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
<p
className="font-['Intro',sans-serif] text-sm tracking-wide"
style={{ color: "rgba(255,255,255,0.65)" }}
>
Herinnering ingepland voor {reminderTime}
</p>
</div>
) : (
<div className="flex flex-col items-center gap-3">
<p
className="font-['Intro',sans-serif] text-xs uppercase tracking-widest"
style={{ color: "rgba(255,255,255,0.35)", letterSpacing: "0.14em" }}
>
Herinnering ontvangen?
</p>
{/* Fused pill input + button */}
<form
onSubmit={handleSubmit}
className="flex w-full max-w-xs overflow-hidden"
style={{
borderRadius: "3px",
border: "1px solid rgba(255,255,255,0.18)",
background: "rgba(255,255,255,0.07)",
backdropFilter: "blur(6px)",
}}
>
<input
type="email"
required
placeholder="jouw@email.be"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={status === "loading"}
className="min-w-0 flex-1 bg-transparent px-4 py-2.5 text-sm text-white outline-none disabled:opacity-50"
style={{
fontFamily: "'Intro', sans-serif",
fontSize: "0.8rem",
letterSpacing: "0.02em",
}}
/>
{/* Vertical separator */}
<div
style={{
width: "1px",
background: "rgba(255,255,255,0.15)",
flexShrink: 0,
}}
/>
<button
type="submit"
disabled={status === "loading" || !email}
className="shrink-0 px-4 py-2.5 font-semibold text-xs transition-all disabled:opacity-40"
style={{
fontFamily: "'Intro', sans-serif",
letterSpacing: "0.06em",
color:
status === "loading"
? "rgba(255,255,255,0.5)"
: "rgba(255,255,255,0.9)",
background: "transparent",
cursor:
status === "loading" || !email ? "not-allowed" : "pointer",
whiteSpace: "nowrap",
}}
>
{status === "loading" ? "…" : "Stuur mij"}
</button>
</form>
{status === "error" && (
<p
className="font-['Intro',sans-serif] text-xs"
style={{ color: "rgba(255,140,140,0.8)" }}
>
{errorMessage}
</p>
)}
</div>
)}
</div>
);
}
/**
* Shown in place of the registration form while registration is not yet open.
*/
export function CountdownBanner() {
const { isOpen, days, hours, minutes, seconds } = useRegistrationOpen();
// Once open the parent component will unmount this — but render nothing just in case
if (isOpen) return null;
const openDate = REGISTRATION_OPENS_AT.toLocaleDateString("nl-BE", {
weekday: "long",
day: "numeric",
month: "long",
year: "numeric",
});
const openTime = REGISTRATION_OPENS_AT.toLocaleTimeString("nl-BE", {
hour: "2-digit",
minute: "2-digit",
});
return (
<div className="flex flex-col items-center gap-6 py-4 text-center sm:gap-8">
<div>
<p className="font-['Intro',sans-serif] text-base text-white/70 sm:text-lg md:text-xl">
Inschrijvingen openen op
</p>
<p className="mt-1 font-['Intro',sans-serif] text-lg text-white capitalize sm:text-xl md:text-2xl">
{openDate} om {openTime}
</p>
</div>
{/* Countdown — single row forced via grid, scales down on small screens */}
<div className="grid grid-cols-[auto_auto_auto_auto_auto_auto_auto] items-center gap-1.5 sm:flex sm:gap-4 md:gap-6">
<UnitBox value={String(days)} label="dagen" />
<span className="mb-6 font-['Intro',sans-serif] text-2xl text-white/40 sm:text-4xl">
:
</span>
<UnitBox value={pad(hours)} label="uren" />
<span className="mb-6 font-['Intro',sans-serif] text-2xl text-white/40 sm:text-4xl">
:
</span>
<UnitBox value={pad(minutes)} label="minuten" />
<span className="mb-6 font-['Intro',sans-serif] text-2xl text-white/40 sm:text-4xl">
:
</span>
<UnitBox value={pad(seconds)} label="seconden" />
</div>
<p className="max-w-md px-4 text-sm text-white/50">
Kom snel terug! Zodra de inschrijvingen openen kun je je hier
registreren als toeschouwer of als artiest.
</p>
{/* Email reminder opt-in — always last */}
<ReminderForm />
</div>
);
}

View File

@@ -1,47 +1,78 @@
import { Link } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import confetti from "canvas-confetti";
import { useEffect, useRef, useState } from "react";
import { CountdownBanner } from "@/components/homepage/CountdownBanner";
import { PerformerForm } from "@/components/registration/PerformerForm";
import { SuccessScreen } from "@/components/registration/SuccessScreen";
import { TypeSelector } from "@/components/registration/TypeSelector";
import { WatcherForm } from "@/components/registration/WatcherForm";
import { authClient } from "@/lib/auth-client";
import { useRegistrationOpen } from "@/lib/useRegistrationOpen";
import { orpc } from "@/utils/orpc";
function fireConfetti() {
const colors = ["#d82560", "#52979b", "#d09035", "#214e51", "#ffffff"];
confetti({
particleCount: 120,
spread: 80,
origin: { x: 0.3, y: 0.6 },
colors,
});
setTimeout(() => {
confetti({
particleCount: 120,
spread: 80,
origin: { x: 0.7, y: 0.6 },
colors,
});
}, 200);
setTimeout(() => {
confetti({
particleCount: 80,
spread: 100,
origin: { x: 0.5, y: 0.5 },
colors,
});
}, 400);
}
type RegistrationType = "performer" | "watcher";
interface SuccessState {
token: string;
email: string;
name: string;
function redirectToSignup(email: string) {
const params = new URLSearchParams({
signup: "1",
email,
next: "/account",
});
window.location.href = `/login?${params.toString()}`;
}
export default function EventRegistrationForm() {
const { data: session } = authClient.useSession();
const { isOpen } = useRegistrationOpen();
const confettiFired = useRef(false);
const { data: capacity } = useQuery(orpc.getWatcherCapacity.queryOptions());
useEffect(() => {
if (isOpen && !confettiFired.current) {
confettiFired.current = true;
fireConfetti();
}
}, [isOpen]);
const [selectedType, setSelectedType] = useState<RegistrationType | null>(
null,
);
const [successState, setSuccessState] = useState<SuccessState | null>(null);
const isLoggedIn = !!session?.user;
const user = session?.user as { name?: string; email?: string } | undefined;
// Split "Jan De Smet" → firstName="Jan", lastName="De Smet"
const nameParts = (user?.name ?? "").trim().split(/\s+/);
const prefillFirstName = nameParts[0] ?? "";
const prefillLastName = nameParts.slice(1).join(" ");
const prefillEmail = user?.email ?? "";
if (successState) {
if (!isOpen) {
return (
<SuccessScreen
token={successState.token}
email={successState.email}
name={successState.name}
isLoggedIn={isLoggedIn}
onReset={() => {
setSuccessState(null);
setSelectedType(null);
}}
/>
<section
id="registration"
className="relative z-30 w-full bg-[#214e51]/96 px-6 py-16 md:px-12"
>
<div className="mx-auto w-full max-w-6xl">
<CountdownBanner />
</div>
</section>
);
}
@@ -60,54 +91,24 @@ export default function EventRegistrationForm() {
<p className="mb-8 max-w-3xl text-lg text-white/80 md:text-xl">
Doe je mee of kom je kijken? Kies je rol en vul het formulier in.
</p>
{/* Login nudge — shown only to guests */}
{!isLoggedIn && (
<div className="mb-10 flex flex-col gap-3 rounded-lg border border-[#52979b]/40 bg-[#52979b]/10 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-white/80">
<span className="mr-1 font-semibold text-teal-300">
Al een account?
</span>
Log in om je gegevens automatisch in te vullen en je Drinkkaart
direct te activeren na registratie.
</p>
<div className="flex shrink-0 items-center gap-3 text-sm">
<Link
to="/login"
className="font-medium text-teal-300 underline-offset-2 transition-colors hover:underline"
>
Inloggen
</Link>
<span className="text-white/30">·</span>
<Link
to="/login"
search={{ signup: "1" }}
className="text-white/60 transition-colors hover:text-white"
>
Nog geen account? Aanmaken
</Link>
</div>
</div>
{!selectedType && (
<TypeSelector
onSelect={setSelectedType}
watcherIsFull={capacity?.isFull ?? false}
watcherAvailable={capacity?.available ?? null}
/>
)}
{!selectedType && <TypeSelector onSelect={setSelectedType} />}
{selectedType === "performer" && (
<PerformerForm
onBack={() => setSelectedType(null)}
onSuccess={(token, email, name) =>
setSuccessState({ token, email, name })
}
prefillFirstName={prefillFirstName}
prefillLastName={prefillLastName}
prefillEmail={prefillEmail}
isLoggedIn={isLoggedIn}
onSuccess={(_token, email, _name) => redirectToSignup(email)}
/>
)}
{selectedType === "watcher" && (
<WatcherForm
onBack={() => setSelectedType(null)}
prefillFirstName={prefillFirstName}
prefillLastName={prefillLastName}
prefillEmail={prefillEmail}
isLoggedIn={isLoggedIn}
onSuccess={(_token, email, _name) => redirectToSignup(email)}
/>
)}
</div>

View File

@@ -86,6 +86,26 @@ export default function Footer() {
{/* Vertical rule */}
<div className="hidden h-28 w-px bg-white/20 md:block" />
{/* Ichtus Antwerpen */}
<a
href="https://ichtusantwerpen.com"
target="_blank"
rel="noopener noreferrer"
className="flex flex-col items-center gap-3 opacity-90 transition-opacity hover:opacity-100"
>
<img
src="/assets/ichtusantwerpen.png"
alt="Ichtus Antwerpen"
className="h-14 w-auto"
/>
<p className="text-center font-['DM_Sans',sans-serif] font-medium text-white/60 text-xs uppercase tracking-[0.15em]">
Ichtus Antwerpen
</p>
</a>
{/* Vertical rule */}
<div className="hidden h-28 w-px bg-white/20 md:block" />
{/* Vlaanderen */}
<a
href="https://www.vlaanderen.be/cjm/nl"

View File

@@ -0,0 +1,74 @@
export default function HoeInschrijven() {
return (
<section className="relative z-25 w-full bg-[#f8f8f8] px-6 py-16 md:px-12">
<div className="mx-auto max-w-6xl">
<h2 className="mb-4 font-['Intro',sans-serif] text-4xl text-[#214e51] md:text-5xl">
Hoe schrijf ik mij in?
</h2>
<p className="mb-10 max-w-3xl text-[#214e51]/70 text-lg">
Inschrijven doe je eenvoudig via deze website zodra de inschrijvingen
openen.
</p>
{/* Step cards */}
<div className="grid gap-6 md:grid-cols-3">
{/* Step 1 */}
<div className="flex flex-col gap-3 rounded-2xl border border-[#214e51]/15 bg-white p-6 shadow-sm">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#d82560] font-['Intro',sans-serif] font-bold text-lg text-white">
1
</div>
<h3 className="font-['Intro',sans-serif] text-[#214e51] text-xl">
Kies je rol
</h3>
<p className="text-[#214e51]/70 text-base leading-relaxed">
Registreer je als{" "}
<strong className="text-[#214e51]">artiest</strong> als je wil
optreden, of als{" "}
<strong className="text-[#214e51]">bezoeker</strong> als je wil
komen kijken. Je kunt ook aangeven met hoeveel mensen je komt.
</p>
</div>
{/* Step 2 */}
<div className="flex flex-col gap-3 rounded-2xl border border-[#214e51]/15 bg-white p-6 shadow-sm">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#d82560] font-['Intro',sans-serif] font-bold text-lg text-white">
2
</div>
<h3 className="font-['Intro',sans-serif] text-[#214e51] text-xl">
Bevestig je plaats
</h3>
<p className="text-[#214e51]/70 text-base leading-relaxed">
We vragen een bijdrage van{" "}
<strong className="text-[#214e51]">5 per persoon</strong> voor
jou én iedereen die je meebrengt.
</p>
</div>
{/* Step 3 */}
<div className="flex flex-col gap-3 rounded-2xl border border-[#214e51]/15 bg-white p-6 shadow-sm">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#d82560] font-['Intro',sans-serif] font-bold text-lg text-white">
3
</div>
<h3 className="font-['Intro',sans-serif] text-[#214e51] text-xl">
Geniet van de avond
</h3>
<p className="text-[#214e51]/70 text-base leading-relaxed">
Je bijdrage gaat{" "}
<strong className="text-[#214e51]">niet verloren</strong> het
wordt volledig op{" "}
<strong className="text-[#214e51]">je drankkaart</strong> gezet.
Zo kun je tijdens de avond iets drinken of een snack nemen.
</p>
</div>
</div>
{/* Bottom note */}
<p className="mt-8 max-w-3xl text-[#214e51]/60 text-base leading-relaxed">
Zo zorgen we ervoor dat iedereen die zich inschrijft ook echt een
plaats heeft en dat we samen kunnen genieten van een gezellige,
inspirerende avond vol muziek, poëzie en andere kunst.
</p>
</div>
</section>
);
}

View File

@@ -12,7 +12,13 @@ const faqQuestions = [
{
question: "Hoelang mag mijn optreden duren?",
answer:
"Elke deelnemer krijgt 5-7 minuten podiumtijd. Zo houden we de avond dynamisch en krijgt iedereen een kans om te shinen.",
"Elke deelnemer krijgt 5 minuten podiumtijd. Zo houden we de avond dynamisch en krijgt iedereen een kans om te shinen.",
},
{
question: "Waar vindt het plaats?",
answer:
"De Open Mic Night vindt plaats op Lange Winkelstraat 5, 2000 Antwerpen.",
mapUrl: "https://maps.app.goo.gl/kU6iug3QVKwWD1vR7",
},
{
question: "Wat moet ik meenemen?",
@@ -179,6 +185,16 @@ export default function Info() {
{item.question}
</h3>
<p className="max-w-xl text-white/80 text-xl">{item.answer}</p>
{"mapUrl" in item && (
<a
href={item.mapUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-white/60 underline hover:text-white/90"
>
Bekijk op Google Maps
</a>
)}
</div>
))}
</div>

View File

@@ -204,51 +204,6 @@ export function GuestList({
)}
</div>
<div className="flex flex-col gap-2">
<label
htmlFor={`guest-${idx}-birthdate`}
className="text-white/80"
>
Geboortedatum <span className="text-red-300">*</span>
</label>
<input
type="date"
id={`guest-${idx}-birthdate`}
value={guest.birthdate}
onChange={(e) => onChange(idx, "birthdate", e.target.value)}
autoComplete="off"
className={inputCls(!!errors[idx]?.birthdate)}
/>
{errors[idx]?.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors[idx].birthdate}
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label
htmlFor={`guest-${idx}-postcode`}
className="text-white/80"
>
Postcode <span className="text-red-300">*</span>
</label>
<input
type="text"
id={`guest-${idx}-postcode`}
value={guest.postcode}
onChange={(e) => onChange(idx, "postcode", e.target.value)}
placeholder="1234 AB"
autoComplete="off"
className={inputCls(!!errors[idx]?.postcode)}
/>
{errors[idx]?.postcode && (
<span className="text-red-300 text-sm" role="alert">
{errors[idx].postcode}
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label htmlFor={`guest-${idx}-email`} className="text-white/80">
E-mail
@@ -290,6 +245,169 @@ export function GuestList({
</span>
)}
</div>
{/* Birthdate */}
<div className="flex flex-col gap-2 md:col-span-2">
<p className="text-white/80">
Geboortedatum <span className="text-red-300">*</span>
</p>
<fieldset className="m-0 flex gap-2 border-0 p-0">
<legend className="sr-only">
Geboortedatum medebezoeker {idx + 1}
</legend>
<div className="flex flex-1 flex-col gap-1">
<label
htmlFor={`guest-${idx}-birthdateDay`}
className="sr-only"
>
Dag
</label>
<select
id={`guest-${idx}-birthdateDay`}
value={guest.birthdate?.split("-")[2] ?? ""}
onChange={(e) => {
const parts = (guest.birthdate || "--").split("-");
onChange(
idx,
"birthdate",
`${parts[0] || ""}-${parts[1] || ""}-${e.target.value.padStart(2, "0")}`,
);
}}
aria-label="Dag"
className={`border-b bg-transparent pb-2 text-sm text-white transition-colors focus:outline-none ${errors[idx]?.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
DD
</option>
{Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
<option
key={d}
value={String(d).padStart(2, "0")}
className="bg-[#214e51]"
>
{String(d).padStart(2, "0")}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label
htmlFor={`guest-${idx}-birthdateMonth`}
className="sr-only"
>
Maand
</label>
<select
id={`guest-${idx}-birthdateMonth`}
value={guest.birthdate?.split("-")[1] ?? ""}
onChange={(e) => {
const parts = (guest.birthdate || "--").split("-");
onChange(
idx,
"birthdate",
`${parts[0] || ""}-${e.target.value.padStart(2, "0")}-${parts[2] || ""}`,
);
}}
aria-label="Maand"
className={`border-b bg-transparent pb-2 text-sm text-white transition-colors focus:outline-none ${errors[idx]?.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
MM
</option>
{[
"Jan",
"Feb",
"Mrt",
"Apr",
"Mei",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
].map((m, i) => (
<option
key={m}
value={String(i + 1).padStart(2, "0")}
className="bg-[#214e51]"
>
{m}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label
htmlFor={`guest-${idx}-birthdateYear`}
className="sr-only"
>
Jaar
</label>
<select
id={`guest-${idx}-birthdateYear`}
value={guest.birthdate?.split("-")[0] ?? ""}
onChange={(e) => {
const parts = (guest.birthdate || "--").split("-");
onChange(
idx,
"birthdate",
`${e.target.value}-${parts[1] || ""}-${parts[2] || ""}`,
);
}}
aria-label="Jaar"
className={`border-b bg-transparent pb-2 text-sm text-white transition-colors focus:outline-none ${errors[idx]?.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
JJJJ
</option>
{Array.from(
{ length: 100 },
(_, i) => new Date().getFullYear() - i,
).map((y) => (
<option
key={y}
value={String(y)}
className="bg-[#214e51]"
>
{y}
</option>
))}
</select>
</div>
</fieldset>
{errors[idx]?.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors[idx].birthdate}
</span>
)}
</div>
{/* Postcode */}
<div className="flex flex-col gap-2">
<label
htmlFor={`guest-${idx}-postcode`}
className="text-white/80"
>
Postcode <span className="text-red-300">*</span>
</label>
<input
type="text"
id={`guest-${idx}-postcode`}
value={guest.postcode}
onChange={(e) => onChange(idx, "postcode", e.target.value)}
placeholder="bv. 9000"
autoComplete="off"
inputMode="numeric"
className={inputCls(!!errors[idx]?.postcode)}
/>
{errors[idx]?.postcode && (
<span className="text-red-300 text-sm" role="alert">
{errors[idx].postcode}
</span>
)}
</div>
</div>
</div>
))}

View File

@@ -1,10 +1,13 @@
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import {
inputCls,
validateBirthdate,
validateEmail,
validatePhone,
validatePostcode,
validateTextField,
} from "@/lib/registration";
import { orpc } from "@/utils/orpc";
@@ -15,8 +18,8 @@ interface PerformerErrors {
lastName?: string;
email?: string;
phone?: string;
postcode?: string;
birthdate?: string;
postcode?: string;
artForm?: string;
isOver16?: string;
}
@@ -24,27 +27,21 @@ interface PerformerErrors {
interface Props {
onBack: () => void;
onSuccess: (token: string, email: string, name: string) => void;
prefillFirstName?: string;
prefillLastName?: string;
prefillEmail?: string;
isLoggedIn?: boolean;
}
export function PerformerForm({
onBack,
onSuccess,
prefillFirstName = "",
prefillLastName = "",
prefillEmail = "",
isLoggedIn = false,
}: Props) {
export function PerformerForm({ onBack, onSuccess }: Props) {
const { data: session } = authClient.useSession();
const sessionEmail = session?.user?.email ?? "";
const [data, setData] = useState({
firstName: prefillFirstName,
lastName: prefillLastName,
email: prefillEmail,
firstName: "",
lastName: "",
email: "",
phone: "",
birthdateDay: "",
birthdateMonth: "",
birthdateYear: "",
postcode: "",
birthdate: "",
artForm: "",
experience: "",
isOver16: false,
@@ -54,6 +51,12 @@ export function PerformerForm({
const [errors, setErrors] = useState<PerformerErrors>({});
const [touched, setTouched] = useState<Record<string, boolean>>({});
useEffect(() => {
if (sessionEmail) {
setData((prev) => ({ ...prev, email: sessionEmail }));
}
}, [sessionEmail]);
const submitMutation = useMutation({
...orpc.submitRegistration.mutationOptions(),
onSuccess: (result) => {
@@ -69,14 +72,21 @@ export function PerformerForm({
},
});
function getBirthdate(): string {
const { birthdateYear, birthdateMonth, birthdateDay } = data;
if (!birthdateYear || !birthdateMonth || !birthdateDay) return "";
return `${birthdateYear}-${birthdateMonth.padStart(2, "0")}-${birthdateDay.padStart(2, "0")}`;
}
function validate(): boolean {
const birthdate = getBirthdate();
const errs: PerformerErrors = {
firstName: validateTextField(data.firstName, true, "Voornaam"),
lastName: validateTextField(data.lastName, true, "Achternaam"),
email: validateEmail(data.email),
phone: validatePhone(data.phone),
postcode: !data.postcode.trim() ? "Postcode is verplicht" : undefined,
birthdate: !data.birthdate ? "Geboortedatum is verplicht" : undefined,
birthdate: validateBirthdate(birthdate),
postcode: validatePostcode(data.postcode),
artForm: !data.artForm.trim() ? "Kunstvorm is verplicht" : undefined,
isOver16: !data.isOver16
? "Je moet 16 jaar of ouder zijn om op te treden"
@@ -88,8 +98,8 @@ export function PerformerForm({
lastName: true,
email: true,
phone: true,
postcode: true,
birthdate: true,
postcode: true,
artForm: true,
isOver16: true,
});
@@ -118,14 +128,6 @@ export function PerformerForm({
),
email: validateEmail(name === "email" ? value : data.email),
phone: validatePhone(name === "phone" ? value : data.phone),
postcode:
name === "postcode" && !value.trim()
? "Postcode is verplicht"
: undefined,
birthdate:
name === "birthdate" && !value
? "Geboortedatum is verplicht"
: undefined,
artForm:
name === "artForm" && !value.trim()
? "Kunstvorm is verplicht"
@@ -145,14 +147,6 @@ export function PerformerForm({
lastName: validateTextField(value, true, "Achternaam"),
email: validateEmail(value),
phone: validatePhone(value),
postcode:
name === "postcode" && !value.trim()
? "Postcode is verplicht"
: undefined,
birthdate:
name === "birthdate" && !value
? "Geboortedatum is verplicht"
: undefined,
artForm: !value.trim() ? "Kunstvorm is verplicht" : undefined,
};
setErrors((prev) => ({ ...prev, [name]: errMap[name] }));
@@ -169,8 +163,8 @@ export function PerformerForm({
lastName: data.lastName.trim(),
email: data.email.trim(),
phone: data.phone.trim() || undefined,
birthdate: getBirthdate(),
postcode: data.postcode.trim(),
birthdate: data.birthdate,
registrationType: "performer",
artForm: data.artForm.trim() || undefined,
experience: data.experience.trim() || undefined,
@@ -291,15 +285,15 @@ export function PerformerForm({
id="p-email"
name="email"
value={data.email}
onChange={isLoggedIn ? undefined : handleChange}
onBlur={isLoggedIn ? undefined : handleBlur}
readOnly={isLoggedIn}
onChange={sessionEmail ? undefined : handleChange}
onBlur={sessionEmail ? undefined : handleBlur}
readOnly={!!sessionEmail}
placeholder="jouw@email.be"
autoComplete="email"
inputMode="email"
aria-required="true"
aria-invalid={touched.email && !!errors.email}
className={`${inputCls(!!touched.email && !!errors.email)}${isLoggedIn ? "cursor-not-allowed opacity-60" : ""}`}
className={`${inputCls(!!touched.email && !!errors.email)}${sessionEmail ? "cursor-not-allowed opacity-75" : ""}`}
/>
{touched.email && errors.email && (
<span className="text-red-300 text-sm" role="alert">
@@ -332,8 +326,123 @@ export function PerformerForm({
</div>
</div>
{/* Postcode + Birthdate row */}
{/* Birthdate + Postcode row */}
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div className="flex flex-col gap-2">
<p className="text-white text-xl">
Geboortedatum <span className="text-red-300">*</span>
</p>
<fieldset className="m-0 flex gap-2 border-0 p-0">
<legend className="sr-only">Geboortedatum</legend>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="p-birthdateDay" className="sr-only">
Dag
</label>
<select
id="p-birthdateDay"
name="birthdateDay"
value={data.birthdateDay}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateDay: e.target.value,
}))
}
aria-label="Dag"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
DD
</option>
{Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
<option key={d} value={String(d)} className="bg-[#214e51]">
{String(d).padStart(2, "0")}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="p-birthdateMonth" className="sr-only">
Maand
</label>
<select
id="p-birthdateMonth"
name="birthdateMonth"
value={data.birthdateMonth}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateMonth: e.target.value,
}))
}
aria-label="Maand"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
MM
</option>
{[
"Jan",
"Feb",
"Mrt",
"Apr",
"Mei",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
].map((m, i) => (
<option
key={m}
value={String(i + 1)}
className="bg-[#214e51]"
>
{m}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="p-birthdateYear" className="sr-only">
Jaar
</label>
<select
id="p-birthdateYear"
name="birthdateYear"
value={data.birthdateYear}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateYear: e.target.value,
}))
}
aria-label="Jaar"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
JJJJ
</option>
{Array.from(
{ length: 100 },
(_, i) => new Date().getFullYear() - i,
).map((y) => (
<option key={y} value={String(y)} className="bg-[#214e51]">
{y}
</option>
))}
</select>
</div>
</fieldset>
{touched.birthdate && errors.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors.birthdate}
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label htmlFor="p-postcode" className="text-white text-xl">
Postcode <span className="text-red-300">*</span>
@@ -345,8 +454,9 @@ export function PerformerForm({
value={data.postcode}
onChange={handleChange}
onBlur={handleBlur}
placeholder="1234 AB"
placeholder="bv. 9000"
autoComplete="postal-code"
inputMode="numeric"
aria-required="true"
aria-invalid={touched.postcode && !!errors.postcode}
className={inputCls(!!touched.postcode && !!errors.postcode)}
@@ -357,27 +467,6 @@ export function PerformerForm({
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label htmlFor="p-birthdate" className="text-white text-xl">
Geboortedatum <span className="text-red-300">*</span>
</label>
<input
type="date"
id="p-birthdate"
name="birthdate"
value={data.birthdate}
onChange={handleChange}
onBlur={handleBlur}
autoComplete="bday"
aria-invalid={touched.birthdate && !!errors.birthdate}
className={`${inputCls(!!touched.birthdate && !!errors.birthdate)} [color-scheme:dark]`}
/>
{touched.birthdate && errors.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors.birthdate}
</span>
)}
</div>
</div>
{/* Performer-specific fields */}
@@ -516,6 +605,33 @@ export function PerformerForm({
<GiftSelector value={giftAmount} onChange={setGiftAmount} />
</div>
{/* Under review notice */}
<div className="flex items-start gap-3 rounded-lg border border-amber-400/30 bg-amber-400/10 p-4">
<svg
className="mt-0.5 h-5 w-5 shrink-0 text-amber-300"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
/>
</svg>
<div>
<p className="font-semibold text-amber-300 text-sm">
Jouw inschrijving staat onder voorbehoud
</p>
<p className="mt-1 text-sm text-white/70">
Na het indienen wordt je aanvraag beoordeeld. Je ontvangt een
bevestiging of je effectief uitgenodigd wordt om op te treden.
</p>
</div>
</div>
<div className="flex flex-col items-center gap-4 pt-4">
<button
type="submit"

View File

@@ -1,157 +0,0 @@
import { useState } from "react";
interface Props {
token: string;
email?: string;
name?: string;
onReset: () => void;
isLoggedIn?: boolean;
}
export function SuccessScreen({
token,
email,
name,
onReset,
isLoggedIn,
}: Props) {
const manageUrl =
typeof window !== "undefined"
? `${window.location.origin}/manage/${token}`
: `/manage/${token}`;
const [drinkkaartPromptDismissed, setDrinkkaartPromptDismissed] = useState(
() => {
try {
return (
typeof localStorage !== "undefined" &&
localStorage.getItem("drinkkaart_prompt_dismissed") === "1"
);
} catch {
return false;
}
},
);
const handleDismissPrompt = () => {
try {
localStorage.setItem("drinkkaart_prompt_dismissed", "1");
} catch {
// ignore
}
setDrinkkaartPromptDismissed(true);
};
// Build signup URL with pre-filled email query param so /login can pre-fill
const signupUrl = email
? `/login?signup=1&email=${encodeURIComponent(email)}`
: "/login?signup=1";
return (
<section
id="registration"
className="relative z-30 flex w-full items-center justify-center bg-[#214e51]/96 px-6 py-16 md:px-12"
>
<div className="mx-auto w-full max-w-3xl">
<div className="rounded-lg border border-white/20 bg-white/5 p-8 md:p-12">
<div className="mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-green-500/20 text-green-400">
<svg
className="h-8 w-8"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-label="Succes"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M5 13l4 4L19 7"
/>
</svg>
</div>
<h2 className="mb-4 font-['Intro',sans-serif] text-3xl text-white md:text-4xl">
Gelukt!
</h2>
<p className="mb-6 text-lg text-white/80">
Je inschrijving is bevestigd. We sturen je zo dadelijk een
bevestigingsmail.
</p>
<div className="mb-8 rounded-lg border border-white/10 bg-white/5 p-6">
<p className="mb-2 text-sm text-white/60">
Geen mail ontvangen? Gebruik deze link:
</p>
<a
href={manageUrl}
className="break-all text-sm text-white/80 underline underline-offset-2 hover:text-white"
>
{manageUrl}
</a>
</div>
<div className="flex flex-wrap items-center gap-4">
<a
href={manageUrl}
className="inline-flex items-center bg-white px-6 py-3 font-['Intro',sans-serif] text-[#214e51] text-lg transition-all hover:scale-105 hover:bg-gray-100"
>
Bekijk mijn inschrijving
</a>
<button
type="button"
onClick={onReset}
className="text-white/60 underline underline-offset-2 transition-colors hover:text-white"
>
Nog een inschrijving
</button>
</div>
{/* Account creation prompt — hidden when already logged in */}
{!isLoggedIn && !drinkkaartPromptDismissed && (
<div className="mt-8 rounded-xl border border-teal-400/30 bg-teal-400/10 p-6">
<h3 className="mb-1 font-['Intro',sans-serif] text-lg text-white">
Maak een gratis account aan
</h3>
<p className="mb-4 text-sm text-white/70">
Met een account zie je je inschrijving, activeer je je
Drinkkaart en laad je saldo op vóór het evenement.
</p>
<ul className="mb-5 space-y-1.5 text-sm text-white/70">
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Beheer je inschrijving op één plek
</li>
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Digitale Drinkkaart met QR-code
</li>
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Saldo opladen vóór het evenement
</li>
</ul>
<div className="flex flex-wrap items-center gap-3">
<a
href={signupUrl}
className="inline-flex items-center rounded-lg bg-white px-5 py-2.5 font-['Intro',sans-serif] text-[#214e51] text-sm transition-all hover:scale-105 hover:bg-gray-100"
>
Account aanmaken
{name && (
<span className="ml-1.5 font-normal text-xs opacity-60">
als {name}
</span>
)}
</a>
<button
type="button"
onClick={handleDismissPrompt}
className="text-sm text-white/40 underline underline-offset-2 transition-colors hover:text-white/70"
>
Overslaan
</button>
</div>
</div>
)}
</div>
</div>
</section>
);
}

View File

@@ -2,9 +2,15 @@ type RegistrationType = "performer" | "watcher";
interface Props {
onSelect: (type: RegistrationType) => void;
watcherIsFull?: boolean;
watcherAvailable?: number | null;
}
export function TypeSelector({ onSelect }: Props) {
export function TypeSelector({
onSelect,
watcherIsFull = false,
watcherAvailable = null,
}: Props) {
return (
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
{/* Performer card */}
@@ -59,10 +65,17 @@ export function TypeSelector({ onSelect }: Props) {
{/* Watcher card */}
<button
type="button"
onClick={() => onSelect("watcher")}
className="group relative flex flex-col overflow-hidden border border-white/20 bg-white/5 p-8 text-left transition-all duration-300 hover:border-white/50 hover:bg-white/10 md:p-10"
onClick={() => !watcherIsFull && onSelect("watcher")}
disabled={watcherIsFull}
className={`group relative flex flex-col overflow-hidden border p-8 text-left transition-all duration-300 md:p-10 ${
watcherIsFull
? "cursor-not-allowed border-white/10 bg-white/3 opacity-60"
: "border-white/20 bg-white/5 hover:border-white/50 hover:bg-white/10"
}`}
>
<div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-400 to-cyan-400 opacity-80" />
<div
className={`absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-400 to-cyan-400 ${watcherIsFull ? "opacity-30" : "opacity-80"}`}
/>
<div className="mb-6 flex h-14 w-14 items-center justify-center rounded-full bg-teal-400/15 text-teal-300">
<svg
className="h-7 w-7"
@@ -83,31 +96,47 @@ export function TypeSelector({ onSelect }: Props) {
Ik wil komen kijken
</h3>
<p className="mb-4 text-white/70">
Geniet van een avond vol talent en kunst. Je betaald 5EUR inkom dat je
mag gebruiken op je drinkkaart.
Geniet van een avond vol talent en kunst. Je betaalt 5 per persoon
dit gaat volledig naar je drinkkaart.
</p>
<div className="mb-6 inline-flex items-center gap-2 rounded-full border border-teal-400/40 bg-teal-400/10 px-4 py-1.5">
<span className="font-semibold text-sm text-teal-300">
Drinkkaart 5 EUR te betalen bij registratie
</span>
</div>
<div className="mt-auto flex items-center gap-2 font-medium text-sm text-teal-300">
<span>Inschrijven als bezoeker</span>
<svg
className="h-4 w-4 transition-transform group-hover:translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
/>
</svg>
</div>
{watcherIsFull ? (
<div className="mb-6 inline-flex items-center gap-2 rounded-full border border-red-400/40 bg-red-400/10 px-4 py-1.5">
<span className="font-semibold text-red-300 text-sm">
Volzet geen plaatsen meer beschikbaar
</span>
</div>
) : (
<div className="mb-6 inline-flex items-center gap-2 rounded-full border border-teal-400/40 bg-teal-400/10 px-4 py-1.5">
<span className="font-semibold text-sm text-teal-300">
5 per persoon drinkkaart inbegrepen
{watcherAvailable !== null && watcherAvailable <= 10 && (
<span className="ml-1 text-amber-300">
({watcherAvailable}{" "}
{watcherAvailable === 1 ? "plaats" : "plaatsen"} vrij)
</span>
)}
</span>
</div>
)}
{!watcherIsFull && (
<div className="mt-auto flex items-center gap-2 font-medium text-sm text-teal-300">
<span>Inschrijven als bezoeker</span>
<svg
className="h-4 w-4 transition-transform group-hover:translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
/>
</svg>
</div>
)}
</button>
</div>
);

View File

@@ -1,5 +1,5 @@
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import {
@@ -7,12 +7,14 @@ import {
type GuestEntry,
type GuestErrors,
inputCls,
validateBirthdate,
validateEmail,
validateGuests,
validatePhone,
validatePostcode,
validateTextField,
} from "@/lib/registration";
import { client, orpc } from "@/utils/orpc";
import { orpc } from "@/utils/orpc";
import { GiftSelector } from "./GiftSelector";
import { GuestList } from "./GuestList";
@@ -21,240 +23,30 @@ interface WatcherErrors {
lastName?: string;
email?: string;
phone?: string;
postcode?: string;
birthdate?: string;
postcode?: string;
}
interface Props {
onBack: () => void;
prefillFirstName?: string;
prefillLastName?: string;
prefillEmail?: string;
isLoggedIn?: boolean;
}
// ── Account creation modal shown after successful registration ─────────────
interface AccountModalProps {
prefillName: string;
prefillEmail: string;
onDone: () => void;
}
function AccountModal({
prefillName,
prefillEmail,
onDone,
}: AccountModalProps) {
const [name, setName] = useState(prefillName);
const [email] = useState(prefillEmail); // email is fixed (tied to registration)
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordError, setPasswordError] = useState<string | undefined>();
const signupMutation = useMutation({
mutationFn: async () => {
if (password.length < 8)
throw new Error("Wachtwoord moet minstens 8 tekens zijn");
if (password !== confirmPassword)
throw new Error("Wachtwoorden komen niet overeen");
const result = await authClient.signUp.email({ email, password, name });
if (result.error) throw new Error(result.error.message);
return result.data;
},
onSuccess: () => {
toast.success(
"Account aangemaakt! Je wordt nu doorgestuurd naar betaling.",
);
onDone();
},
onError: (error) => {
toast.error(`Account aanmaken mislukt: ${error.message}`);
},
});
const handlePasswordChange = (val: string) => {
setPassword(val);
if (passwordError) setPasswordError(undefined);
};
const handleConfirmChange = (val: string) => {
setConfirmPassword(val);
if (passwordError) setPasswordError(undefined);
};
const handleSignup = (e: React.FormEvent) => {
e.preventDefault();
if (password.length < 8) {
setPasswordError("Wachtwoord moet minstens 8 tekens zijn");
return;
}
if (password !== confirmPassword) {
setPasswordError("Wachtwoorden komen niet overeen");
return;
}
signupMutation.mutate();
};
// Receive the checkout URL from parent by exposing a setter via ref pattern
// (simpler: the parent renders the modal and passes a prop)
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4">
<div className="w-full max-w-md rounded-2xl border border-white/10 bg-[#1a3d40] p-8 shadow-2xl">
{/* Header */}
<div className="mb-6 flex items-start gap-4">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-teal-400/20 text-teal-300 text-xl">
</div>
<div>
<h2 className="font-['Intro',sans-serif] text-2xl text-white">
Inschrijving gelukt!
</h2>
<p className="mt-1 text-sm text-white/60">
Maak een gratis account aan om je Drinkkaart bij te houden.
</p>
</div>
</div>
{/* Value prop */}
<div className="mb-6 rounded-lg border border-teal-400/20 bg-teal-400/10 p-4">
<ul className="space-y-1.5 text-sm text-white/80">
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Zie je drinkkaart-saldo en QR-code
</li>
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Laad je kaart op vóór het evenement
</li>
<li className="flex items-center gap-2">
<span className="text-teal-300"></span>
Beheer je inschrijving op één plek
</li>
</ul>
</div>
{/* Signup form */}
<form onSubmit={handleSignup} className="space-y-4">
{/* Name */}
<div>
<label
className="mb-1.5 block text-sm text-white/60"
htmlFor="modal-name"
>
Naam
</label>
<input
id="modal-name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full rounded-lg border border-white/20 bg-white/10 px-3 py-2 text-white placeholder:text-white/30 focus:border-teal-400/60 focus:outline-none"
/>
</div>
{/* Email (read-only) */}
<div>
<label
className="mb-1.5 block text-sm text-white/60"
htmlFor="modal-email"
>
Email
</label>
<input
id="modal-email"
type="email"
value={email}
readOnly
className="w-full cursor-not-allowed rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-white/60"
/>
</div>
{/* Password */}
<div>
<label
className="mb-1.5 block text-sm text-white/60"
htmlFor="modal-password"
>
Wachtwoord
</label>
<input
id="modal-password"
type="password"
placeholder="Minstens 8 tekens"
value={password}
onChange={(e) => handlePasswordChange(e.target.value)}
required
minLength={8}
className="w-full rounded-lg border border-white/20 bg-white/10 px-3 py-2 text-white placeholder:text-white/30 focus:border-teal-400/60 focus:outline-none"
/>
</div>
{/* Confirm password */}
<div>
<label
className="mb-1.5 block text-sm text-white/60"
htmlFor="modal-confirm"
>
Bevestig wachtwoord
</label>
<input
id="modal-confirm"
type="password"
placeholder="Herhaal je wachtwoord"
value={confirmPassword}
onChange={(e) => handleConfirmChange(e.target.value)}
required
className="w-full rounded-lg border border-white/20 bg-white/10 px-3 py-2 text-white placeholder:text-white/30 focus:border-teal-400/60 focus:outline-none"
/>
</div>
{passwordError && (
<p className="text-red-300 text-sm">{passwordError}</p>
)}
<button
type="submit"
disabled={signupMutation.isPending}
className="w-full rounded-lg bg-white py-3 font-['Intro',sans-serif] text-[#214e51] transition-all hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50"
>
{signupMutation.isPending
? "Bezig..."
: "Account aanmaken & betalen"}
</button>
</form>
{/* Skip */}
<button
type="button"
onClick={onDone}
className="mt-4 w-full text-center text-sm text-white/40 transition-colors hover:text-white/70"
>
Overslaan, verder naar betaling
</button>
</div>
</div>
);
onSuccess: (token: string, email: string, name: string) => void;
}
// ── Main watcher form ──────────────────────────────────────────────────────
export function WatcherForm({
onBack,
prefillFirstName = "",
prefillLastName = "",
prefillEmail = "",
isLoggedIn = false,
}: Props) {
export function WatcherForm({ onBack, onSuccess }: Props) {
const { data: session } = authClient.useSession();
const sessionEmail = session?.user?.email ?? "";
const [data, setData] = useState({
firstName: prefillFirstName,
lastName: prefillLastName,
email: prefillEmail,
firstName: "",
lastName: "",
email: "",
phone: "",
birthdateDay: "",
birthdateMonth: "",
birthdateYear: "",
postcode: "",
birthdate: "",
extraQuestions: "",
});
const [errors, setErrors] = useState<WatcherErrors>({});
@@ -263,40 +55,21 @@ export function WatcherForm({
const [guestErrors, setGuestErrors] = useState<GuestErrors[]>([]);
const [giftAmount, setGiftAmount] = useState(0);
// Modal state: shown after successful registration while we fetch checkout URL
const [modalState, setModalState] = useState<{
prefillName: string;
prefillEmail: string;
checkoutUrl: string;
} | null>(null);
useEffect(() => {
if (sessionEmail) {
setData((prev) => ({ ...prev, email: sessionEmail }));
}
}, [sessionEmail]);
const submitMutation = useMutation({
...orpc.submitRegistration.mutationOptions(),
onSuccess: async (result) => {
if (!result.managementToken) return;
try {
const redirectUrl = isLoggedIn
? `${window.location.origin}/account?topup=success`
: undefined;
const checkout = await client.getCheckoutUrl({
token: result.managementToken,
redirectUrl,
});
if (isLoggedIn) {
// Already logged in — skip the account-creation modal, go straight to checkout
window.location.href = checkout.checkoutUrl;
} else {
// Show the account-creation modal before redirecting to checkout
setModalState({
prefillName:
`${data.firstName.trim()} ${data.lastName.trim()}`.trim(),
prefillEmail: data.email.trim(),
checkoutUrl: checkout.checkoutUrl,
});
}
} catch (error) {
console.error("Checkout error:", error);
toast.error("Er is iets misgegaan bij het aanmaken van de betaling");
onSuccess: (result) => {
if (result.managementToken) {
onSuccess(
result.managementToken,
data.email.trim(),
`${data.firstName.trim()} ${data.lastName.trim()}`.trim(),
);
}
},
onError: (error) => {
@@ -304,14 +77,21 @@ export function WatcherForm({
},
});
function getBirthdate(): string {
const { birthdateYear, birthdateMonth, birthdateDay } = data;
if (!birthdateYear || !birthdateMonth || !birthdateDay) return "";
return `${birthdateYear}-${birthdateMonth.padStart(2, "0")}-${birthdateDay.padStart(2, "0")}`;
}
function validate(): boolean {
const birthdate = getBirthdate();
const fieldErrs: WatcherErrors = {
firstName: validateTextField(data.firstName, true, "Voornaam"),
lastName: validateTextField(data.lastName, true, "Achternaam"),
email: validateEmail(data.email),
phone: validatePhone(data.phone),
postcode: !data.postcode.trim() ? "Postcode is verplicht" : undefined,
birthdate: !data.birthdate ? "Geboortedatum is verplicht" : undefined,
birthdate: validateBirthdate(birthdate),
postcode: validatePostcode(data.postcode),
};
setErrors(fieldErrs);
setTouched({
@@ -319,8 +99,8 @@ export function WatcherForm({
lastName: true,
email: true,
phone: true,
postcode: true,
birthdate: true,
postcode: true,
});
const { errors: gErrs, valid: gValid } = validateGuests(guests);
setGuestErrors(gErrs);
@@ -338,14 +118,6 @@ export function WatcherForm({
lastName: validateTextField(value, true, "Achternaam"),
email: validateEmail(value),
phone: validatePhone(value),
postcode:
name === "postcode" && !value.trim()
? "Postcode is verplicht"
: undefined,
birthdate:
name === "birthdate" && !value
? "Geboortedatum is verplicht"
: undefined,
};
setErrors((prev) => ({ ...prev, [name]: errMap[name] }));
}
@@ -361,14 +133,6 @@ export function WatcherForm({
lastName: validateTextField(value, true, "Achternaam"),
email: validateEmail(value),
phone: validatePhone(value),
postcode:
name === "postcode" && !value.trim()
? "Postcode is verplicht"
: undefined,
birthdate:
name === "birthdate" && !value
? "Geboortedatum is verplicht"
: undefined,
};
setErrors((prev) => ({ ...prev, [name]: errMap[name] }));
}
@@ -417,8 +181,8 @@ export function WatcherForm({
lastName: data.lastName.trim(),
email: data.email.trim(),
phone: data.phone.trim() || undefined,
birthdate: getBirthdate(),
postcode: data.postcode.trim(),
birthdate: data.birthdate,
registrationType: "watcher",
guests: guests.map((g) => ({
firstName: g.firstName.trim(),
@@ -437,19 +201,6 @@ export function WatcherForm({
return (
<div>
{/* Account-creation interstitial modal */}
{modalState && (
<AccountModal
prefillName={modalState.prefillName}
prefillEmail={modalState.prefillEmail}
onDone={() => {
const url = modalState.checkoutUrl;
setModalState(null);
window.location.href = url;
}}
/>
)}
{/* Back + type header */}
<div className="mb-8 flex items-center gap-4">
<button
@@ -506,7 +257,7 @@ export function WatcherForm({
<p className="font-semibold text-white">Drinkkaart inbegrepen</p>
<p className="text-sm text-white/70">
Je betaald bij registratie
<strong className="text-teal-300">5</strong> (+ 2 per
<strong className="text-teal-300"> 5</strong> (+ 5 per
medebezoeker) dat gaat naar je drinkkaart.
{guests.length > 0 && (
<span className="ml-1 font-semibold text-teal-300">
@@ -579,15 +330,15 @@ export function WatcherForm({
id="w-email"
name="email"
value={data.email}
onChange={isLoggedIn ? undefined : handleChange}
onBlur={isLoggedIn ? undefined : handleBlur}
readOnly={isLoggedIn}
onChange={sessionEmail ? undefined : handleChange}
onBlur={sessionEmail ? undefined : handleBlur}
readOnly={!!sessionEmail}
placeholder="jouw@email.be"
autoComplete="email"
inputMode="email"
aria-required="true"
aria-invalid={touched.email && !!errors.email}
className={`${inputCls(!!touched.email && !!errors.email)}${isLoggedIn ? "cursor-not-allowed opacity-60" : ""}`}
className={`${inputCls(!!touched.email && !!errors.email)}${sessionEmail ? "cursor-not-allowed opacity-75" : ""}`}
/>
{touched.email && errors.email && (
<span className="text-red-300 text-sm" role="alert">
@@ -620,8 +371,120 @@ export function WatcherForm({
</div>
</div>
{/* Postcode + Birthdate row */}
{/* Birthdate + Postcode row */}
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div className="flex flex-col gap-2">
<p className="text-white text-xl">
Geboortedatum <span className="text-red-300">*</span>
</p>
<fieldset className="m-0 flex gap-2 border-0 p-0">
<legend className="sr-only">Geboortedatum</legend>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="w-birthdateDay" className="sr-only">
Dag
</label>
<select
id="w-birthdateDay"
value={data.birthdateDay}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateDay: e.target.value,
}))
}
aria-label="Dag"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
DD
</option>
{Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
<option key={d} value={String(d)} className="bg-[#214e51]">
{String(d).padStart(2, "0")}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="w-birthdateMonth" className="sr-only">
Maand
</label>
<select
id="w-birthdateMonth"
value={data.birthdateMonth}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateMonth: e.target.value,
}))
}
aria-label="Maand"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
MM
</option>
{[
"Jan",
"Feb",
"Mrt",
"Apr",
"Mei",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
].map((m, i) => (
<option
key={m}
value={String(i + 1)}
className="bg-[#214e51]"
>
{m}
</option>
))}
</select>
</div>
<div className="flex flex-1 flex-col gap-1">
<label htmlFor="w-birthdateYear" className="sr-only">
Jaar
</label>
<select
id="w-birthdateYear"
value={data.birthdateYear}
onChange={(e) =>
setData((prev) => ({
...prev,
birthdateYear: e.target.value,
}))
}
aria-label="Jaar"
className={`border-b bg-transparent pb-2 text-lg text-white transition-colors focus:outline-none ${touched.birthdate && errors.birthdate ? "border-red-400" : "border-white/30 focus:border-white"}`}
>
<option value="" className="bg-[#214e51]">
JJJJ
</option>
{Array.from(
{ length: 100 },
(_, i) => new Date().getFullYear() - i,
).map((y) => (
<option key={y} value={String(y)} className="bg-[#214e51]">
{y}
</option>
))}
</select>
</div>
</fieldset>
{touched.birthdate && errors.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors.birthdate}
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label htmlFor="w-postcode" className="text-white text-xl">
Postcode <span className="text-red-300">*</span>
@@ -633,8 +496,9 @@ export function WatcherForm({
value={data.postcode}
onChange={handleChange}
onBlur={handleBlur}
placeholder="1234 AB"
placeholder="bv. 9000"
autoComplete="postal-code"
inputMode="numeric"
aria-required="true"
aria-invalid={touched.postcode && !!errors.postcode}
className={inputCls(!!touched.postcode && !!errors.postcode)}
@@ -645,27 +509,6 @@ export function WatcherForm({
</span>
)}
</div>
<div className="flex flex-col gap-2">
<label htmlFor="w-birthdate" className="text-white text-xl">
Geboortedatum <span className="text-red-300">*</span>
</label>
<input
type="date"
id="w-birthdate"
name="birthdate"
value={data.birthdate}
onChange={handleChange}
onBlur={handleBlur}
autoComplete="bday"
aria-invalid={touched.birthdate && !!errors.birthdate}
className={`${inputCls(!!touched.birthdate && !!errors.birthdate)} [color-scheme:dark]`}
/>
{touched.birthdate && errors.birthdate && (
<span className="text-red-300 text-sm" role="alert">
{errors.birthdate}
</span>
)}
</div>
</div>
{/* Guests */}
@@ -736,7 +579,7 @@ export function WatcherForm({
Bezig...
</span>
) : (
"Bevestigen & betalen"
"Bevestigen"
)}
</button>
<a

View File

@@ -1,3 +1,3 @@
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({});
export const authClient = createAuthClient();

View File

@@ -0,0 +1,12 @@
/**
* Single source-of-truth for when registration opens.
* Change this date to reschedule — all gating logic imports from here.
*/
export const REGISTRATION_OPENS_AT = new Date("2026-03-16T19:00:00+01:00");
/**
* Feature flag for the registration countdown gate.
* Set to `false` to bypass the countdown and always show the registration form.
* Set to `true` to enforce the countdown until REGISTRATION_OPENS_AT.
*/
export const COUNTDOWN_ENABLED = true;

View File

@@ -6,8 +6,9 @@
// ---------------------------------------------------------------------------
export const DRINK_CARD_BASE = 5; // €5 for primary registrant
export const DRINK_CARD_PER_GUEST = 2; // €2 per additional guest
export const DRINK_CARD_PER_GUEST = 5; // €5 per additional guest (same as primary)
export const MAX_GUESTS = 9;
export const MAX_WATCHERS = 70; // max total watcher spots (people, not registrations)
/** Returns drink card value in euros for a given number of extra guests. */
export function calculateDrinkCard(guestCount: number): number {
@@ -92,6 +93,22 @@ export function validatePhone(value: string): string | undefined {
return undefined;
}
export function validateBirthdate(value: string): string | undefined {
if (!value.trim()) return "Geboortedatum is verplicht";
// Expect YYYY-MM-DD format
if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
return "Voer een geldige geboortedatum in";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "Voer een geldige geboortedatum in";
if (date > new Date()) return "Geboortedatum mag niet in de toekomst liggen";
return undefined;
}
export function validatePostcode(value: string): string | undefined {
if (!value.trim()) return "Postcode is verplicht";
return undefined;
}
/** Validates all guests and returns errors array + overall validity flag. */
export function validateGuests(guests: GuestEntry[]): {
errors: GuestErrors[];
@@ -108,8 +125,8 @@ export function validateGuests(guests: GuestEntry[]): {
g.phone.trim() && !/^[\d\s\-+()]{10,}$/.test(g.phone.replace(/\s/g, ""))
? "Voer een geldig telefoonnummer in"
: undefined,
birthdate: !g.birthdate.trim() ? "Geboortedatum is verplicht" : undefined,
postcode: !g.postcode.trim() ? "Postcode is verplicht" : undefined,
birthdate: validateBirthdate(g.birthdate),
postcode: validatePostcode(g.postcode),
}));
const valid = !errors.some((e) => Object.values(e).some(Boolean));
return { errors, valid };

View File

@@ -0,0 +1,48 @@
import { useEffect, useState } from "react";
import { COUNTDOWN_ENABLED, REGISTRATION_OPENS_AT } from "./opening";
interface RegistrationOpenState {
isOpen: boolean;
days: number;
hours: number;
minutes: number;
seconds: number;
}
function compute(): RegistrationOpenState {
if (!COUNTDOWN_ENABLED) {
return { isOpen: true, days: 0, hours: 0, minutes: 0, seconds: 0 };
}
const diff = REGISTRATION_OPENS_AT.getTime() - Date.now();
if (diff <= 0) {
return { isOpen: true, days: 0, hours: 0, minutes: 0, seconds: 0 };
}
const totalSeconds = Math.floor(diff / 1000);
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return { isOpen: false, days, hours, minutes, seconds };
}
/**
* Returns live countdown state to {@link REGISTRATION_OPENS_AT}.
* Ticks every second; clears the interval once registration is open.
*/
export function useRegistrationOpen(): RegistrationOpenState {
const [state, setState] = useState<RegistrationOpenState>(compute);
useEffect(() => {
if (state.isOpen) return;
const id = setInterval(() => {
const next = compute();
setState(next);
if (next.isOpen) clearInterval(id);
}, 1000);
return () => clearInterval(id);
}, [state.isOpen]);
return state;
}

View File

@@ -10,8 +10,11 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as TermsRouteImport } from './routes/terms'
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
import { Route as PrivacyRouteImport } from './routes/privacy'
import { Route as LoginRouteImport } from './routes/login'
import { Route as KampRouteImport } from './routes/kamp'
import { Route as ForgotPasswordRouteImport } from './routes/forgot-password'
import { Route as DrinkkaartRouteImport } from './routes/drinkkaart'
import { Route as ContactRouteImport } from './routes/contact'
import { Route as AccountRouteImport } from './routes/account'
@@ -19,8 +22,9 @@ import { Route as IndexRouteImport } from './routes/index'
import { Route as AdminIndexRouteImport } from './routes/admin/index'
import { Route as ManageTokenRouteImport } from './routes/manage.$token'
import { Route as AdminDrinkkaartRouteImport } from './routes/admin/drinkkaart'
import { Route as ApiWebhookLemonsqueezyRouteImport } from './routes/api/webhook/lemonsqueezy'
import { Route as ApiWebhookMollieRouteImport } from './routes/api/webhook/mollie'
import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc/$'
import { Route as ApiCronRemindersRouteImport } from './routes/api/cron/reminders'
import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
const TermsRoute = TermsRouteImport.update({
@@ -28,6 +32,11 @@ const TermsRoute = TermsRouteImport.update({
path: '/terms',
getParentRoute: () => rootRouteImport,
} as any)
const ResetPasswordRoute = ResetPasswordRouteImport.update({
id: '/reset-password',
path: '/reset-password',
getParentRoute: () => rootRouteImport,
} as any)
const PrivacyRoute = PrivacyRouteImport.update({
id: '/privacy',
path: '/privacy',
@@ -38,6 +47,16 @@ const LoginRoute = LoginRouteImport.update({
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
const KampRoute = KampRouteImport.update({
id: '/kamp',
path: '/kamp',
getParentRoute: () => rootRouteImport,
} as any)
const ForgotPasswordRoute = ForgotPasswordRouteImport.update({
id: '/forgot-password',
path: '/forgot-password',
getParentRoute: () => rootRouteImport,
} as any)
const DrinkkaartRoute = DrinkkaartRouteImport.update({
id: '/drinkkaart',
path: '/drinkkaart',
@@ -73,9 +92,9 @@ const AdminDrinkkaartRoute = AdminDrinkkaartRouteImport.update({
path: '/admin/drinkkaart',
getParentRoute: () => rootRouteImport,
} as any)
const ApiWebhookLemonsqueezyRoute = ApiWebhookLemonsqueezyRouteImport.update({
id: '/api/webhook/lemonsqueezy',
path: '/api/webhook/lemonsqueezy',
const ApiWebhookMollieRoute = ApiWebhookMollieRouteImport.update({
id: '/api/webhook/mollie',
path: '/api/webhook/mollie',
getParentRoute: () => rootRouteImport,
} as any)
const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
@@ -83,6 +102,11 @@ const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
path: '/api/rpc/$',
getParentRoute: () => rootRouteImport,
} as any)
const ApiCronRemindersRoute = ApiCronRemindersRouteImport.update({
id: '/api/cron/reminders',
path: '/api/cron/reminders',
getParentRoute: () => rootRouteImport,
} as any)
const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({
id: '/api/auth/$',
path: '/api/auth/$',
@@ -94,30 +118,38 @@ export interface FileRoutesByFullPath {
'/account': typeof AccountRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/forgot-password': typeof ForgotPasswordRoute
'/kamp': typeof KampRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/reset-password': typeof ResetPasswordRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin/': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/cron/reminders': typeof ApiCronRemindersRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
'/api/webhook/mollie': typeof ApiWebhookMollieRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/account': typeof AccountRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/forgot-password': typeof ForgotPasswordRoute
'/kamp': typeof KampRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/reset-password': typeof ResetPasswordRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/cron/reminders': typeof ApiCronRemindersRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
'/api/webhook/mollie': typeof ApiWebhookMollieRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
@@ -125,15 +157,19 @@ export interface FileRoutesById {
'/account': typeof AccountRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/forgot-password': typeof ForgotPasswordRoute
'/kamp': typeof KampRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/reset-password': typeof ResetPasswordRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin/': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/cron/reminders': typeof ApiCronRemindersRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
'/api/webhook/mollie': typeof ApiWebhookMollieRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -142,45 +178,57 @@ export interface FileRouteTypes {
| '/account'
| '/contact'
| '/drinkkaart'
| '/forgot-password'
| '/kamp'
| '/login'
| '/privacy'
| '/reset-password'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin/'
| '/api/auth/$'
| '/api/cron/reminders'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
| '/api/webhook/mollie'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
| '/account'
| '/contact'
| '/drinkkaart'
| '/forgot-password'
| '/kamp'
| '/login'
| '/privacy'
| '/reset-password'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin'
| '/api/auth/$'
| '/api/cron/reminders'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
| '/api/webhook/mollie'
id:
| '__root__'
| '/'
| '/account'
| '/contact'
| '/drinkkaart'
| '/forgot-password'
| '/kamp'
| '/login'
| '/privacy'
| '/reset-password'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin/'
| '/api/auth/$'
| '/api/cron/reminders'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
| '/api/webhook/mollie'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -188,15 +236,19 @@ export interface RootRouteChildren {
AccountRoute: typeof AccountRoute
ContactRoute: typeof ContactRoute
DrinkkaartRoute: typeof DrinkkaartRoute
ForgotPasswordRoute: typeof ForgotPasswordRoute
KampRoute: typeof KampRoute
LoginRoute: typeof LoginRoute
PrivacyRoute: typeof PrivacyRoute
ResetPasswordRoute: typeof ResetPasswordRoute
TermsRoute: typeof TermsRoute
AdminDrinkkaartRoute: typeof AdminDrinkkaartRoute
ManageTokenRoute: typeof ManageTokenRoute
AdminIndexRoute: typeof AdminIndexRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
ApiCronRemindersRoute: typeof ApiCronRemindersRoute
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
ApiWebhookLemonsqueezyRoute: typeof ApiWebhookLemonsqueezyRoute
ApiWebhookMollieRoute: typeof ApiWebhookMollieRoute
}
declare module '@tanstack/react-router' {
@@ -208,6 +260,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof TermsRouteImport
parentRoute: typeof rootRouteImport
}
'/reset-password': {
id: '/reset-password'
path: '/reset-password'
fullPath: '/reset-password'
preLoaderRoute: typeof ResetPasswordRouteImport
parentRoute: typeof rootRouteImport
}
'/privacy': {
id: '/privacy'
path: '/privacy'
@@ -222,6 +281,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
'/kamp': {
id: '/kamp'
path: '/kamp'
fullPath: '/kamp'
preLoaderRoute: typeof KampRouteImport
parentRoute: typeof rootRouteImport
}
'/forgot-password': {
id: '/forgot-password'
path: '/forgot-password'
fullPath: '/forgot-password'
preLoaderRoute: typeof ForgotPasswordRouteImport
parentRoute: typeof rootRouteImport
}
'/drinkkaart': {
id: '/drinkkaart'
path: '/drinkkaart'
@@ -271,11 +344,11 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AdminDrinkkaartRouteImport
parentRoute: typeof rootRouteImport
}
'/api/webhook/lemonsqueezy': {
id: '/api/webhook/lemonsqueezy'
path: '/api/webhook/lemonsqueezy'
fullPath: '/api/webhook/lemonsqueezy'
preLoaderRoute: typeof ApiWebhookLemonsqueezyRouteImport
'/api/webhook/mollie': {
id: '/api/webhook/mollie'
path: '/api/webhook/mollie'
fullPath: '/api/webhook/mollie'
preLoaderRoute: typeof ApiWebhookMollieRouteImport
parentRoute: typeof rootRouteImport
}
'/api/rpc/$': {
@@ -285,6 +358,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiRpcSplatRouteImport
parentRoute: typeof rootRouteImport
}
'/api/cron/reminders': {
id: '/api/cron/reminders'
path: '/api/cron/reminders'
fullPath: '/api/cron/reminders'
preLoaderRoute: typeof ApiCronRemindersRouteImport
parentRoute: typeof rootRouteImport
}
'/api/auth/$': {
id: '/api/auth/$'
path: '/api/auth/$'
@@ -300,15 +380,19 @@ const rootRouteChildren: RootRouteChildren = {
AccountRoute: AccountRoute,
ContactRoute: ContactRoute,
DrinkkaartRoute: DrinkkaartRoute,
ForgotPasswordRoute: ForgotPasswordRoute,
KampRoute: KampRoute,
LoginRoute: LoginRoute,
PrivacyRoute: PrivacyRoute,
ResetPasswordRoute: ResetPasswordRoute,
TermsRoute: TermsRoute,
AdminDrinkkaartRoute: AdminDrinkkaartRoute,
ManageTokenRoute: ManageTokenRoute,
AdminIndexRoute: AdminIndexRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
ApiCronRemindersRoute: ApiCronRemindersRoute,
ApiRpcSplatRoute: ApiRpcSplatRoute,
ApiWebhookLemonsqueezyRoute: ApiWebhookLemonsqueezyRoute,
ApiWebhookMollieRoute: ApiWebhookMollieRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)

View File

@@ -1,3 +1,4 @@
import type { EmailMessage } from "@kk/api/email-queue";
import { QueryClientProvider } from "@tanstack/react-query";
import { createRouter as createTanStackRouter } from "@tanstack/react-router";
@@ -6,6 +7,18 @@ import Loader from "./components/loader";
import { routeTree } from "./routeTree.gen";
import { orpc, queryClient } from "./utils/orpc";
// Minimal CF Queue binding shape needed for type inference
type Queue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
sendBatch(
messages: Array<{ body: EmailMessage }>,
options?: { contentType?: string },
): Promise<void>;
};
export const getRouter = () => {
const router = createTanStackRouter({
routeTree,
@@ -26,3 +39,9 @@ declare module "@tanstack/react-router" {
router: ReturnType<typeof getRouter>;
}
}
declare module "@tanstack/router-core" {
interface Register {
server: { requestContext: { emailQueue?: Queue } };
}
}

View File

@@ -128,7 +128,7 @@ export const Route = createRootRouteWithContext<RouterAppContext>()({
name: "Kunstenkamp Open Mic Night",
description:
"Een avond vol muziek, theater, dans, woordkunst en meer. Iedereen is welkom om zijn of haar talent te tonen.",
startDate: "2026-04-18T19:00:00+02:00",
startDate: "2026-04-24T19:30:00+02:00",
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
organizer: {
@@ -142,7 +142,7 @@ export const Route = createRootRouteWithContext<RouterAppContext>()({
price: "0",
priceCurrency: "EUR",
availability: "https://schema.org/InStock",
validFrom: "2026-03-01T00:00:00+02:00",
validFrom: "2026-03-16T19:00:00+01:00",
},
}),
},

View File

@@ -1,4 +1,4 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import {
Calendar,
@@ -74,6 +74,22 @@ function AccountPage() {
const [showQr, setShowQr] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
const checkoutMutation = useMutation({
mutationFn: async (token: string) => {
const result = await client.getCheckoutUrl({
token,
redirectUrl: `${window.location.origin}/account?topup=success`,
});
return result;
},
onSuccess: (data) => {
window.location.href = data.checkoutUrl;
},
onError: () => {
toast.error("Er is iets misgegaan bij het aanmaken van de betaling");
},
});
const sessionQuery = useQuery({
queryKey: ["session"],
queryFn: () => authClient.getSession(),
@@ -90,7 +106,7 @@ function AccountPage() {
orpc.drinkkaart.getMyDrinkkaart.queryOptions(),
);
const registrationQuery = useQuery(orpc.getMyRegistrations.queryOptions());
const registrationQuery = useQuery(orpc.getMyRegistration.queryOptions());
// Handle topup=success redirect (from Lemon Squeezy returning to /account)
useEffect(() => {
@@ -128,7 +144,7 @@ function AccountPage() {
| { name?: string; email?: string }
| undefined;
const registrations = registrationQuery.data ?? [];
const registration = registrationQuery.data;
const drinkkaart = drinkkaartQuery.data;
const isLoading =
@@ -170,122 +186,172 @@ function AccountPage() {
Mijn Inschrijving
</h2>
{registrations.length > 0 ? (
<div className="flex flex-col gap-4">
{registrations.map((registration) => (
<div
key={registration.id}
className="rounded-2xl border border-white/10 bg-white/5 p-6"
>
{/* Type badge */}
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-2">
{registration.registrationType === "performer" ? (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/20 px-3 py-1 font-medium text-amber-300 text-sm">
<Music className="h-3.5 w-3.5" />
Artiest
</span>
) : (
<span className="inline-flex items-center gap-1.5 rounded-full bg-teal-500/20 px-3 py-1 font-medium text-sm text-teal-300">
<Users className="h-3.5 w-3.5" />
Bezoeker
</span>
)}
</div>
{(registration.registrationType !== "performer" ||
(registration.giftAmount ?? 0) > 0) && (
<PaymentBadge status={registration.paymentStatus} />
)}
</div>
{/* Name */}
<p className="mb-1 font-medium text-lg text-white">
{registration.firstName} {registration.lastName}
</p>
{/* Art form (performer only) */}
{registration.registrationType === "performer" &&
registration.artForm && (
<p className="mb-1 text-sm text-white/60">
Kunstvorm:{" "}
<span className="text-white/80">
{registration.artForm}
</span>
</p>
)}
{/* Guests (watcher only) */}
{registration.registrationType === "watcher" &&
registration.guests.length > 0 && (
<p className="mb-1 text-sm text-white/60">
{registration.guests.length + 1} personen (jij +{" "}
{registration.guests.length} gast
{registration.guests.length > 1 ? "en" : ""})
</p>
)}
{/* Drink card value */}
{registration.registrationType === "watcher" &&
(registration.drinkCardValue ?? 0) > 0 && (
<p className="mb-1 text-sm text-white/60">
Drinkkaart:{" "}
<span className="text-white/80">
{registration.drinkCardValue}
</span>
</p>
)}
{/* Gift */}
{(registration.giftAmount ?? 0) > 0 && (
<p className="mb-1 text-sm text-white/60">
Gift:{" "}
<span className="text-white/80">
{(registration.giftAmount ?? 0) / 100}
</span>
</p>
)}
{/* Date */}
<p className="mt-3 text-white/40 text-xs">
Ingeschreven op{" "}
{new Date(registration.createdAt).toLocaleDateString(
"nl-BE",
{
day: "numeric",
month: "long",
year: "numeric",
},
)}
</p>
{/* Action */}
{registration.managementToken && (
<div className="mt-5">
<Link
to="/manage/$token"
params={{ token: registration.managementToken }}
className="inline-flex items-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm text-white transition-colors hover:bg-white/20"
>
Beheer inschrijving
<svg
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
/>
</svg>
</Link>
</div>
{registration ? (
<div className="rounded-2xl border border-white/10 bg-white/5 p-6">
{/* Type badge */}
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-2">
{registration.registrationType === "performer" ? (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/20 px-3 py-1 font-medium text-amber-300 text-sm">
<Music className="h-3.5 w-3.5" />
Artiest
</span>
) : (
<span className="inline-flex items-center gap-1.5 rounded-full bg-teal-500/20 px-3 py-1 font-medium text-sm text-teal-300">
<Users className="h-3.5 w-3.5" />
Bezoeker
</span>
)}
</div>
))}
{/* Only show a payment badge when there's actually something to pay:
watchers always have a drinkcard fee; anyone with a gift amount does too.
Performers with no gift have nothing to pay → hide the badge. */}
{(registration.registrationType === "watcher" ||
(registration.giftAmount ?? 0) > 0) && (
<PaymentBadge status={registration.paymentStatus} />
)}
</div>
{/* Name */}
<p className="mb-1 font-medium text-lg text-white">
{registration.firstName} {registration.lastName}
</p>
{/* Art form (performer only) */}
{registration.registrationType === "performer" &&
registration.artForm && (
<p className="mb-1 text-sm text-white/60">
Kunstvorm:{" "}
<span className="text-white/80">
{registration.artForm}
</span>
</p>
)}
{/* Guests (watcher only) */}
{registration.registrationType === "watcher" &&
registration.guests.length > 0 && (
<p className="mb-1 text-sm text-white/60">
{registration.guests.length + 1} personen (jij +{" "}
{registration.guests.length} gast
{registration.guests.length > 1 ? "en" : ""})
</p>
)}
{/* Drink card value */}
{registration.registrationType === "watcher" &&
(registration.drinkCardValue ?? 0) > 0 && (
<p className="mb-1 text-sm text-white/60">
Drinkkaart:{" "}
<span className="text-white/80">
{registration.drinkCardValue}
</span>
</p>
)}
{/* Gift */}
{(registration.giftAmount ?? 0) > 0 && (
<p className="mb-1 text-sm text-white/60">
Gift:{" "}
<span className="text-white/80">
{(registration.giftAmount ?? 0) / 100}
</span>
</p>
)}
{/* Date */}
<p className="mt-3 text-white/40 text-xs">
Ingeschreven op{" "}
{new Date(registration.createdAt).toLocaleDateString(
"nl-BE",
{
day: "numeric",
month: "long",
year: "numeric",
},
)}
</p>
{/* Action */}
{registration.managementToken && (
<div className="mt-5">
<Link
to="/manage/$token"
params={{ token: registration.managementToken }}
className="inline-flex items-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm text-white transition-colors hover:bg-white/20"
>
Beheer inschrijving
<svg
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
/>
</svg>
</Link>
</div>
)}
{/* Pay now CTA — shown for watchers with pending payment */}
{registration.registrationType === "watcher" &&
registration.paymentStatus === "pending" &&
registration.managementToken && (
<div className="mt-5 rounded-lg border border-teal-400/30 bg-teal-400/10 p-4">
<p className="mb-3 text-sm text-white/80">
Je inschrijving is bevestigd maar de betaling staat nog
open. Betaal nu om je Drinkkaart te activeren.
</p>
<button
type="button"
disabled={checkoutMutation.isPending}
onClick={() =>
checkoutMutation.mutate(
registration.managementToken ?? "",
)
}
className="inline-flex items-center gap-2 rounded-lg bg-white px-4 py-2 font-semibold text-[#214e51] text-sm transition-colors hover:bg-white/90 disabled:cursor-not-allowed disabled:opacity-50"
>
{checkoutMutation.isPending ? (
<>
<svg
className="h-4 w-4 animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
aria-hidden="true"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
Laden...
</>
) : (
<>
<Wallet className="h-4 w-4" />
Betaal nu
</>
)}
</button>
</div>
)}
</div>
) : (
<div className="rounded-2xl border border-white/10 bg-white/5 p-6">

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
import { runSendReminders } from "@kk/api/routers/index";
import { env } from "@kk/env/server";
import { createFileRoute } from "@tanstack/react-router";
async function handleCronReminders({ request }: { request: Request }) {
const secret = env.CRON_SECRET;
if (!secret) {
return new Response("CRON_SECRET not configured", { status: 500 });
}
// Accept the secret via Authorization header (Bearer) or JSON body
const authHeader = request.headers.get("Authorization");
let providedSecret: string | null = null;
if (authHeader?.startsWith("Bearer ")) {
providedSecret = authHeader.slice(7);
} else {
try {
const body = await request.json();
providedSecret = (body as { secret?: string }).secret ?? null;
} catch {
// ignore parse errors
}
}
if (!providedSecret || providedSecret !== secret) {
return new Response("Unauthorized", { status: 401 });
}
const result = await runSendReminders();
return Response.json(result);
}
export const Route = createFileRoute("/api/cron/reminders")({
server: {
handlers: {
POST: handleCronReminders,
},
},
});

View File

@@ -1,4 +1,5 @@
import { createContext } from "@kk/api/context";
import type { EmailMessage } from "@kk/api/email-queue";
import { appRouter } from "@kk/api/routers/index";
import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { OpenAPIReferencePlugin } from "@orpc/openapi/plugins";
@@ -7,6 +8,18 @@ import { RPCHandler } from "@orpc/server/fetch";
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { createFileRoute } from "@tanstack/react-router";
// Minimal CF Queue binding shape — mirrors the declaration in router.tsx / context.ts
type Queue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
sendBatch(
messages: Array<{ body: EmailMessage }>,
options?: { contentType?: string },
): Promise<void>;
};
const rpcHandler = new RPCHandler(appRouter, {
interceptors: [
onError((error) => {
@@ -28,16 +41,21 @@ const apiHandler = new OpenAPIHandler(appRouter, {
],
});
async function handle({ request }: { request: Request }) {
const rpcResult = await rpcHandler.handle(request, {
async function handle(ctx: { request: Request; context?: unknown }) {
// emailQueue is threaded in via the fetch wrapper in server.ts
const emailQueue = (ctx.context as { emailQueue?: Queue } | undefined)
?.emailQueue;
const context = await createContext({ req: ctx.request, emailQueue });
const rpcResult = await rpcHandler.handle(ctx.request, {
prefix: "/api/rpc",
context: await createContext({ req: request }),
context,
});
if (rpcResult.response) return rpcResult.response;
const apiResult = await apiHandler.handle(request, {
const apiResult = await apiHandler.handle(ctx.request, {
prefix: "/api/rpc/api-reference",
context: await createContext({ req: request }),
context,
});
if (apiResult.response) return apiResult.response;

View File

@@ -1,4 +1,6 @@
import { createHmac, randomUUID } from "node:crypto";
import { randomUUID } from "node:crypto";
import { sendPaymentConfirmationEmail } from "@kk/api/email";
import type { EmailMessage } from "@kk/api/email-queue";
import { creditRegistrationToAccount } from "@kk/api/routers/index";
import { db } from "@kk/db";
import { drinkkaart, drinkkaartTopup, registration } from "@kk/db/schema";
@@ -7,101 +9,122 @@ import { env } from "@kk/env/server";
import { createFileRoute } from "@tanstack/react-router";
import { and, eq } from "drizzle-orm";
// LemonSqueezy webhook payload types (order_created event)
interface LemonSqueezyOrderCreatedPayload {
meta: {
event_name: string;
custom_data?: {
type?: string;
registration_token?: string;
drinkkaartId?: string;
userId?: string;
};
};
data: {
id: string;
attributes: {
status: string;
customer_id: number;
total: number; // amount in cents
};
// Minimal CF Queue binding shape used to enqueue emails
type EmailQueue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
};
// Mollie payment object (relevant fields only)
interface MolliePayment {
id: string;
status: string;
amount: { value: string; currency: string };
customerId?: string;
metadata?: {
registration_token?: string;
type?: string;
drinkkaartId?: string;
userId?: string;
};
}
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string,
): boolean {
const hmac = createHmac("sha256", secret);
hmac.update(payload);
const digest = hmac.digest("hex");
return signature === digest;
async function fetchMolliePayment(paymentId: string): Promise<MolliePayment> {
const response = await fetch(
`https://api.mollie.com/v2/payments/${paymentId}`,
{
headers: {
Authorization: `Bearer ${env.MOLLIE_API_KEY}`,
},
},
);
if (!response.ok) {
throw new Error(
`Failed to fetch Mollie payment ${paymentId}: ${response.status}`,
);
}
return response.json() as Promise<MolliePayment>;
}
async function handleWebhook({ request }: { request: Request }) {
if (!env.LEMON_SQUEEZY_WEBHOOK_SECRET) {
console.error("LEMON_SQUEEZY_WEBHOOK_SECRET not configured");
async function handleWebhook({
request,
context,
}: {
request: Request;
context?: unknown;
}) {
const emailQueue = (context as { emailQueue?: EmailQueue } | undefined)
?.emailQueue;
if (!env.MOLLIE_API_KEY) {
console.error("MOLLIE_API_KEY not configured");
return new Response("Payment provider not configured", { status: 500 });
}
const payload = await request.text();
const signature = request.headers.get("X-Signature");
if (!signature) {
return new Response("Missing signature", { status: 401 });
}
if (
!verifyWebhookSignature(
payload,
signature,
env.LEMON_SQUEEZY_WEBHOOK_SECRET,
)
) {
return new Response("Invalid signature", { status: 401 });
}
let event: LemonSqueezyOrderCreatedPayload;
// Mollie sends application/x-www-form-urlencoded with a single "id" field
let paymentId: string | null = null;
try {
event = JSON.parse(payload) as LemonSqueezyOrderCreatedPayload;
const body = await request.text();
const params = new URLSearchParams(body);
paymentId = params.get("id");
} catch {
return new Response("Invalid JSON", { status: 400 });
return new Response("Invalid request body", { status: 400 });
}
// Only handle order_created events
if (event.meta.event_name !== "order_created") {
return new Response("Event ignored", { status: 200 });
if (!paymentId) {
return new Response("Missing payment id", { status: 400 });
}
const orderId = event.data.id;
const customerId = String(event.data.attributes.customer_id);
const amountCents = event.data.attributes.total;
const customData = event.meta.custom_data;
// Fetch-to-verify: retrieve the actual payment from Mollie to confirm its
// status. A malicious webhook cannot fake a paid status this way.
let payment: MolliePayment;
try {
payment = await fetchMolliePayment(paymentId);
} catch (err) {
console.error("Failed to fetch Mollie payment:", err);
return new Response("Failed to fetch payment", { status: 500 });
}
// Only process paid payments
if (payment.status !== "paid") {
return new Response("Payment status ignored", { status: 200 });
}
const metadata = payment.metadata;
try {
// -------------------------------------------------------------------------
// Branch: Drinkkaart top-up
// -------------------------------------------------------------------------
if (customData?.type === "drinkkaart_topup") {
const { drinkkaartId, userId } = customData;
if (metadata?.type === "drinkkaart_topup") {
const { drinkkaartId, userId } = metadata;
if (!drinkkaartId || !userId) {
console.error(
"Missing drinkkaartId or userId in drinkkaart_topup custom_data",
"Missing drinkkaartId or userId in drinkkaart_topup payment metadata",
);
return new Response("Missing drinkkaart data", { status: 400 });
}
// Amount in cents — Mollie returns e.g. "10.00"; parse to integer cents
const amountCents = Math.round(
Number.parseFloat(payment.amount.value) * 100,
);
// Idempotency: skip if already processed
const existing = await db
.select({ id: drinkkaartTopup.id })
.from(drinkkaartTopup)
.where(eq(drinkkaartTopup.lemonsqueezyOrderId, orderId))
.where(eq(drinkkaartTopup.molliePaymentId, payment.id))
.limit(1)
.then((r) => r[0]);
if (existing) {
console.log(`Drinkkaart topup already processed for order ${orderId}`);
console.log(
`Drinkkaart topup already processed for payment ${payment.id}`,
);
return new Response("OK", { status: 200 });
}
@@ -136,7 +159,7 @@ async function handleWebhook({ request }: { request: Request }) {
);
if (result.rowsAffected === 0) {
// Return 500 so LemonSqueezy retries; idempotency check prevents double-credit
// Return 500 so Mollie retries; idempotency check prevents double-credit
console.error(
`Drinkkaart optimistic lock conflict for ${drinkkaartId}`,
);
@@ -151,14 +174,14 @@ async function handleWebhook({ request }: { request: Request }) {
balanceBefore,
balanceAfter,
type: "payment",
lemonsqueezyOrderId: orderId,
molliePaymentId: payment.id,
adminId: null,
reason: null,
paidAt: new Date(),
});
console.log(
`Drinkkaart topup successful: drinkkaart=${drinkkaartId}, amount=${amountCents}c, order=${orderId}`,
`Drinkkaart topup successful: drinkkaart=${drinkkaartId}, amount=${amountCents}c, payment=${payment.id}`,
);
return new Response("OK", { status: 200 });
@@ -167,9 +190,9 @@ async function handleWebhook({ request }: { request: Request }) {
// -------------------------------------------------------------------------
// Branch: Registration payment
// -------------------------------------------------------------------------
const registrationToken = customData?.registration_token;
const registrationToken = metadata?.registration_token;
if (!registrationToken) {
console.error("No registration token in order custom_data");
console.error("No registration token in payment metadata");
return new Response("Missing registration token", { status: 400 });
}
@@ -192,16 +215,35 @@ async function handleWebhook({ request }: { request: Request }) {
.set({
paymentStatus: "paid",
paymentAmount: 0,
lemonsqueezyOrderId: orderId,
lemonsqueezyCustomerId: customerId,
molliePaymentId: payment.id,
paidAt: new Date(),
})
.where(eq(registration.managementToken, registrationToken));
console.log(
`Payment successful for registration ${registrationToken}, order ${orderId}`,
`Payment successful for registration ${registrationToken}, payment ${payment.id}`,
);
// Send payment confirmation email via queue when available, otherwise direct.
const confirmMsg: EmailMessage = {
type: "paymentConfirmation",
to: regRow.email,
firstName: regRow.firstName,
managementToken: regRow.managementToken ?? registrationToken,
drinkCardValue: regRow.drinkCardValue ?? undefined,
giftAmount: regRow.giftAmount ?? undefined,
};
if (emailQueue) {
await emailQueue.send(confirmMsg);
} else {
sendPaymentConfirmationEmail(confirmMsg).catch((err) =>
console.error(
`Failed to send payment confirmation email for ${regRow.email}:`,
err,
),
);
}
// If this is a watcher with a drink card value, try to credit their
// drinkkaart immediately — but only if they already have an account.
if (
@@ -250,7 +292,7 @@ async function handleWebhook({ request }: { request: Request }) {
}
}
export const Route = createFileRoute("/api/webhook/lemonsqueezy")({
export const Route = createFileRoute("/api/webhook/mollie")({
server: {
handlers: {
POST: handleWebhook,

View File

@@ -39,9 +39,9 @@ function ContactPage() {
<section className="rounded-lg bg-white/5 p-6">
<h3 className="mb-3 text-white text-xl">Open Mic Night</h3>
<p>Vrijdag 24 april 2026</p>
<p>Aanvang: 19:00 uur</p>
<p>Aanvang: 19:30 uur</p>
<p className="mt-2 text-white/60">
Locatie wordt later bekendgemaakt aan geregistreerde deelnemers.
Lange Winkelstraat 5, 2000 Antwerpen
</p>
</section>
@@ -72,6 +72,14 @@ function ContactPage() {
>
Vlaanderen Cultuur, Jeugd & Media
</a>
<a
href="https://ichtusantwerpen.com"
target="_blank"
rel="noopener noreferrer"
className="link-hover text-white/80 hover:text-white"
>
Ichtus Antwerpen
</a>
</div>
</section>

View File

@@ -1,21 +1,575 @@
import { useMutation } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { DEDUCTION_PRESETS_CENTS, formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
// /drinkkaart redirects to /account, preserving ?topup=success for
// backward-compatibility with the Lemon Squeezy webhook return URL.
export const Route = createFileRoute("/drinkkaart")({
validateSearch: (search: Record<string, unknown>) => ({
topup: search.topup as string | undefined,
}),
beforeLoad: async ({ search }) => {
beforeLoad: async () => {
const session = await authClient.getSession();
if (!session.data?.user) {
throw redirect({ to: "/login" });
}
throw redirect({
to: "/account",
search: search.topup ? { topup: search.topup } : {},
});
const user = session.data.user as { role?: string };
if (user.role !== "admin") {
throw redirect({ to: "/" });
}
},
component: () => null,
component: DrinkkaartScanPage,
});
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type ScanState =
| { step: "scanning" }
| { step: "resolving" }
| {
step: "resolved";
drinkkaartId: string;
userId: string;
userName: string;
userEmail: string;
balance: number;
}
| {
step: "confirming";
drinkkaartId: string;
userName: string;
userEmail: string;
balance: number;
amountCents: number;
}
| {
step: "success";
userName: string;
amountCents: number;
balanceAfter: number;
}
| { step: "error"; message: string };
// ---------------------------------------------------------------------------
// ScanningView — full-screen camera with manual fallback
// ---------------------------------------------------------------------------
function ScanningView({ onScan }: { onScan: (token: string) => void }) {
const videoContainerId = "qr-video-container";
const scannerRef = useRef<unknown>(null);
const [hasError, setHasError] = useState(false);
const [manualToken, setManualToken] = useState("");
const [showManual, setShowManual] = useState(false);
const onScanRef = useRef(onScan);
useEffect(() => {
onScanRef.current = onScan;
}, [onScan]);
useEffect(() => {
if (hasError) return;
let stopped = false;
import("html5-qrcode")
.then(({ Html5Qrcode }) => {
if (stopped) return;
const scanner = new Html5Qrcode(videoContainerId);
scannerRef.current = scanner;
scanner
.start(
{ facingMode: "environment" },
{ fps: 15, qrbox: { width: 240, height: 240 } },
(decodedText: string) => {
scanner
.stop()
.catch(console.error)
.finally(() => {
if (!stopped) onScanRef.current(decodedText);
});
},
() => {},
)
.catch((err: unknown) => {
if (!stopped) {
console.error("Camera start failed:", err);
setHasError(true);
setShowManual(true);
}
});
})
.catch((err) => {
console.error("Failed to load html5-qrcode:", err);
setHasError(true);
setShowManual(true);
});
return () => {
stopped = true;
const s = scannerRef.current as {
stop: () => Promise<void>;
clear: () => Promise<void>;
} | null;
s?.stop()
.catch(() => {})
.finally(() => s?.clear().catch(() => {}));
};
}, [hasError]);
const handleManualSubmit = () => {
const token = manualToken.trim();
if (token) onScan(token);
};
return (
<div className="flex flex-1 flex-col">
{/* Camera — fills all available space above the hint */}
{!hasError && (
<div
id={videoContainerId}
className="[&_#qr-shaded-region]:!border-white/40 flex-1 overflow-hidden bg-black [&>video]:h-full [&>video]:w-full [&>video]:object-cover"
/>
)}
{hasError && (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-sm rounded-2xl border border-white/10 bg-white/5 p-6 text-center">
<p className="text-white/60">Camera niet beschikbaar.</p>
</div>
</div>
)}
{/* Bottom controls */}
<div className="shrink-0 space-y-3 px-4 pt-4 pb-8">
{showManual ? (
<div className="flex gap-2">
<Input
autoFocus
value={manualToken}
onChange={(e) => setManualToken(e.target.value)}
placeholder="Plak QR token..."
className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
onKeyDown={(e) => e.key === "Enter" && handleManualSubmit()}
/>
<Button
onClick={handleManualSubmit}
disabled={!manualToken.trim()}
className="shrink-0 bg-white text-[#214e51] hover:bg-white/90"
>
OK
</Button>
</div>
) : (
<div className="flex items-center justify-between">
<p className="text-sm text-white/40">
Richt de camera op de QR-code
</p>
<button
type="button"
onClick={() => setShowManual(true)}
className="text-sm text-white/30 hover:text-white/60"
>
Handmatig
</button>
</div>
)}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
function DrinkkaartScanPage() {
const [scanState, setScanState] = useState<ScanState>({ step: "scanning" });
const [customCents, setCustomCents] = useState("");
const [useCustom, setUseCustom] = useState(false);
const [selectedCents, setSelectedCents] = useState<number>(
DEDUCTION_PRESETS_CENTS[1],
);
const successTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Auto-return to scanner 1.5s after success
useEffect(() => {
if (scanState.step === "success") {
successTimerRef.current = setTimeout(() => {
setScanState({ step: "scanning" });
setCustomCents("");
setUseCustom(false);
setSelectedCents(DEDUCTION_PRESETS_CENTS[1]);
}, 1500);
}
return () => {
if (successTimerRef.current) clearTimeout(successTimerRef.current);
};
}, [scanState.step]);
// --- Mutations ---
const resolveQrMutation = useMutation(
orpc.drinkkaart.resolveQrToken.mutationOptions(),
);
const deductMutation = useMutation(
orpc.drinkkaart.deductBalance.mutationOptions(),
);
// --- Handlers ---
const handleScan = useCallback(
(token: string) => {
setScanState({ step: "resolving" });
resolveQrMutation.mutate(
{ token },
{
onSuccess: (data) => {
setScanState({
step: "resolved",
drinkkaartId: data.drinkkaartId,
userId: data.userId,
userName: data.userName,
userEmail: data.userEmail,
balance: data.balance,
});
},
onError: (err: Error) => {
setScanState({
step: "error",
message: err.message ?? "Ongeldig QR-token",
});
},
},
);
},
[resolveQrMutation],
);
const handlePresetSelect = (cents: number) => {
setSelectedCents(cents);
setUseCustom(false);
};
const getAmountCents = () => {
if (useCustom) {
return Math.round((Number.parseFloat(customCents || "0") || 0) * 100);
}
return selectedCents;
};
const handleDeductTap = () => {
if (scanState.step !== "resolved") return;
const amountCents = getAmountCents();
if (!amountCents || amountCents < 1 || amountCents > scanState.balance)
return;
setScanState({
step: "confirming",
drinkkaartId: scanState.drinkkaartId,
userName: scanState.userName,
userEmail: scanState.userEmail,
balance: scanState.balance,
amountCents,
});
};
const handleConfirm = () => {
if (scanState.step !== "confirming") return;
deductMutation.mutate(
{
drinkkaartId: scanState.drinkkaartId,
amountCents: scanState.amountCents,
},
{
onSuccess: (data) => {
toast.success(`${formatCents(scanState.amountCents)} afgeschreven`);
setScanState({
step: "success",
userName: scanState.userName,
amountCents: scanState.amountCents,
balanceAfter: data.balanceAfter,
});
deductMutation.reset();
},
onError: (err: Error) => {
setScanState({
step: "error",
message: err.message ?? "Fout bij afschrijving",
});
deductMutation.reset();
},
},
);
};
const restartScanner = () => {
setScanState({ step: "scanning" });
setCustomCents("");
setUseCustom(false);
setSelectedCents(DEDUCTION_PRESETS_CENTS[1]);
deductMutation.reset();
};
// Determine the display amount for the deduct button (only in resolved step)
const resolvedAmountCents =
scanState.step === "resolved" ? getAmountCents() : 0;
const resolvedBalance = scanState.step === "resolved" ? scanState.balance : 0;
const deductIsValid =
scanState.step === "resolved" &&
Number.isInteger(resolvedAmountCents) &&
resolvedAmountCents >= 1 &&
resolvedAmountCents <= resolvedBalance;
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
return (
<div className="flex h-dvh flex-col bg-[#214e51]">
{/* ------------------------------------------------------------------ */}
{/* Header */}
{/* ------------------------------------------------------------------ */}
<header className="flex shrink-0 items-center justify-between border-white/10 border-b px-4 py-3">
<h1 className="font-['Intro',sans-serif] text-lg text-white">
Drinkkaart
</h1>
{/* Only show the admin link when not mid-flow */}
{(scanState.step === "scanning" || scanState.step === "error") && (
<a
href="/admin/drinkkaart"
className="rounded-lg px-3 py-1.5 text-sm text-white/50 hover:bg-white/10 hover:text-white"
>
Beheer
</a>
)}
{scanState.step === "resolved" && (
<button
type="button"
onClick={restartScanner}
className="rounded-lg px-3 py-1.5 text-sm text-white/50 hover:bg-white/10 hover:text-white"
>
Annuleer
</button>
)}
{scanState.step === "confirming" && (
<button
type="button"
onClick={() => {
// Go back to resolved state
const s = scanState;
setScanState({
step: "resolved",
drinkkaartId: s.drinkkaartId,
userId: "",
userName: s.userName,
userEmail: s.userEmail,
balance: s.balance,
});
}}
className="rounded-lg px-3 py-1.5 text-sm text-white/50 hover:bg-white/10 hover:text-white"
>
Terug
</button>
)}
</header>
{/* ------------------------------------------------------------------ */}
{/* Main content area */}
{/* ------------------------------------------------------------------ */}
<main className="flex flex-1 flex-col overflow-hidden">
{/* ---- SCANNING ---- */}
{scanState.step === "scanning" && <ScanningView onScan={handleScan} />}
{/* ---- RESOLVING ---- */}
{scanState.step === "resolving" && (
<div className="flex flex-1 flex-col items-center justify-center gap-4 px-6">
<div className="h-12 w-12 animate-spin rounded-full border-4 border-white/20 border-t-white" />
<p className="text-white/60">Controleren...</p>
</div>
)}
{/* ---- RESOLVED: show person + deduct controls ---- */}
{scanState.step === "resolved" && (
<div className="flex flex-1 flex-col overflow-y-auto">
{/* Person card */}
<div className="mx-4 mt-4 rounded-2xl border border-white/10 bg-white/5 p-5">
<div className="flex items-start justify-between">
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-lg text-white">
{scanState.userName}
</p>
<p className="truncate text-sm text-white/50">
{scanState.userEmail}
</p>
</div>
<div className="ml-4 shrink-0 text-right">
<p className="text-white/40 text-xs">Saldo</p>
<p className="font-['Intro',sans-serif] text-3xl text-white">
{formatCents(scanState.balance)}
</p>
</div>
</div>
</div>
{/* Amount selection */}
<div className="mx-4 mt-4 space-y-4">
<p className="text-sm text-white/60">Bedrag kiezen</p>
{/* Preset grid */}
<div className="grid grid-cols-4 gap-2">
{DEDUCTION_PRESETS_CENTS.map((cents) => (
<button
key={cents}
type="button"
onClick={() => handlePresetSelect(cents)}
className={`rounded-xl border py-4 font-semibold text-sm transition-colors ${
!useCustom && selectedCents === cents
? "border-white bg-white text-[#214e51]"
: "border-white/20 text-white hover:border-white/50 active:bg-white/10"
}`}
>
{formatCents(cents)}
</button>
))}
</div>
{/* Custom amount */}
<div className="relative">
<span className="absolute top-1/2 left-3.5 -translate-y-1/2 text-white/50">
</span>
<Input
type="number"
min="0.01"
step="0.01"
placeholder="Eigen bedrag"
value={customCents}
onChange={(e) => {
setCustomCents(e.target.value);
setUseCustom(true);
}}
onFocus={() => setUseCustom(true)}
className="border-white/20 bg-white/10 py-4 pl-8 text-base text-white placeholder:text-white/30"
/>
</div>
{/* Insufficient balance warning */}
{resolvedAmountCents > resolvedBalance && (
<p className="text-red-400 text-sm">
Onvoldoende saldo ({formatCents(resolvedBalance)})
</p>
)}
</div>
{/* Deduct button — sticky at bottom */}
<div className="mt-auto px-4 pt-4 pb-8">
<Button
onClick={handleDeductTap}
disabled={!deductIsValid}
className="h-14 w-full bg-white font-semibold text-[#214e51] text-lg hover:bg-white/90 disabled:opacity-40"
>
{deductIsValid
? `Afschrijven — ${formatCents(resolvedAmountCents)}`
: "Kies een bedrag"}
</Button>
</div>
</div>
)}
{/* ---- CONFIRMING ---- */}
{scanState.step === "confirming" && (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-sm space-y-6">
{/* Summary card */}
<div className="rounded-2xl border border-white/10 bg-white/5 p-6 text-center">
<p className="text-sm text-white/60">Afschrijving voor</p>
<p className="mt-1 font-semibold text-white text-xl">
{scanState.userName}
</p>
<p className="mt-4 font-['Intro',sans-serif] text-5xl text-white">
{formatCents(scanState.amountCents)}
</p>
<p className="mt-3 text-sm text-white/50">
Nieuw saldo:{" "}
<span className="text-white">
{formatCents(scanState.balance - scanState.amountCents)}
</span>
</p>
</div>
{deductMutation.isError && (
<p className="text-center text-red-400 text-sm">
{(deductMutation.error as Error)?.message ??
"Fout bij afschrijving"}
</p>
)}
{/* Confirm button */}
<Button
onClick={handleConfirm}
disabled={deductMutation.isPending}
className="h-14 w-full bg-white font-semibold text-[#214e51] text-lg hover:bg-white/90 disabled:opacity-50"
>
{deductMutation.isPending ? "Verwerken..." : "Bevestigen"}
</Button>
</div>
</div>
)}
{/* ---- SUCCESS ---- */}
{scanState.step === "success" && (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-sm space-y-4 text-center">
<div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-green-400/20">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
className="h-8 w-8 text-green-400"
aria-label="Betaling geslaagd"
>
<polyline points="20 6 9 17 4 12" />
</svg>
</div>
<div>
<p className="font-semibold text-green-300 text-xl">
{formatCents(scanState.amountCents)} afgeschreven
</p>
<p className="mt-1 text-sm text-white/60">
{scanState.userName} nieuw saldo:{" "}
<strong className="text-white">
{formatCents(scanState.balanceAfter)}
</strong>
</p>
</div>
<p className="text-white/30 text-xs">
Volgende scan wordt gestart
</p>
</div>
</div>
)}
{/* ---- ERROR ---- */}
{scanState.step === "error" && (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-sm space-y-5">
<div className="rounded-2xl border border-red-400/20 bg-red-400/5 p-5 text-center">
<p className="font-semibold text-lg text-red-300">Fout</p>
<p className="mt-2 text-sm text-white/60">
{scanState.message}
</p>
</div>
<Button
onClick={restartScanner}
className="h-14 w-full bg-white font-semibold text-[#214e51] text-lg hover:bg-white/90"
>
Opnieuw scannen
</Button>
</div>
</div>
)}
</main>
</div>
);
}

View File

@@ -0,0 +1,118 @@
import { useMutation } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
export const Route = createFileRoute("/forgot-password")({
component: ForgotPasswordPage,
});
function ForgotPasswordPage() {
const [email, setEmail] = useState("");
const [sent, setSent] = useState(false);
const mutation = useMutation({
mutationFn: async (email: string) => {
const result = await authClient.requestPasswordReset({
email,
redirectTo: "/reset-password",
});
if (result.error) {
throw new Error(result.error.message);
}
return result.data;
},
onSuccess: () => {
setSent(true);
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
mutation.mutate(email);
};
return (
<div className="flex min-h-[calc(100dvh-2.75rem)] items-center justify-center overflow-y-auto px-4 py-8 sm:min-h-[calc(100dvh-3.5rem)]">
<Card className="my-auto w-full max-w-md border-white/10 bg-white/5">
<CardHeader className="text-center">
<CardTitle className="font-['Intro',sans-serif] text-3xl text-white">
Wachtwoord vergeten
</CardTitle>
<CardDescription className="text-white/60">
{sent
? "Controleer je inbox"
: "Vul je e-mailadres in en we sturen je een link"}
</CardDescription>
</CardHeader>
<CardContent>
{sent ? (
<div className="space-y-4">
<div className="rounded-lg border border-white/10 bg-white/5 p-5 text-center">
<p className="text-sm text-white/80 leading-relaxed">
Als er een account bestaat voor{" "}
<span className="font-medium text-white">{email}</span>, is er
een e-mail verstuurd met een link om je wachtwoord opnieuw in
te stellen. De link is 1 uur geldig.
</p>
</div>
<Link
to="/login"
className="block text-center text-sm text-white/60 hover:text-white"
>
Terug naar inloggen
</Link>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="email"
className="mb-2 block text-sm text-white/60"
>
E-mailadres
</label>
<Input
id="email"
type="email"
placeholder="jouw@email.be"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
/>
</div>
{mutation.isError && (
<p className="text-red-400 text-sm">{mutation.error.message}</p>
)}
<Button
type="submit"
disabled={mutation.isPending}
className="w-full bg-white text-[#214e51] hover:bg-white/90"
>
{mutation.isPending ? "Bezig..." : "Stuur reset-link"}
</Button>
<div className="text-center">
<Link
to="/login"
className="text-sm text-white/60 hover:text-white"
>
Terug naar inloggen
</Link>
</div>
</form>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,25 +1,172 @@
import { createFileRoute } from "@tanstack/react-router";
import ArtForms from "@/components/homepage/ArtForms";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import EventRegistrationForm from "@/components/homepage/EventRegistrationForm";
import Footer from "@/components/homepage/Footer";
import Hero from "@/components/homepage/Hero";
import HoeInschrijven from "@/components/homepage/HoeInschrijven";
import Info from "@/components/homepage/Info";
const KAMP_BANNER_KEY = "kk_kamp_banner_dismissed";
export const Route = createFileRoute("/")({
component: HomePage,
});
function HomePage() {
function KampBanner({ onDismiss }: { onDismiss: () => void }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!document.getElementById("kamp-banner-font")) {
const el = document.createElement("link");
el.id = "kamp-banner-font";
el.rel = "stylesheet";
el.href =
"https://fonts.googleapis.com/css2?family=Special+Elite&display=swap";
document.head.appendChild(el);
}
const t = setTimeout(() => setVisible(true), 600);
return () => clearTimeout(t);
}, []);
const handleDismiss = () => {
setVisible(false);
setTimeout(onDismiss, 300);
};
return (
<div className="relative">
<main className="relative">
<Hero />
<Info />
<ArtForms />
<EventRegistrationForm />
<Footer />
</main>
</div>
<header
style={{
position: "fixed",
bottom: "1.25rem",
left: "50%",
transform: visible
? "translateX(-50%) translateY(0)"
: "translateX(-50%) translateY(120%)",
transition: "transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1)",
zIndex: 50,
width: "min(calc(100vw - 2rem), 480px)",
}}
>
<div
style={{
background: "#ede4c8",
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='200' height='200' filter='url(%23n)' opacity='0.06'/%3E%3C/svg%3E")`,
border: "1px solid #12100e",
outline: "3px solid rgba(18,16,14,0.1)",
outlineOffset: "3px",
borderRadius: 0,
padding: "12px 14px 14px",
boxShadow: "3px 5px 20px rgba(0,0,0,0.25)",
}}
>
{/* Top double rule */}
<div style={{ marginBottom: "10px" }}>
<div
style={{
height: "2px",
background: "#12100e",
marginBottom: "3px",
}}
/>
<div style={{ height: "1px", background: "rgba(18,16,14,0.35)" }} />
</div>
<div style={{ display: "flex", alignItems: "flex-start", gap: "10px" }}>
<div style={{ flex: 1, minWidth: 0 }}>
<p
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "8px",
letterSpacing: "0.3em",
textTransform: "uppercase",
color: "rgba(18,16,14,0.45)",
marginBottom: "6px",
}}
>
Aankondiging · Zomerkamp 2026
</p>
<p
style={{
fontFamily: "'Playfair Display', serif",
fontWeight: 700,
fontSize: "14px",
color: "#12100e",
lineHeight: 1.35,
marginBottom: "12px",
}}
>
Inschrijvingen voor de zomerkampen zijn open!
</p>
<Link
to="/kamp"
style={{
display: "inline-block",
fontFamily: "'Special Elite', cursive",
fontSize: "9px",
letterSpacing: "0.22em",
textTransform: "uppercase",
textDecoration: "none",
color: "#ede4c8",
background: "#12100e",
border: "1px solid rgba(18,16,14,0.4)",
outline: "2px solid rgba(18,16,14,0.08)",
outlineOffset: "3px",
padding: "7px 12px 6px",
}}
>
Schrijf je in
</Link>
</div>
<button
type="button"
onClick={handleDismiss}
aria-label="Sluit deze melding"
style={{
background: "none",
border: "none",
color: "rgba(18,16,14,0.3)",
cursor: "pointer",
padding: "2px",
flexShrink: 0,
fontSize: "18px",
lineHeight: 1,
fontFamily: "'Special Elite', cursive",
}}
>
×
</button>
</div>
</div>
</header>
);
}
function HomePage() {
const [showBanner, setShowBanner] = useState(false);
useEffect(() => {
if (!localStorage.getItem(KAMP_BANNER_KEY)) {
setShowBanner(true);
}
}, []);
const dismissBanner = () => {
localStorage.setItem(KAMP_BANNER_KEY, "1");
setShowBanner(false);
};
return (
<>
<div className="relative">
<main className="relative">
<Hero />
<Info />
<HoeInschrijven />
<EventRegistrationForm />
<Footer />
</main>
</div>
{showBanner && <KampBanner onDismiss={dismissBanner} />}
</>
);
}

View File

@@ -0,0 +1,473 @@
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
const KAMP_URL = "https://ejv.be/jong/kampen/kunstenkamp/";
export const Route = createFileRoute("/kamp")({
component: KampPage,
});
const STYLES = `
@import url('https://fonts.googleapis.com/css2?family=UnifrakturMaguntia&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400;1,700&family=EB+Garamond:ital,wght@0,400;0,500;1,400;1,500&family=Special+Elite&display=swap');
@keyframes kampPressIn {
from { opacity: 0; }
to { opacity: 1; }
}
body.kamp-page {
background-color: #d6cdb0 !important;
overflow: hidden;
}
body.kamp-page ::selection {
background: #12100e;
color: #ede4c8;
}
.kamp-scroll::-webkit-scrollbar {
width: 6px;
}
.kamp-scroll::-webkit-scrollbar-track {
background: #c9c0a4;
}
.kamp-scroll::-webkit-scrollbar-thumb {
background: #12100e;
}
`;
const PAPER = "#ede4c8";
const INK = "#12100e";
const INK_MID = "rgba(18,16,14,0.5)";
const INK_GHOST = "rgba(18,16,14,0.2)";
const RULE_W = "rgba(18,16,14,0.75)";
function TripleRule() {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "3px" }}>
<div style={{ height: "3px", background: INK }} />
<div style={{ height: "1px", background: RULE_W }} />
<div style={{ height: "2px", background: INK }} />
</div>
);
}
function DoubleRule() {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "3px" }}>
<div style={{ height: "2px", background: RULE_W }} />
<div style={{ height: "1px", background: RULE_W }} />
</div>
);
}
function KampPage() {
const [mounted, setMounted] = useState(false);
const [ctaHovered, setCtaHovered] = useState(false);
useEffect(() => {
if (!document.getElementById("kamp-newspaper-styles")) {
const el = document.createElement("style");
el.id = "kamp-newspaper-styles";
el.textContent = STYLES;
document.head.appendChild(el);
}
document.body.classList.add("kamp-page");
const t = setTimeout(() => setMounted(true), 60);
return () => {
document.body.classList.remove("kamp-page");
clearTimeout(t);
};
}, []);
return (
<div
style={{
height: "100dvh",
background: "#d6cdb0",
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='400' height='400' filter='url(%23n)' opacity='0.12'/%3E%3C/svg%3E")`,
backgroundRepeat: "repeat",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "1.5rem 1rem",
}}
>
{/* Newspaper page */}
<article
className="kamp-scroll"
style={{
width: "100%",
maxWidth: "700px",
height: "100%",
background: PAPER,
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='300'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='300' height='300' filter='url(%23n)' opacity='0.06'/%3E%3C/svg%3E")`,
border: `1px solid ${INK}`,
boxShadow:
"3px 5px 24px rgba(0,0,0,0.18), 0 1px 3px rgba(0,0,0,0.12)",
opacity: mounted ? 1 : 0,
animation: mounted ? "kampPressIn 0.9s ease both" : undefined,
overflowY: "auto",
}}
>
{/* Outer decorative border inset */}
<div
style={{
margin: "6px",
border: `1px solid ${INK}`,
}}
>
{/* Top flag strip */}
<div
style={{
borderBottom: `1px solid ${INK}`,
padding: "7px 20px 6px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Link
to="/"
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "10px",
letterSpacing: "0.18em",
color: INK,
textDecoration: "none",
borderBottom: `1px solid ${INK}`,
paddingBottom: "1px",
}}
>
Open Mic Night
</Link>
<span
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "9px",
letterSpacing: "0.18em",
color: INK_MID,
}}
>
· ·
</span>
<span
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "9px",
letterSpacing: "0.22em",
textTransform: "uppercase",
color: INK_MID,
}}
>
Anno 2026
</span>
</div>
{/* Masthead */}
<div
style={{
padding: "20px 24px 16px",
textAlign: "center",
borderBottom: `1px solid ${INK}`,
}}
>
<h1
style={{
fontFamily: "'UnifrakturMaguntia', cursive",
fontSize: "clamp(2.4rem, 9vw, 4.5rem)",
color: INK,
margin: 0,
lineHeight: 1,
letterSpacing: "0.02em",
}}
>
De Kunstenkamp Gazet
</h1>
</div>
{/* Publication bar */}
<div
style={{
display: "flex",
justifyContent: "space-between",
padding: "6px 20px 5px",
borderBottom: `1px solid ${INK}`,
}}
>
{[
"Vol. CCXXVI",
"Zomerkamp · Juli 2026",
"Prijs: uw aanwezigheid",
].map((t) => (
<span
key={t}
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "10px",
color: INK_MID,
letterSpacing: "0.1em",
}}
>
{t}
</span>
))}
</div>
{/* Main content area */}
<div style={{ padding: "28px 28px 24px" }}>
{/* Triple rule */}
<div style={{ marginBottom: "24px" }}>
<TripleRule />
</div>
{/* Main headline */}
<div style={{ textAlign: "center", marginBottom: "16px" }}>
<h2
style={{
fontFamily: "'Playfair Display', serif",
fontWeight: 900,
fontSize: "clamp(2.6rem, 9vw, 4.5rem)",
color: INK,
textTransform: "uppercase",
letterSpacing: "0.06em",
lineHeight: 0.95,
margin: "0 0 14px",
}}
>
Wat Is Waar?
</h2>
<p
style={{
fontFamily: "'Playfair Display', serif",
fontStyle: "italic",
fontSize: "clamp(1rem, 2.5vw, 1.2rem)",
color: INK_MID,
margin: 0,
lineHeight: 1.45,
}}
>
Een krant. Een tijdmachine. De waarheid doorheen de eeuwen.
</p>
</div>
{/* Triple rule */}
<div style={{ marginBottom: "22px" }}>
<TripleRule />
</div>
{/* Editorial body copy */}
<p
style={{
fontFamily: "'EB Garamond', serif",
fontSize: "clamp(1.05rem, 2.2vw, 1.2rem)",
color: INK,
lineHeight: 1.75,
margin: "0 0 10px",
textAlign: "justify",
hyphens: "auto",
}}
>
In de zomer van 1826 en opnieuw in 2026 reizen onze
verslaggevers terug naar de roerige redactiezalen van de
negentiende eeuw. Waar de drukpers ronkt, de rookmachines tieren
en elke kop een mening verbergt, stellen wij de vraag die door
alle eeuwen galmt: <em>wat mogen wij geloven?</em>
</p>
<p
style={{
fontFamily: "'EB Garamond', serif",
fontStyle: "italic",
fontSize: "clamp(0.95rem, 2vw, 1.08rem)",
color: INK_MID,
lineHeight: 1.7,
margin: "0 0 24px",
textAlign: "justify",
hyphens: "auto",
}}
>
Twee waarheden en een leugen. Vier bolhoeden en één typmachine.
Bereid u voor op een week journalistiek, theater, dans en
woordkunst alles gehuld in inkt en papier-maché.
</p>
{/* Ornamental divider */}
<p
style={{
textAlign: "center",
fontFamily: "'EB Garamond', serif",
fontSize: "13px",
color: INK_GHOST,
margin: "0 0 24px",
letterSpacing: "0.4em",
}}
>
· ·
</p>
{/* Details grid */}
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
border: `1px solid ${INK}`,
marginBottom: "28px",
}}
>
{[
{ label: "Primo", value: "20 25 Juli 2026" },
{ label: "Secundo", value: "27 Juli 1 Aug 2026" },
{
label: "Leeftijd",
value: "9 18 jaar",
sub: "* geboortejaar dat je 10 wordt",
},
{
label: "Locatie",
value: "Camp de Limauges",
sub: "Ceroux-Mousty · België",
},
].map(({ label, value, sub }, i) => (
<div
key={label}
style={{
padding: "16px 18px",
borderRight: i % 2 === 0 ? `1px solid ${INK}` : undefined,
borderTop: i >= 2 ? `1px solid ${INK}` : undefined,
}}
>
<p
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "9px",
letterSpacing: "0.3em",
textTransform: "uppercase",
color: INK_MID,
margin: "0 0 6px",
}}
>
{label}
</p>
<p
style={{
fontFamily: "'Playfair Display', serif",
fontWeight: 700,
fontSize: "clamp(1rem, 2.5vw, 1.15rem)",
color: INK,
margin: 0,
lineHeight: 1.3,
}}
>
{value}
</p>
{sub && (
<p
style={{
fontFamily: "'EB Garamond', serif",
fontStyle: "italic",
fontSize: "13px",
color: INK_MID,
margin: "4px 0 0",
}}
>
{sub}
</p>
)}
</div>
))}
</div>
{/* Double rule */}
<div style={{ marginBottom: "24px" }}>
<DoubleRule />
</div>
{/* CTA — inverted ink block */}
<div style={{ marginBottom: "4px" }}>
<p
style={{
fontFamily: "'Special Elite', cursive",
fontSize: "9px",
letterSpacing: "0.35em",
textTransform: "uppercase",
color: INK_MID,
textAlign: "center",
margin: "0 0 10px",
}}
>
Aankondiging
</p>
<a
href={KAMP_URL}
target="_blank"
rel="noopener noreferrer"
onMouseEnter={() => setCtaHovered(true)}
onMouseLeave={() => setCtaHovered(false)}
style={{
display: "block",
background: ctaHovered ? "#2a2418" : INK,
color: PAPER,
textDecoration: "none",
textAlign: "center",
padding: "28px 32px 26px",
outline: `2px solid ${INK}`,
outlineOffset: "4px",
transition: "background 0.2s ease",
}}
>
<span
style={{
display: "block",
fontFamily: "'Playfair Display', serif",
fontWeight: 900,
fontSize: "clamp(1.5rem, 5vw, 2.4rem)",
textTransform: "uppercase",
letterSpacing: "0.1em",
lineHeight: 1,
marginBottom: "10px",
}}
>
Schrijf U In
</span>
<span
style={{
display: "block",
fontFamily: "'Special Elite', cursive",
fontSize: "clamp(0.7rem, 2vw, 0.85rem)",
letterSpacing: "0.25em",
opacity: 0.65,
}}
>
via ejv.be
</span>
</a>
</div>
</div>
{/* Footer */}
<div
style={{
borderTop: `1px solid ${INK}`,
padding: "7px 20px 8px",
textAlign: "center",
}}
>
<p
style={{
fontFamily: "'EB Garamond', serif",
fontStyle: "italic",
fontSize: "12px",
color: INK_GHOST,
margin: 0,
letterSpacing: "0.06em",
}}
>
Kunst · Expressie · Avontuur · Waar is de waarheid?
</p>
</div>
</div>
</article>
</div>
);
}

View File

@@ -12,6 +12,8 @@ import {
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { REGISTRATION_OPENS_AT } from "@/lib/opening";
import { useRegistrationOpen } from "@/lib/useRegistrationOpen";
import { orpc } from "@/utils/orpc";
export const Route = createFileRoute("/login")({
@@ -31,6 +33,7 @@ export const Route = createFileRoute("/login")({
function LoginPage() {
const navigate = useNavigate();
const search = Route.useSearch();
const { isOpen } = useRegistrationOpen();
const [isSignup, setIsSignup] = useState(() => search.signup === "1");
const [email, setEmail] = useState(() => search.email ?? "");
const [password, setPassword] = useState("");
@@ -204,6 +207,43 @@ function LoginPage() {
Terug naar website
</Link>
</div>
) : isSignup && !isOpen ? (
/* Signup is closed until registration opens */
<div className="space-y-4">
<div className="rounded-lg border border-white/10 bg-white/5 p-5 text-center">
<p className="mb-1 font-['Intro',sans-serif] text-white">
Registratie nog niet open
</p>
<p className="text-sm text-white/60">
Accounts aanmaken kan vanaf{" "}
<span className="text-teal-300">
{REGISTRATION_OPENS_AT.toLocaleDateString("nl-BE", {
weekday: "long",
day: "numeric",
month: "long",
})}{" "}
om{" "}
{REGISTRATION_OPENS_AT.toLocaleTimeString("nl-BE", {
hour: "2-digit",
minute: "2-digit",
})}
</span>
.
</p>
</div>
<div className="flex flex-col gap-2 text-center">
<button
type="button"
onClick={() => setIsSignup(false)}
className="text-sm text-white/60 hover:text-white"
>
Al een account? Log in
</button>
<Link to="/" className="text-sm text-white/60 hover:text-white">
Terug naar website
</Link>
</div>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
{isSignup && (
@@ -259,6 +299,16 @@ function LoginPage() {
className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
/>
</div>
{!isSignup && (
<div className="text-right">
<Link
to="/forgot-password"
className="text-sm text-white/50 hover:text-white"
>
Wachtwoord vergeten?
</Link>
</div>
)}
<Button
type="submit"
disabled={loginMutation.isPending || signupMutation.isPending}
@@ -271,15 +321,34 @@ function LoginPage() {
: "Inloggen"}
</Button>
<div className="flex flex-col gap-2 text-center">
<button
type="button"
onClick={() => setIsSignup(!isSignup)}
className="text-sm text-white/60 hover:text-white"
>
{isSignup
? "Al een account? Log in"
: "Nog geen account? Registreer"}
</button>
{/* Only show signup toggle when registration is open */}
{isOpen && (
<button
type="button"
onClick={() => setIsSignup(!isSignup)}
className="text-sm text-white/60 hover:text-white"
>
{isSignup
? "Al een account? Log in"
: "Nog geen account? Registreer"}
</button>
)}
{!isOpen && isSignup === false && (
<button
type="button"
onClick={() => setIsSignup(true)}
className="cursor-not-allowed text-sm text-white/30"
disabled
title={`Registratie opent op ${REGISTRATION_OPENS_AT.toLocaleString("nl-BE", { day: "numeric", month: "long", hour: "2-digit", minute: "2-digit" })}`}
>
Nog geen account? (opent{" "}
{REGISTRATION_OPENS_AT.toLocaleString("nl-BE", {
day: "numeric",
month: "long",
})}
)
</button>
)}
<Link to="/" className="text-sm text-white/60 hover:text-white">
Terug naar website
</Link>

View File

@@ -117,8 +117,8 @@ interface EditFormProps {
lastName: string;
email: string;
phone: string | null;
postcode: string | null;
birthdate: string | null;
birthdate: string;
postcode: string;
registrationType: string;
artForm: string | null;
experience: string | null;
@@ -142,8 +142,8 @@ function EditForm({ token, initialData, onCancel, onSaved }: EditFormProps) {
lastName: initialData.lastName,
email: initialData.email,
phone: initialData.phone ?? "",
postcode: initialData.postcode ?? "",
birthdate: initialData.birthdate ?? "",
postcode: initialData.postcode ?? "",
registrationType: initialType,
artForm: initialData.artForm ?? "",
experience: initialData.experience ?? "",
@@ -183,14 +183,14 @@ function EditForm({ token, initialData, onCancel, onSaved }: EditFormProps) {
lastName: formData.lastName.trim(),
email: formData.email.trim(),
phone: formData.phone.trim() || undefined,
postcode: formData.postcode.trim() || "",
birthdate: formData.birthdate || "",
registrationType: formData.registrationType,
artForm: performer ? formData.artForm.trim() || undefined : undefined,
experience: performer
? formData.experience.trim() || undefined
: undefined,
isOver16: performer ? formData.isOver16 : false,
birthdate: formData.birthdate.trim(),
postcode: formData.postcode.trim(),
guests: performer
? []
: formGuests.map((g) => ({
@@ -279,42 +279,6 @@ function EditForm({ token, initialData, onCancel, onSaved }: EditFormProps) {
/>
</div>
{/* Postcode + Birthdate */}
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<label htmlFor="postcode" className="mb-2 block text-white">
Postcode *
</label>
<input
id="postcode"
type="text"
required
value={formData.postcode}
onChange={(e) =>
setFormData((p) => ({ ...p, postcode: e.target.value }))
}
autoComplete="postal-code"
className={inputCls(false)}
/>
</div>
<div>
<label htmlFor="birthdate" className="mb-2 block text-white">
Geboortedatum *
</label>
<input
id="birthdate"
type="date"
required
value={formData.birthdate}
onChange={(e) =>
setFormData((p) => ({ ...p, birthdate: e.target.value }))
}
autoComplete="bday"
className={`${inputCls(false)} [color-scheme:dark]`}
/>
</div>
</div>
{/* Registration type toggle */}
<div>
<p className="mb-3 text-white">Type inschrijving</p>
@@ -636,19 +600,20 @@ function ManageRegistrationPage() {
)}
</div>
{/* Payment status - not shown for performers without a gift */}
{(!isPerformer || (data.giftAmount ?? 0) > 0) &&
(data.paymentStatus !== "paid" || (data.giftAmount ?? 0) > 0) && (
<div className="mb-6">
{data.paymentStatus === "paid" ? (
<PaidBadge />
) : data.paymentStatus === "extra_payment_pending" ? (
<ExtraPaymentBadge amountCents={data.paymentAmount ?? 0} />
) : (
<PendingBadge />
)}
</div>
)}
{/* Payment status badge:
- performers only see a badge if they have a gift to pay, or already paid one
- watchers always have a payment (drink card), so always show a badge */}
{(isPerformer ? (data.giftAmount ?? 0) > 0 : true) && (
<div className="mb-6">
{data.paymentStatus === "paid" ? (
<PaidBadge />
) : data.paymentStatus === "extra_payment_pending" ? (
<ExtraPaymentBadge amountCents={data.paymentAmount ?? 0} />
) : (
<PendingBadge />
)}
</div>
)}
{/* Gift display */}
{(data.giftAmount ?? 0) > 0 && (
@@ -678,14 +643,6 @@ function ManageRegistrationPage() {
<p className="text-sm text-white/50">Telefoon</p>
<p className="text-lg text-white">{data.phone || "—"}</p>
</div>
<div>
<p className="text-sm text-white/50">Postcode</p>
<p className="text-lg text-white">{data.postcode || "—"}</p>
</div>
<div>
<p className="text-sm text-white/50">Geboortedatum</p>
<p className="text-lg text-white">{data.birthdate || "—"}</p>
</div>
</div>
{isPerformer && (
@@ -720,16 +677,6 @@ function ManageRegistrationPage() {
<p className="text-white">
{g.firstName} {g.lastName}
</p>
{g.birthdate && (
<p className="text-sm text-white/60">
Geboortedatum: {g.birthdate}
</p>
)}
{g.postcode && (
<p className="text-sm text-white/60">
Postcode: {g.postcode}
</p>
)}
{g.email && (
<p className="text-sm text-white/60">{g.email}</p>
)}

View File

@@ -26,7 +26,7 @@ function PrivacyPage() {
<p>
We verzamelen alleen de gegevens die je zelf invoert bij de
registratie: voornaam, achternaam, e-mailadres, telefoonnummer,
kunstvorm en ervaring.
geboortedatum, postcode, kunstvorm en ervaring.
</p>
</section>
@@ -39,6 +39,12 @@ function PrivacyPage() {
Mic Night, om het programma samen te stellen en om je te
informeren over aanvullende details over het evenement.
</p>
<p className="mt-3">
<strong className="text-white">Geboortedatum en postcode</strong>{" "}
worden gevraagd ter naleving van de rapportageverplichtingen van{" "}
<strong className="text-white">EJV</strong> en{" "}
<strong className="text-white">de Vlaamse Overheid</strong>.
</p>
</section>
<section>

View File

@@ -0,0 +1,154 @@
import { useMutation } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
export const Route = createFileRoute("/reset-password")({
validateSearch: (search: Record<string, unknown>) => {
const token = typeof search.token === "string" ? search.token : undefined;
return { ...(token !== undefined && { token }) } as { token?: string };
},
component: ResetPasswordPage,
});
function ResetPasswordPage() {
const navigate = useNavigate();
const search = Route.useSearch();
const token = search.token;
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
const mutation = useMutation({
mutationFn: async ({
token,
newPassword,
}: {
token: string;
newPassword: string;
}) => {
const result = await authClient.resetPassword({ token, newPassword });
if (result.error) {
throw new Error(result.error.message);
}
return result.data;
},
onSuccess: () => {
toast.success("Wachtwoord succesvol gewijzigd!");
navigate({ to: "/login" });
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirm) {
toast.error("De wachtwoorden komen niet overeen.");
return;
}
if (!token) {
toast.error("Ongeldige reset-link. Vraag een nieuwe aan.");
return;
}
mutation.mutate({ token, newPassword: password });
};
if (!token) {
return (
<div className="flex min-h-[calc(100dvh-2.75rem)] items-center justify-center px-4 sm:min-h-[calc(100dvh-3.5rem)]">
<Card className="w-full max-w-md border-white/10 bg-white/5">
<CardHeader className="text-center">
<CardTitle className="font-['Intro',sans-serif] text-3xl text-white">
Ongeldige link
</CardTitle>
<CardDescription className="text-white/60">
Deze reset-link is ongeldig of verlopen.
</CardDescription>
</CardHeader>
<CardContent className="text-center">
<Link
to="/forgot-password"
className="text-sm text-white/60 hover:text-white"
>
Vraag een nieuwe reset-link aan
</Link>
</CardContent>
</Card>
</div>
);
}
return (
<div className="flex min-h-[calc(100dvh-2.75rem)] items-center justify-center overflow-y-auto px-4 py-8 sm:min-h-[calc(100dvh-3.5rem)]">
<Card className="my-auto w-full max-w-md border-white/10 bg-white/5">
<CardHeader className="text-center">
<CardTitle className="font-['Intro',sans-serif] text-3xl text-white">
Nieuw wachtwoord
</CardTitle>
<CardDescription className="text-white/60">
Kies een nieuw wachtwoord voor je account
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="password"
className="mb-2 block text-sm text-white/60"
>
Nieuw wachtwoord
</label>
<Input
id="password"
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
/>
</div>
<div>
<label
htmlFor="confirm"
className="mb-2 block text-sm text-white/60"
>
Bevestig wachtwoord
</label>
<Input
id="confirm"
type="password"
placeholder="••••••••"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
minLength={8}
className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
/>
</div>
{mutation.isError && (
<p className="text-red-400 text-sm">{mutation.error.message}</p>
)}
<Button
type="submit"
disabled={mutation.isPending}
className="w-full bg-white text-[#214e51] hover:bg-white/90"
>
{mutation.isPending ? "Bezig..." : "Stel wachtwoord in"}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}

72
apps/web/src/server.ts Normal file
View File

@@ -0,0 +1,72 @@
import type { EmailMessage } from "@kk/api/email-queue";
import { dispatchEmailMessage } from "@kk/api/email-queue";
import { runSendReminders } from "@kk/api/routers/index";
import {
createStartHandler,
defaultStreamHandler,
} from "@tanstack/react-start/server";
// ---------------------------------------------------------------------------
// CF Workers globals — not in DOM/ES2022 lib
// ---------------------------------------------------------------------------
type MessageItem<Body> = {
body: Body;
ack(): void;
retry(): void;
};
type MessageBatch<Body> = { messages: Array<MessageItem<Body>> };
type ExecutionContext = { waitUntil(promise: Promise<unknown>): void };
// ---------------------------------------------------------------------------
// Minimal CF Queue binding shape
// ---------------------------------------------------------------------------
type EmailQueue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
sendBatch(
messages: Array<{ body: EmailMessage }>,
options?: { contentType?: string },
): Promise<void>;
};
type Env = {
EMAIL_QUEUE?: EmailQueue;
};
const startHandler = createStartHandler(defaultStreamHandler);
export default {
fetch(request: Request, env: Env) {
// Cast required: TanStack Start's BaseContext doesn't know about emailQueue,
// but it threads the value through to route handlers via requestContext.
return startHandler(request, {
context: { emailQueue: env.EMAIL_QUEUE } as Record<string, unknown>,
});
},
async queue(
batch: MessageBatch<EmailMessage>,
_env: Env,
_ctx: ExecutionContext,
) {
for (const msg of batch.messages) {
try {
await dispatchEmailMessage(msg.body);
msg.ack();
} catch (err) {
console.error("Queue dispatch failed:", err);
msg.retry();
}
}
},
async scheduled(
_event: { cron: string; scheduledTime: number },
env: Env,
ctx: ExecutionContext,
) {
ctx.waitUntil(runSendReminders(env.EMAIL_QUEUE));
},
};

View File

@@ -42,6 +42,7 @@
"@tanstack/react-start": "^1.141.1",
"@tanstack/router-plugin": "^1.141.1",
"better-auth": "catalog:",
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dotenv": "catalog:",
@@ -66,8 +67,10 @@
"@kk/config": "workspace:*",
"@tanstack/react-query-devtools": "^5.91.1",
"@tanstack/react-router-devtools": "^1.141.1",
"@tanstack/router-core": "^1.141.1",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0",
"@types/canvas-confetti": "^1.9.0",
"@types/qrcode": "^1.5.6",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",
@@ -93,7 +96,7 @@
"@orpc/zod": "catalog:",
"dotenv": "catalog:",
"drizzle-orm": "^0.45.1",
"nodemailer": "^8.0.1",
"nodemailer": "^8.0.2",
"zod": "catalog:",
},
"devDependencies": {
@@ -109,10 +112,12 @@
"@kk/env": "workspace:*",
"better-auth": "catalog:",
"dotenv": "catalog:",
"nodemailer": "^8.0.2",
"zod": "catalog:",
},
"devDependencies": {
"@kk/config": "workspace:*",
"@types/nodemailer": "^7.0.11",
"typescript": "catalog:",
},
},
@@ -909,6 +914,8 @@
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
"@types/canvas-confetti": ["@types/canvas-confetti@1.9.0", "", {}, "sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg=="],
"@types/draco3d": ["@types/draco3d@1.4.10", "", {}, "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw=="],
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
@@ -1027,6 +1034,8 @@
"caniuse-lite": ["caniuse-lite@1.0.30001774", "", {}, "sha512-DDdwPGz99nmIEv216hKSgLD+D4ikHQHjBC/seF98N9CPqRX4M5mSxT9eTV6oyisnJcuzxtZy4n17yKKQYmYQOA=="],
"canvas-confetti": ["canvas-confetti@1.9.4", "", {}, "sha512-yxQbJkAVrFXWNbTUjPqjF7G+g6pDotOUHGbkZq2NELZUMDpiJ85rIEazVb8GTaAptNW2miJAXbs1BtioA251Pw=="],
"chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"cheerio": ["cheerio@1.2.0", "", { "dependencies": { "cheerio-select": "^2.1.0", "dom-serializer": "^2.0.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "encoding-sniffer": "^0.2.1", "htmlparser2": "^10.1.0", "parse5": "^7.3.0", "parse5-htmlparser2-tree-adapter": "^7.1.0", "parse5-parser-stream": "^7.1.2", "undici": "^7.19.0", "whatwg-mimetype": "^4.0.0" } }, "sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg=="],
@@ -1503,7 +1512,7 @@
"node-releases": ["node-releases@2.0.27", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
"nodemailer": ["nodemailer@8.0.1", "", {}, "sha512-5kcldIXmaEjZcHR6F28IKGSgpmZHaF1IXLWFTG+Xh3S+Cce4MiakLtWY+PlBU69fLbRa8HlaGIrC/QolUpHkhg=="],
"nodemailer": ["nodemailer@8.0.2", "", {}, "sha512-zbj002pZAIkWQFxyAaqoxvn+zoIwRnS40hgjqTXudKOOJkiFFgBeNqjgD3/YCR12sZnrghWYBY+yP1ZucdDRpw=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],

View File

@@ -20,7 +20,7 @@
"@orpc/zod": "catalog:",
"dotenv": "catalog:",
"drizzle-orm": "^0.45.1",
"nodemailer": "^8.0.1",
"nodemailer": "^8.0.2",
"zod": "catalog:"
},
"devDependencies": {

View File

@@ -0,0 +1,10 @@
// ---------------------------------------------------------------------------
// Single source-of-truth for event details used across the API
// ---------------------------------------------------------------------------
export const EVENT = "Open Mic Night — vrijdag 24 april 2026";
export const LOCATION = "Lange Winkelstraat 5, 2000 Antwerpen";
export const OPENS = "maandag 16 maart 2026 om 19:00";
// Registration opens — used for reminder scheduling windows
export const REGISTRATION_OPENS_AT = new Date("2026-03-16T19:00:00+01:00");

View File

@@ -1,13 +1,33 @@
import { auth } from "@kk/auth";
import { env } from "@kk/env/server";
import type { EmailMessage } from "./email-queue";
export async function createContext({ req }: { req: Request }) {
// CF Workers runtime Queue type (not the alchemy resource type)
type Queue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
sendBatch(
messages: Array<{ body: EmailMessage }>,
options?: { contentType?: string },
): Promise<void>;
};
export async function createContext({
req,
emailQueue,
}: {
req: Request;
emailQueue?: Queue;
}) {
const session = await auth.api.getSession({
headers: req.headers,
});
return {
session,
env,
emailQueue,
};
}

View File

@@ -0,0 +1,147 @@
/**
* Email queue types and dispatcher.
*
* All email sends are modelled as a discriminated union so the Cloudflare Queue
* consumer can pattern-match on `msg.type` and call the right send*Email().
*
* The `Queue<EmailMessage>` type used in context.ts / server.ts refers to the
* CF runtime binding type (`import type { Queue } from "@cloudflare/workers-types"`).
*/
import {
sendCancellationEmail,
sendConfirmationEmail,
sendPaymentConfirmationEmail,
sendPaymentReminderEmail,
sendReminder24hEmail,
sendReminderEmail,
sendSubscriptionConfirmationEmail,
sendUpdateEmail,
} from "./email";
import { sendDeductionEmail } from "./lib/drinkkaart-email";
// ---------------------------------------------------------------------------
// Message types — one variant per send*Email function
// ---------------------------------------------------------------------------
export type ConfirmationMessage = {
type: "registrationConfirmation";
to: string;
firstName: string;
managementToken: string;
wantsToPerform: boolean;
artForm?: string | null;
giftAmount?: number;
drinkCardValue?: number;
signupUrl?: string;
};
export type UpdateMessage = {
type: "updateConfirmation";
to: string;
firstName: string;
managementToken: string;
wantsToPerform: boolean;
artForm?: string | null;
giftAmount?: number;
drinkCardValue?: number;
};
export type CancellationMessage = {
type: "cancellation";
to: string;
firstName: string;
};
export type SubscriptionConfirmationMessage = {
type: "subscriptionConfirmation";
to: string;
};
export type Reminder24hMessage = {
type: "reminder24h";
to: string;
firstName?: string | null;
};
export type Reminder1hMessage = {
type: "reminder1h";
to: string;
firstName?: string | null;
};
export type PaymentReminderMessage = {
type: "paymentReminder";
to: string;
firstName: string;
managementToken: string;
drinkCardValue?: number;
giftAmount?: number;
};
export type PaymentConfirmationMessage = {
type: "paymentConfirmation";
to: string;
firstName: string;
managementToken: string;
drinkCardValue?: number;
giftAmount?: number;
};
export type DeductionMessage = {
type: "deduction";
to: string;
firstName: string;
amountCents: number;
newBalanceCents: number;
};
export type EmailMessage =
| ConfirmationMessage
| UpdateMessage
| CancellationMessage
| SubscriptionConfirmationMessage
| Reminder24hMessage
| Reminder1hMessage
| PaymentReminderMessage
| PaymentConfirmationMessage
| DeductionMessage;
// ---------------------------------------------------------------------------
// Consumer-side dispatcher — called once per queue message
// ---------------------------------------------------------------------------
export async function dispatchEmailMessage(msg: EmailMessage): Promise<void> {
switch (msg.type) {
case "registrationConfirmation":
await sendConfirmationEmail(msg);
break;
case "updateConfirmation":
await sendUpdateEmail(msg);
break;
case "cancellation":
await sendCancellationEmail(msg);
break;
case "subscriptionConfirmation":
await sendSubscriptionConfirmationEmail({ to: msg.to });
break;
case "reminder24h":
await sendReminder24hEmail(msg);
break;
case "reminder1h":
await sendReminderEmail(msg);
break;
case "paymentReminder":
await sendPaymentReminderEmail(msg);
break;
case "paymentConfirmation":
await sendPaymentConfirmationEmail(msg);
break;
case "deduction":
await sendDeductionEmail(msg);
break;
default:
// Exhaustiveness check — TypeScript will catch unhandled variants at compile time
msg satisfies never;
}
}

View File

@@ -1,276 +1,186 @@
import { env } from "@kk/env/server";
import nodemailer from "nodemailer";
import { EVENT, LOCATION, OPENS } from "./constants";
// Singleton transport — created once per module, reused across all email sends.
// Re-creating it on every call causes EventEmitter listener accumulation in
// long-lived Cloudflare Worker processes, triggering memory leak warnings.
let _transport: nodemailer.Transporter | null | undefined;
// ---------------------------------------------------------------------------
// Transport — singleton so a warm CF isolate reuses the open TCP connection
// ---------------------------------------------------------------------------
let _transport: nodemailer.Transporter | undefined;
function getTransport(): nodemailer.Transporter | null {
if (_transport !== undefined) return _transport;
if (_transport) return _transport;
if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS) {
_transport = null;
// Not cached — re-evaluated on every call so a cold isolate that
// receives vars after module init can still pick them up.
return null;
}
_transport = nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_PORT === 465,
auth: {
user: env.SMTP_USER,
pass: env.SMTP_PASS,
},
auth: { user: env.SMTP_USER, pass: env.SMTP_PASS },
});
return _transport;
}
const from = env.SMTP_FROM ?? "Kunstenkamp <info@kunstenkamp.be>";
const baseUrl = env.BETTER_AUTH_URL ?? "https://kunstenkamp.be";
// ---------------------------------------------------------------------------
// Logging — console.log(JSON) is the only thing visible in CF dashboard
// ---------------------------------------------------------------------------
function registrationConfirmationHtml(params: {
firstName: string;
manageUrl: string;
wantsToPerform: boolean;
artForm?: string | null;
giftAmount?: number;
drinkCardValue?: number;
}) {
const role = params.wantsToPerform
? `Optreden${params.artForm ? `${params.artForm}` : ""}`
export function emailLog(
level: "info" | "warn" | "error",
event: string,
extra?: Record<string, unknown>,
): void {
console.log(JSON.stringify({ level, event, ...extra }));
}
// ---------------------------------------------------------------------------
// HTML helpers
// ---------------------------------------------------------------------------
/** Primary or secondary CTA button */
function btn(
href: string,
label: string,
variant: "primary" | "secondary" = "primary",
): string {
const bg = variant === "primary" ? "#fff" : "rgba(255,255,255,0.15)";
const color = variant === "primary" ? "#214e51" : "#fff";
return `<table cellpadding="0" cellspacing="0" style="margin:0 0 16px;">
<tr><td style="border-radius:2px;background:${bg};">
<a href="${href}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:${color};text-decoration:none;">${label}</a>
</td></tr>
</table>`;
}
/** Info card — single label + value */
function card(label: string, value: string): string {
return `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
<tr><td style="padding:20px 24px;">
<p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">${label}</p>
<p style="margin:0;font-size:18px;color:#fff;font-weight:600;">${value}</p>
</td></tr>
</table>`;
}
/** Payment breakdown card — renders only when totalCents > 0 */
function paymentCard(drinkCardCents: number, giftCents: number): string {
const total = drinkCardCents + giftCents;
if (total === 0) return "";
return `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
<tr><td style="padding:20px 24px;">
<p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);">Drinkkaart: <strong style="color:#fff;">${euro(drinkCardCents)}</strong></p>` : ""}
${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);">Vrijwillige gift: <strong style="color:#fff;">${euro(giftCents)}</strong></p>` : ""}
<p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#fff;font-weight:600;">Totaal: ${euro(total)}</p>
</td></tr>
</table>`;
}
/** Shared text paragraph */
function p(text: string): string {
return `<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">${text}</p>`;
}
/** Muted footnote */
function note(html: string): string {
return `<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">${html}</p>`;
}
// ---------------------------------------------------------------------------
// Email layout shell
// ---------------------------------------------------------------------------
function emailLayout(heading: string, body: string): string {
return `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>${heading}</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
<tr><td style="padding:40px 48px 32px;">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
<h1 style="margin:12px 0 0;font-size:28px;color:#fff;font-weight:700;">${heading}</h1>
</td></tr>
<tr><td style="padding:0 48px 32px;">${body}</td></tr>
<tr><td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);line-height:1.6;">
Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a><br/>
Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
// ---------------------------------------------------------------------------
// Shared send helper — logs attempt/sent/error, skips when SMTP not configured
// ---------------------------------------------------------------------------
async function send(
type: string,
to: string,
subject: string,
html: string,
): Promise<void> {
emailLog("info", "email.attempt", { type, to });
const transport = getTransport();
if (!transport) {
emailLog("warn", "email.skipped", {
type,
to,
reason: "smtp_not_configured",
// Which vars are missing — helps diagnose CF env issues
hasHost: !!env.SMTP_HOST,
hasUser: !!env.SMTP_USER,
hasPass: !!env.SMTP_PASS,
});
return;
}
try {
await transport.sendMail({ from: env.SMTP_FROM, to, subject, html });
emailLog("info", "email.sent", { type, to });
} catch (err) {
emailLog("error", "email.error", { type, to, error: String(err) });
throw err;
}
}
// ---------------------------------------------------------------------------
// Euro formatter
// ---------------------------------------------------------------------------
function euro(cents: number): string {
return `${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;
}
// ---------------------------------------------------------------------------
// Helpers for registration emails
// ---------------------------------------------------------------------------
function roleLabel(wantsToPerform: boolean, artForm?: string | null): string {
return wantsToPerform
? `Optreden${artForm ? `${artForm}` : ""}`
: "Toeschouwer";
const giftCents = params.giftAmount ?? 0;
// drinkCardValue is stored in euros (e.g., 5), giftAmount in cents (e.g., 5000)
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const hasPayment = drinkCardCents > 0 || giftCents > 0;
const formatEuro = (cents: number) =>
`${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;
const paymentSummary = hasPayment
? `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
<tr>
<td style="padding:20px 24px;">
<p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Drinkkaart: <span style="color:#ffffff;font-weight:500;">${formatEuro(drinkCardCents)}</span></p>` : ""}
${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Vrijwillige gift: <span style="color:#ffffff;font-weight:500;">${formatEuro(giftCents)}</span></p>` : ""}
<p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#ffffff;font-weight:600;">Totaal: ${formatEuro(drinkCardCents + giftCents)}</p>
</td>
</tr>
</table>`
: "";
return `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bevestiging inschrijving</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
<!-- Header -->
<tr>
<td style="padding:40px 48px 32px;">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
<h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Je inschrijving is bevestigd!</h1>
</td>
</tr>
<!-- Body -->
<tr>
<td style="padding:0 48px 32px;">
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Hoi ${params.firstName},
</p>
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
We hebben je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 24 april 2026</strong> in goede orde ontvangen.
</p>
<!-- Registration summary -->
<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
<tr>
<td style="padding:20px 24px;">
<p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Jouw rol</p>
<p style="margin:0;font-size:18px;color:#ffffff;font-weight:600;">${role}</p>
</td>
</tr>
</table>
${paymentSummary}
<p style="margin:0 0 24px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Wil je je gegevens later nog aanpassen of je inschrijving annuleren? Gebruik dan de knop hieronder. De link is uniek voor jou — deel hem niet.
</p>
<!-- CTA button -->
<table cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius:2px;background:#ffffff;">
<a href="${params.manageUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
Beheer mijn inschrijving
</a>
</td>
</tr>
</table>
<p style="margin:16px 0 0;font-size:13px;color:rgba(255,255,255,0.4);">
Of kopieer deze link: <span style="color:rgba(255,255,255,0.6);">${params.manageUrl}</span>
</p>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);line-height:1.6;">
Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a><br/>
Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
}
function updateConfirmationHtml(params: {
firstName: string;
manageUrl: string;
wantsToPerform: boolean;
artForm?: string | null;
giftAmount?: number;
drinkCardValue?: number;
}) {
const role = params.wantsToPerform
? `Optreden${params.artForm ? `${params.artForm}` : ""}`
: "Toeschouwer";
const giftCents = params.giftAmount ?? 0;
// drinkCardValue is stored in euros (e.g., 5), giftAmount in cents (e.g., 5000)
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const hasPayment = drinkCardCents > 0 || giftCents > 0;
const formatEuro = (cents: number) =>
`${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;
const paymentSummary = hasPayment
? `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
<tr>
<td style="padding:20px 24px;">
<p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Drinkkaart: <span style="color:#ffffff;font-weight:500;">${formatEuro(drinkCardCents)}</span></p>` : ""}
${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Vrijwillige gift: <span style="color:#ffffff;font-weight:500;">${formatEuro(giftCents)}</span></p>` : ""}
<p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#ffffff;font-weight:600;">Totaal: ${formatEuro(drinkCardCents + giftCents)}</p>
</td>
</tr>
</table>`
: "";
return `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<title>Inschrijving bijgewerkt</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
<tr>
<td style="padding:40px 48px 32px;">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
<h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Inschrijving bijgewerkt</h1>
</td>
</tr>
<tr>
<td style="padding:0 48px 32px;">
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Hoi ${params.firstName},
</p>
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 18 april 2026</strong> is succesvol bijgewerkt.
</p>
<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
<tr>
<td style="padding:20px 24px;">
<p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Jouw rol</p>
<p style="margin:0;font-size:18px;color:#ffffff;font-weight:600;">${role}</p>
</td>
</tr>
</table>
${paymentSummary}
<table cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius:2px;background:#ffffff;">
<a href="${params.manageUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
Bekijk mijn inschrijving
</a>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">
Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
function manageUrl(token: string): string {
return `${env.BETTER_AUTH_URL}/manage/${token}`;
}
function cancellationHtml(params: { firstName: string }) {
return `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<title>Inschrijving geannuleerd</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
<tr>
<td style="padding:40px 48px 32px;">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
<h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Inschrijving geannuleerd</h1>
</td>
</tr>
<tr>
<td style="padding:0 48px 40px;">
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Hoi ${params.firstName},
</p>
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 18 april 2026</strong> is geannuleerd.
</p>
<p style="margin:0;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Van gedachten veranderd? Je kunt je altijd opnieuw inschrijven via <a href="${baseUrl}/#registration" style="color:#ffffff;">kunstenkamp.be</a>.
</p>
</td>
</tr>
<tr>
<td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">
Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
}
// ---------------------------------------------------------------------------
// Emails
// ---------------------------------------------------------------------------
export async function sendConfirmationEmail(params: {
to: string;
@@ -280,26 +190,41 @@ export async function sendConfirmationEmail(params: {
artForm?: string | null;
giftAmount?: number;
drinkCardValue?: number;
signupUrl?: string;
}) {
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping confirmation email");
return;
}
const manageUrl = `${baseUrl}/manage/${params.managementToken}`;
await transport.sendMail({
from,
to: params.to,
subject: "Bevestiging inschrijving — Open Mic Night",
html: registrationConfirmationHtml({
firstName: params.firstName,
manageUrl,
wantsToPerform: params.wantsToPerform,
artForm: params.artForm,
giftAmount: params.giftAmount,
drinkCardValue: params.drinkCardValue,
}),
});
const manage = manageUrl(params.managementToken);
const signup =
params.signupUrl ??
`${env.BETTER_AUTH_URL}/login?signup=1&email=${encodeURIComponent(params.to)}&next=/account`;
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const giftCents = params.giftAmount ?? 0;
await send(
"registrationConfirmation",
params.to,
"Bevestiging inschrijving — Open Mic Night",
emailLayout(
"Je inschrijving is bevestigd!",
p(`Hoi ${params.firstName},`) +
p(
`We hebben je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> in goede orde ontvangen.`,
) +
card("Locatie", LOCATION) +
card("Jouw rol", roleLabel(params.wantsToPerform, params.artForm)) +
paymentCard(drinkCardCents, giftCents) +
p(
"Maak een account aan om je inschrijving te beheren en je Drinkkaart te activeren.",
) +
btn(signup, "Account aanmaken") +
p(
"Wil je je gegevens aanpassen of je inschrijving annuleren? De link hieronder is uniek voor jou — deel hem niet.",
) +
btn(manage, "Beheer mijn inschrijving", "secondary") +
note(
`Of kopieer: <span style="color:rgba(255,255,255,0.6);">${manage}</span>`,
),
),
);
}
export async function sendUpdateEmail(params: {
@@ -311,40 +236,183 @@ export async function sendUpdateEmail(params: {
giftAmount?: number;
drinkCardValue?: number;
}) {
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping update email");
return;
}
const manageUrl = `${baseUrl}/manage/${params.managementToken}`;
await transport.sendMail({
from,
to: params.to,
subject: "Inschrijving bijgewerkt — Open Mic Night",
html: updateConfirmationHtml({
firstName: params.firstName,
manageUrl,
wantsToPerform: params.wantsToPerform,
artForm: params.artForm,
giftAmount: params.giftAmount,
drinkCardValue: params.drinkCardValue,
}),
});
const manage = manageUrl(params.managementToken);
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const giftCents = params.giftAmount ?? 0;
await send(
"updateConfirmation",
params.to,
"Inschrijving bijgewerkt — Open Mic Night",
emailLayout(
"Inschrijving bijgewerkt",
p(`Hoi ${params.firstName},`) +
p(
`Je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> is succesvol bijgewerkt.`,
) +
card("Locatie", LOCATION) +
card("Jouw rol", roleLabel(params.wantsToPerform, params.artForm)) +
paymentCard(drinkCardCents, giftCents) +
btn(manage, "Bekijk mijn inschrijving"),
),
);
}
export async function sendCancellationEmail(params: {
to: string;
firstName: string;
}) {
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping cancellation email");
return;
}
await transport.sendMail({
from,
to: params.to,
subject: "Inschrijving geannuleerd — Open Mic Night",
html: cancellationHtml({ firstName: params.firstName }),
});
await send(
"cancellation",
params.to,
"Inschrijving geannuleerd — Open Mic Night",
emailLayout(
"Inschrijving geannuleerd",
p(`Hoi ${params.firstName},`) +
p(
`Je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> is geannuleerd.`,
) +
p(
`Van gedachten veranderd? Je kunt je altijd opnieuw inschrijven via <a href="${env.BETTER_AUTH_URL}/#registration" style="color:#fff;">kunstenkamp.be</a>.`,
),
),
);
}
export async function sendSubscriptionConfirmationEmail(params: {
to: string;
}) {
await send(
"subscriptionConfirmation",
params.to,
"Herinnering ingepland — Open Mic Night",
emailLayout(
"Je herinnering is ingepland!",
p(
`We sturen een herinnering naar <strong style="color:#fff;">${params.to}</strong> wanneer de inschrijvingen openen.`,
) +
card("Inschrijvingen openen", OPENS) +
p(
"Je ontvangt twee herinneringen: één 24 uur van tevoren en één 1 uur voor de opening.",
) +
p("Wees er snel bij — de plaatsen zijn beperkt!") +
btn(`${env.BETTER_AUTH_URL}/#registration`, "Bekijk de pagina"),
),
);
}
export async function sendReminder24hEmail(params: {
to: string;
firstName?: string | null;
}) {
const greeting = params.firstName ? `Hoi ${params.firstName},` : "Hoi!";
await send(
"reminder24h",
params.to,
"Nog 24 uur — inschrijvingen openen morgen!",
emailLayout(
"Nog 24 uur!",
p(greeting) +
p(
`Morgen openen de inschrijvingen voor <strong style="color:#fff;">${EVENT}</strong>. Zet je wekker!`,
) +
card("Inschrijvingen openen", OPENS) +
p("Wees er snel bij — de plaatsen zijn beperkt!") +
btn(`${env.BETTER_AUTH_URL}/#registration`, "Bekijk de pagina") +
note(
"Je ontvangt dit bericht omdat je een herinnering hebt aangevraagd op kunstenkamp.be.",
),
),
);
}
export async function sendReminderEmail(params: {
to: string;
firstName?: string | null;
}) {
const greeting = params.firstName ? `Hoi ${params.firstName},` : "Hoi!";
await send(
"reminder1h",
params.to,
"Nog 1 uur — inschrijvingen openen straks!",
emailLayout(
"Nog 1 uur!",
p(greeting) +
p(
`Over ongeveer <strong style="color:#fff;">1 uur</strong> openen de inschrijvingen voor <strong style="color:#fff;">${EVENT}</strong>.`,
) +
card("Inschrijvingen openen", OPENS) +
p("Wees er snel bij — de plaatsen zijn beperkt!") +
btn(`${env.BETTER_AUTH_URL}/#registration`, "Schrijf je in") +
note(
"Je ontvangt dit bericht omdat je een herinnering hebt aangevraagd op kunstenkamp.be.",
),
),
);
}
export async function sendPaymentReminderEmail(params: {
to: string;
firstName: string;
managementToken: string;
drinkCardValue?: number;
giftAmount?: number;
}) {
const manage = manageUrl(params.managementToken);
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const giftCents = params.giftAmount ?? 0;
const total = drinkCardCents + giftCents;
const amountNote =
total > 0
? `Je betaling van <strong style="color:#fff;">${euro(total)}</strong> staat nog open.`
: "Je betaling staat nog open.";
await send(
"paymentReminder",
params.to,
"Herinnering: betaling open — Open Mic Night",
emailLayout(
"Betaling nog open",
p(`Hoi ${params.firstName},`) +
p(
`Je hebt je ingeschreven voor <strong style="color:#fff;">${EVENT}</strong>, maar we hebben nog geen betaling ontvangen.`,
) +
card("Locatie", LOCATION) +
p(`${amountNote} Log in op je account om te betalen.`) +
btn(`${env.BETTER_AUTH_URL}/account`, "Betaal nu") +
note(
`Je inschrijving beheren? <a href="${manage}" style="color:rgba(255,255,255,0.6);">Klik hier</a>`,
),
),
);
}
export async function sendPaymentConfirmationEmail(params: {
to: string;
firstName: string;
managementToken: string;
drinkCardValue?: number;
giftAmount?: number;
}) {
const manage = manageUrl(params.managementToken);
const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
const giftCents = params.giftAmount ?? 0;
await send(
"paymentConfirmation",
params.to,
"Betaling ontvangen — Open Mic Night",
emailLayout(
"Betaling ontvangen!",
p(`Hoi ${params.firstName},`) +
p(
`We hebben je betaling voor <strong style="color:#fff;">${EVENT}</strong> in goede orde ontvangen. Tot dan!`,
) +
card("Locatie", LOCATION) +
paymentCard(drinkCardCents, giftCents) +
btn(manage, "Beheer mijn inschrijving", "secondary"),
),
);
}

View File

@@ -1,13 +1,15 @@
import { env } from "@kk/env/server";
import nodemailer from "nodemailer";
import { emailLog } from "../email";
// Re-use the same SMTP transport strategy as email.ts.
let _transport: nodemailer.Transporter | null | undefined;
// Re-use the same SMTP transport strategy as email.ts:
// only cache a successfully-created transporter; never cache null so that a
// cold isolate that receives env vars after module init can still pick them up.
let _transport: nodemailer.Transporter | undefined;
function getTransport(): nodemailer.Transporter | null {
if (_transport !== undefined) return _transport;
if (_transport) return _transport;
if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS) {
_transport = null;
return null;
}
_transport = nodemailer.createTransport({
@@ -22,9 +24,6 @@ function getTransport(): nodemailer.Transporter | null {
return _transport;
}
const from = env.SMTP_FROM ?? "Kunstenkamp <info@kunstenkamp.be>";
const baseUrl = env.BETTER_AUTH_URL ?? "https://kunstenkamp.be";
function formatEuro(cents: number): string {
return new Intl.NumberFormat("nl-BE", {
style: "currency",
@@ -116,7 +115,7 @@ function deductionHtml(params: {
/**
* Send a deduction notification email to the cardholder.
* Fire-and-forget: errors are logged but not re-thrown.
* Throws on SMTP error so the queue consumer can retry.
*/
export async function sendDeductionEmail(params: {
to: string;
@@ -124,9 +123,18 @@ export async function sendDeductionEmail(params: {
amountCents: number;
newBalanceCents: number;
}): Promise<void> {
emailLog("info", "email.attempt", { type: "deduction", to: params.to });
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping deduction email");
emailLog("warn", "email.skipped", {
type: "deduction",
to: params.to,
reason: "smtp_not_configured",
hasHost: !!env.SMTP_HOST,
hasUser: !!env.SMTP_USER,
hasPass: !!env.SMTP_PASS,
});
return;
}
@@ -144,16 +152,26 @@ export async function sendDeductionEmail(params: {
currency: "EUR",
}).format(params.amountCents / 100);
await transport.sendMail({
from,
to: params.to,
subject: `Drinkkaart — ${amountFormatted} afgeschreven`,
html: deductionHtml({
firstName: params.firstName,
amountCents: params.amountCents,
newBalanceCents: params.newBalanceCents,
dateTime,
drinkkaartUrl: `${baseUrl}/drinkkaart`,
}),
});
try {
await transport.sendMail({
from: env.SMTP_FROM,
to: params.to,
subject: `Drinkkaart — ${amountFormatted} afgeschreven`,
html: deductionHtml({
firstName: params.firstName,
amountCents: params.amountCents,
newBalanceCents: params.newBalanceCents,
dateTime,
drinkkaartUrl: `${env.BETTER_AUTH_URL}/drinkkaart`,
}),
});
emailLog("info", "email.sent", { type: "deduction", to: params.to });
} catch (err) {
emailLog("error", "email.error", {
type: "deduction",
to: params.to,
error: String(err),
});
throw err;
}
}

View File

@@ -9,6 +9,7 @@ import { user } from "@kk/db/schema/auth";
import { ORPCError } from "@orpc/server";
import { and, desc, eq, gte, lte, sql } from "drizzle-orm";
import { z } from "zod";
import type { EmailMessage } from "../email-queue";
import { adminProcedure, protectedProcedure } from "../index";
import { sendDeductionEmail } from "../lib/drinkkaart-email";
import {
@@ -134,82 +135,49 @@ export const drinkkaartRouter = {
.handler(async ({ input, context }) => {
const { env: serverEnv, session } = context;
if (
!serverEnv.LEMON_SQUEEZY_API_KEY ||
!serverEnv.LEMON_SQUEEZY_STORE_ID ||
!serverEnv.LEMON_SQUEEZY_VARIANT_ID
) {
if (!serverEnv.MOLLIE_API_KEY) {
throw new ORPCError("INTERNAL_SERVER_ERROR", {
message: "LemonSqueezy is niet geconfigureerd",
message: "Mollie is niet geconfigureerd",
});
}
const card = await getOrCreateDrinkkaart(session.user.id);
const response = await fetch(
"https://api.lemonsqueezy.com/v1/checkouts",
{
method: "POST",
headers: {
Accept: "application/vnd.api+json",
"Content-Type": "application/vnd.api+json",
Authorization: `Bearer ${serverEnv.LEMON_SQUEEZY_API_KEY}`,
},
body: JSON.stringify({
data: {
type: "checkouts",
attributes: {
custom_price: input.amountCents,
product_options: {
name: "Drinkkaart Opladen",
description: `Opwaardering van ${formatCents(input.amountCents)}`,
redirect_url: `${serverEnv.BETTER_AUTH_URL}/account?topup=success`,
},
checkout_data: {
email: session.user.email,
name: session.user.name,
custom: {
type: "drinkkaart_topup",
drinkkaartId: card.id,
userId: session.user.id,
},
},
checkout_options: {
embed: false,
locale: "nl",
},
},
relationships: {
store: {
data: {
type: "stores",
id: serverEnv.LEMON_SQUEEZY_STORE_ID,
},
},
variant: {
data: {
type: "variants",
id: serverEnv.LEMON_SQUEEZY_VARIANT_ID,
},
},
},
},
}),
// Mollie amounts must be formatted as "10.00" (string, 2 decimal places)
const amountValue = (input.amountCents / 100).toFixed(2);
const response = await fetch("https://api.mollie.com/v2/payments", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${serverEnv.MOLLIE_API_KEY}`,
},
);
body: JSON.stringify({
amount: { value: amountValue, currency: "EUR" },
description: `Drinkkaart Opladen — ${formatCents(input.amountCents)}`,
redirectUrl: `${serverEnv.BETTER_AUTH_URL}/account?topup=success`,
webhookUrl: `${serverEnv.BETTER_AUTH_URL}/api/webhook/mollie`,
locale: "nl_NL",
metadata: {
type: "drinkkaart_topup",
drinkkaartId: card.id,
userId: session.user.id,
},
}),
});
if (!response.ok) {
const errorData = await response.json();
console.error("LemonSqueezy Drinkkaart checkout error:", errorData);
console.error("Mollie Drinkkaart checkout error:", errorData);
throw new ORPCError("INTERNAL_SERVER_ERROR", {
message: "Kon checkout niet aanmaken",
});
}
const data = (await response.json()) as {
data?: { attributes?: { url?: string } };
_links?: { checkout?: { href?: string } };
};
const checkoutUrl = data.data?.attributes?.url;
const checkoutUrl = data._links?.checkout?.href;
if (!checkoutUrl) {
throw new ORPCError("INTERNAL_SERVER_ERROR", {
message: "Geen checkout URL ontvangen",
@@ -372,7 +340,7 @@ export const drinkkaartRouter = {
createdAt: now,
});
// Fire-and-forget deduction email
// Fire-and-forget deduction email (via queue when available)
const cardUser = await db
.select({ email: user.email, name: user.name })
.from(user)
@@ -381,14 +349,21 @@ export const drinkkaartRouter = {
.then((r) => r[0]);
if (cardUser) {
sendDeductionEmail({
const deductionMsg: EmailMessage = {
type: "deduction",
to: cardUser.email,
firstName: cardUser.name.split(" ")[0] ?? cardUser.name,
amountCents: input.amountCents,
newBalanceCents: balanceAfter,
}).catch((err) =>
console.error("Failed to send deduction email:", err),
);
};
if (context.emailQueue) {
await context.emailQueue.send(deductionMsg);
} else {
await sendDeductionEmail(deductionMsg).catch((err) =>
console.error("Failed to send deduction email:", err),
);
}
}
return {

View File

@@ -1,28 +1,72 @@
import { randomUUID } from "node:crypto";
import { db } from "@kk/db";
import { adminRequest, registration } from "@kk/db/schema";
import { adminRequest, registration, reminder } from "@kk/db/schema";
import { user } from "@kk/db/schema/auth";
import { drinkkaart, drinkkaartTopup } from "@kk/db/schema/drinkkaart";
import { env } from "@kk/env/server";
import type { RouterClient } from "@orpc/server";
import { and, count, desc, eq, gte, isNull, like, lte, sum } from "drizzle-orm";
import { z } from "zod";
import {
and,
count,
desc,
eq,
gte,
isNull,
like,
lte,
or,
sum,
} from "drizzle-orm";
import { z } from "zod";
import { REGISTRATION_OPENS_AT } from "../constants";
import {
emailLog,
sendCancellationEmail,
sendConfirmationEmail,
sendPaymentReminderEmail,
sendReminder24hEmail,
sendReminderEmail,
sendSubscriptionConfirmationEmail,
sendUpdateEmail,
} from "../email";
import type { EmailMessage } from "../email-queue";
// Minimal CF Queue binding shape (mirrors context.ts)
type EmailQueue = {
send(
message: EmailMessage,
options?: { contentType?: string },
): Promise<void>;
sendBatch(
messages: Array<{ body: EmailMessage }>,
options?: { contentType?: string },
): Promise<void>;
};
import { adminProcedure, protectedProcedure, publicProcedure } from "../index";
import { generateQrSecret } from "../lib/drinkkaart-utils";
import { drinkkaartRouter } from "./drinkkaart";
// Reminder windows derived from the canonical registration open date
const REMINDER_1H_WINDOW_START = new Date(
REGISTRATION_OPENS_AT.getTime() - 60 * 60 * 1000,
);
const REMINDER_24H_WINDOW_START = new Date(
REGISTRATION_OPENS_AT.getTime() - 25 * 60 * 60 * 1000,
);
const REMINDER_24H_WINDOW_END = new Date(
REGISTRATION_OPENS_AT.getTime() - 23 * 60 * 60 * 1000,
);
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
/** Drink card price in euros: €5 base + €2 per extra guest. */
const MAX_WATCHERS = 70; // max total watcher spots (people, not registrations)
/** Drink card price in euros: €5 per person (primary + guests). */
function drinkCardEuros(guestCount: number): number {
return 5 + guestCount * 2;
return 5 + guestCount * 5;
}
/** Drink card price in cents for payment processing. */
@@ -36,8 +80,6 @@ function parseGuestsJson(raw: string | null): Array<{
lastName: string;
email?: string;
phone?: string;
birthdate?: string;
postcode?: string;
}> {
if (!raw) return [];
try {
@@ -52,7 +94,7 @@ function parseGuestsJson(raw: string | null): Array<{
* Credits a watcher's drinkCardValue to their drinkkaart account.
*
* Safe to call multiple times — the `drinkkaartCreditedAt IS NULL` guard and the
* `lemonsqueezy_order_id` UNIQUE constraint together prevent double-crediting even
* `mollie_payment_id` UNIQUE constraint together prevent double-crediting even
* if called concurrently (webhook + signup racing each other).
*
* Returns a status string describing the outcome.
@@ -162,11 +204,11 @@ export async function creditRegistrationToAccount(
return { credited: false, amountCents: 0, status: "already_credited" };
}
// Record the topup. Re-use the registration's lemonsqueezyOrderId so the
// Record the topup. Re-use the registration's molliePaymentId so the
// topup row is clearly linked to the original payment. We prefix with
// "reg_" to distinguish from direct drinkkaart top-up orders if needed.
const topupPaymentId = reg.lemonsqueezyOrderId
? `reg_${reg.lemonsqueezyOrderId}`
const topupPaymentId = reg.molliePaymentId
? `reg_${reg.molliePaymentId}`
: null;
await db.insert(drinkkaartTopup).values({
@@ -177,7 +219,7 @@ export async function creditRegistrationToAccount(
balanceBefore,
balanceAfter,
type: "payment",
lemonsqueezyOrderId: topupPaymentId,
molliePaymentId: topupPaymentId,
adminId: null,
reason: "Drinkkaart bij registratie",
paidAt: reg.paidAt ?? new Date(),
@@ -229,8 +271,8 @@ const coreRegistrationFields = {
lastName: z.string().min(1),
email: z.string().email(),
phone: z.string().optional(),
postcode: z.string().min(1),
birthdate: z.string().min(1),
postcode: z.string().min(1),
registrationType: registrationTypeSchema.default("watcher"),
artForm: z.string().optional(),
experience: z.string().optional(),
@@ -265,6 +307,28 @@ export const appRouter = {
healthCheck: publicProcedure.handler(() => "OK"),
drinkkaart: drinkkaartRouter,
getWatcherCapacity: publicProcedure.handler(async () => {
const rows = await db
.select({ guests: registration.guests })
.from(registration)
.where(
and(
eq(registration.registrationType, "watcher"),
isNull(registration.cancelledAt),
),
);
const takenSpots = rows.reduce((sum, r) => {
const g = r.guests ? (JSON.parse(r.guests) as unknown[]) : [];
return sum + 1 + g.length;
}, 0);
return {
total: MAX_WATCHERS,
taken: takenSpots,
available: Math.max(0, MAX_WATCHERS - takenSpots),
isFull: takenSpots >= MAX_WATCHERS,
};
}),
privateData: protectedProcedure.handler(({ context }) => ({
message: "This is private",
user: context.session?.user,
@@ -272,19 +336,42 @@ export const appRouter = {
submitRegistration: publicProcedure
.input(submitRegistrationSchema)
.handler(async ({ input }) => {
.handler(async ({ input, context }) => {
const managementToken = randomUUID();
const isPerformer = input.registrationType === "performer";
const guests = isPerformer ? [] : (input.guests ?? []);
// Enforce max watcher capacity (70 people total, counting guests)
if (!isPerformer) {
const rows = await db
.select({ guests: registration.guests })
.from(registration)
.where(
and(
eq(registration.registrationType, "watcher"),
isNull(registration.cancelledAt),
),
);
const takenSpots = rows.reduce((sum, r) => {
const g = r.guests ? (JSON.parse(r.guests) as unknown[]) : [];
return sum + 1 + g.length;
}, 0);
const newSpots = 1 + guests.length;
if (takenSpots + newSpots > MAX_WATCHERS) {
throw new Error(
`Er zijn helaas niet genoeg plaatsen meer beschikbaar. Nog ${MAX_WATCHERS - takenSpots} ${MAX_WATCHERS - takenSpots === 1 ? "plaats" : "plaatsen"} vrij.`,
);
}
}
await db.insert(registration).values({
id: randomUUID(),
firstName: input.firstName,
lastName: input.lastName,
email: input.email,
phone: input.phone || null,
postcode: input.postcode,
birthdate: input.birthdate,
postcode: input.postcode,
registrationType: input.registrationType,
artForm: isPerformer ? input.artForm || null : null,
experience: isPerformer ? input.experience || null : null,
@@ -296,7 +383,8 @@ export const appRouter = {
managementToken,
});
await sendConfirmationEmail({
const confirmationMsg: EmailMessage = {
type: "registrationConfirmation",
to: input.email,
firstName: input.firstName,
managementToken,
@@ -304,9 +392,18 @@ export const appRouter = {
artForm: input.artForm,
giftAmount: input.giftAmount,
drinkCardValue: isPerformer ? 0 : drinkCardEuros(guests.length),
}).catch((err) =>
console.error("Failed to send confirmation email:", err),
);
};
if (context.emailQueue) {
await context.emailQueue.send(confirmationMsg);
} else {
await sendConfirmationEmail(confirmationMsg).catch((err) =>
emailLog("error", "email.catch", {
type: "confirmation",
error: String(err),
}),
);
}
return { success: true, managementToken };
}),
@@ -329,7 +426,7 @@ export const appRouter = {
updateRegistration: publicProcedure
.input(updateRegistrationSchema)
.handler(async ({ input }) => {
.handler(async ({ input, context }) => {
const row = await getActiveRegistration(input.token);
const isPerformer = input.registrationType === "performer";
@@ -372,8 +469,8 @@ export const appRouter = {
lastName: input.lastName,
email: input.email,
phone: input.phone || null,
postcode: input.postcode,
birthdate: input.birthdate,
postcode: input.postcode,
registrationType: input.registrationType,
artForm: isPerformer ? input.artForm || null : null,
experience: isPerformer ? input.experience || null : null,
@@ -387,7 +484,8 @@ export const appRouter = {
})
.where(eq(registration.managementToken, input.token));
await sendUpdateEmail({
const updateMsg: EmailMessage = {
type: "updateConfirmation",
to: input.email,
firstName: input.firstName,
managementToken: input.token,
@@ -395,14 +493,25 @@ export const appRouter = {
artForm: input.artForm,
giftAmount: input.giftAmount,
drinkCardValue: isPerformer ? 0 : drinkCardEuros(guests.length),
}).catch((err) => console.error("Failed to send update email:", err));
};
if (context.emailQueue) {
await context.emailQueue.send(updateMsg);
} else {
await sendUpdateEmail(updateMsg).catch((err) =>
emailLog("error", "email.catch", {
type: "update",
error: String(err),
}),
);
}
return { success: true };
}),
cancelRegistration: publicProcedure
.input(z.object({ token: z.string().uuid() }))
.handler(async ({ input }) => {
.handler(async ({ input, context }) => {
const row = await getActiveRegistration(input.token);
await db
@@ -410,12 +519,22 @@ export const appRouter = {
.set({ cancelledAt: new Date() })
.where(eq(registration.managementToken, input.token));
await sendCancellationEmail({
const cancellationMsg: EmailMessage = {
type: "cancellation",
to: row.email,
firstName: row.firstName,
}).catch((err) =>
console.error("Failed to send cancellation email:", err),
);
};
if (context.emailQueue) {
await context.emailQueue.send(cancellationMsg);
} else {
await sendCancellationEmail(cancellationMsg).catch((err) =>
emailLog("error", "email.catch", {
type: "cancellation",
error: String(err),
}),
);
}
return { success: true };
}),
@@ -428,7 +547,7 @@ export const appRouter = {
if (input.search) {
const term = `%${input.search}%`;
conditions.push(
and(
or(
like(registration.firstName, term),
like(registration.lastName, term),
like(registration.email, term),
@@ -476,27 +595,49 @@ export const appRouter = {
const today = new Date();
today.setHours(0, 0, 0, 0);
const [totalResult, todayResult, artFormResult, typeResult, giftResult] =
await Promise.all([
db.select({ count: count() }).from(registration),
db
.select({ count: count() })
.from(registration)
.where(gte(registration.createdAt, today)),
db
.select({ artForm: registration.artForm, count: count() })
.from(registration)
.where(eq(registration.registrationType, "performer"))
.groupBy(registration.artForm),
db
.select({
registrationType: registration.registrationType,
count: count(),
})
.from(registration)
.groupBy(registration.registrationType),
db.select({ total: sum(registration.giftAmount) }).from(registration),
]);
const [
totalResult,
todayResult,
artFormResult,
typeResult,
giftResult,
watcherGuestRows,
] = await Promise.all([
db.select({ count: count() }).from(registration),
db
.select({ count: count() })
.from(registration)
.where(gte(registration.createdAt, today)),
db
.select({ artForm: registration.artForm, count: count() })
.from(registration)
.where(eq(registration.registrationType, "performer"))
.groupBy(registration.artForm),
db
.select({
registrationType: registration.registrationType,
count: count(),
})
.from(registration)
.groupBy(registration.registrationType),
db.select({ total: sum(registration.giftAmount) }).from(registration),
// Fetch guests column for all watcher registrations to count total guests
db
.select({ guests: registration.guests })
.from(registration)
.where(
and(
eq(registration.registrationType, "watcher"),
isNull(registration.cancelledAt),
),
),
]);
// Sum up all guest counts across all watcher registrations
const totalGuestCount = watcherGuestRows.reduce((sum, r) => {
const guests = parseGuestsJson(r.guests);
return sum + guests.length;
}, 0);
return {
total: totalResult[0]?.count ?? 0,
@@ -510,6 +651,7 @@ export const appRouter = {
count: r.count,
})),
totalGiftRevenue: giftResult[0]?.total ?? 0,
totalGuestCount,
};
}),
@@ -519,63 +661,106 @@ export const appRouter = {
.from(registration)
.orderBy(desc(registration.createdAt));
const escapeCell = (val: string) => `"${val.replace(/"/g, '""')}"`;
// Each person (registrant + guests) gets their own row.
// Guest rows reference the registrant via "Registration ID".
const headers = [
"ID",
"Row Type", // "registrant" | "guest"
"Registration ID", // UUID of the parent registration (same for registrant + its guests)
"First Name",
"Last Name",
"Email",
"Phone",
"Postcode",
"Birthdate",
"Postcode",
// Registrant-only fields (blank for guest rows)
"Type",
"Art Form",
"Experience",
"Is Over 16",
"Drink Card Value",
"Gift Amount",
"Guest Count",
"Guests",
"Drink Card Value (EUR)",
"Gift Amount (cents)",
"Payment Status",
"Paid At",
"Extra Questions",
"Cancelled At",
"Created At",
];
const rows = data.map((r) => {
const guests = parseGuestsJson(r.guests);
const guestSummary = guests
.map(
(g) =>
`${g.firstName} ${g.lastName}${g.birthdate ? ` (${g.birthdate})` : ""}${g.postcode ? ` [${g.postcode}]` : ""}${g.email ? ` <${g.email}>` : ""}${g.phone ? ` (${g.phone})` : ""}`,
)
.join(" | ");
return [
const rows: string[][] = [];
for (const r of data) {
const guests = parseGuestsJson(r.guests) as Array<{
firstName: string;
lastName: string;
email?: string;
phone?: string;
birthdate?: string;
postcode?: string;
}>;
const paymentStatus =
r.paymentStatus === "paid"
? "Paid"
: r.paymentStatus === "extra_payment_pending"
? "Extra Payment Pending"
: "Pending";
// Registrant row
rows.push([
"registrant",
r.id,
r.firstName,
r.lastName,
r.email,
r.phone || "",
r.postcode || "",
r.birthdate || "",
r.registrationType,
r.postcode || "",
r.registrationType ?? "",
r.artForm || "",
r.experience || "",
r.isOver16 ? "Yes" : "No",
String(r.drinkCardValue ?? 0),
String(r.giftAmount ?? 0),
String(guests.length),
guestSummary,
r.paymentStatus === "paid" ? "Paid" : "Pending",
paymentStatus,
r.paidAt ? r.paidAt.toISOString() : "",
r.extraQuestions || "",
r.cancelledAt ? r.cancelledAt.toISOString() : "",
r.createdAt.toISOString(),
];
});
]);
// One row per guest — link back to parent registration via Registration ID
for (const g of guests) {
rows.push([
"guest",
r.id,
g.firstName,
g.lastName,
g.email || "",
g.phone || "",
g.birthdate || "",
g.postcode || "",
// Registrant-only fields left blank
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
]);
}
}
const csvContent = [
headers.join(","),
headers.map(escapeCell).join(","),
...rows.map((row) =>
row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(","),
row.map((cell) => escapeCell(String(cell))).join(","),
),
].join("\n");
@@ -597,7 +782,7 @@ export const appRouter = {
return result;
}),
getMyRegistrations: protectedProcedure.handler(async ({ context }) => {
getMyRegistration: protectedProcedure.handler(async ({ context }) => {
const email = context.session.user.email;
const rows = await db
@@ -606,12 +791,16 @@ export const appRouter = {
.where(
and(eq(registration.email, email), isNull(registration.cancelledAt)),
)
.orderBy(desc(registration.createdAt));
.orderBy(desc(registration.createdAt))
.limit(1);
return rows.map((row) => ({
const row = rows[0];
if (!row) return null;
return {
...row,
guests: parseGuestsJson(row.guests),
}));
};
}),
// ---------------------------------------------------------------------------
@@ -739,6 +928,166 @@ export const appRouter = {
return { success: true, message: "Admin toegang geweigerd" };
}),
// ---------------------------------------------------------------------------
// Reminder opt-in
// ---------------------------------------------------------------------------
/**
* Subscribe an email address to receive reminders before registration opens:
* one 24 hours before and one 1 hour before. Silently deduplicates — if the
* email is already subscribed, returns ok:true without error. Returns
* ok:false if registration is already open.
*/
subscribeReminder: publicProcedure
.input(z.object({ email: z.string().email() }))
.handler(async ({ input, context }) => {
const now = Date.now();
// Registration is already open — no point subscribing
if (now >= REGISTRATION_OPENS_AT.getTime()) {
return { ok: false, reason: "already_open" as const };
}
// Check for an existing subscription (silent dedup)
const existing = await db
.select({ id: reminder.id })
.from(reminder)
.where(eq(reminder.email, input.email))
.limit(1)
.then((rows) => rows[0]);
if (existing) {
return { ok: true };
}
await db.insert(reminder).values({
id: randomUUID(),
email: input.email,
});
const subMsg: EmailMessage = {
type: "subscriptionConfirmation",
to: input.email,
};
if (context.emailQueue) {
await context.emailQueue.send(subMsg);
} else {
// Awaited — CF Workers abandon unawaited promises when the response
// returns. Mail errors are caught so they don't fail the request.
await sendSubscriptionConfirmationEmail({ to: input.email }).catch(
(err) =>
emailLog("error", "email.catch", {
type: "subscription_confirmation",
to: input.email,
error: String(err),
}),
);
}
return { ok: true };
}),
/**
* Send pending reminder emails to all opted-in addresses.
* Protected by a shared secret (`CRON_SECRET`) passed as an Authorization
* header. Should be called by a Cloudflare Cron Trigger at the top of
* every hour, or directly via `POST /api/cron/reminders`.
*
* Fires two waves:
* - 24 hours before: window [REGISTRATION_OPENS_AT - 25h, REGISTRATION_OPENS_AT - 23h)
* - 1 hour before: window [REGISTRATION_OPENS_AT - 1h, REGISTRATION_OPENS_AT)
*/
sendReminders: publicProcedure
.input(z.object({ secret: z.string() }))
.handler(async ({ input }) => {
// Validate the shared secret
if (!env.CRON_SECRET || input.secret !== env.CRON_SECRET) {
throw new Error("Unauthorized");
}
const now = Date.now();
const in24hWindow =
now >= REMINDER_24H_WINDOW_START.getTime() &&
now < REMINDER_24H_WINDOW_END.getTime();
const in1hWindow =
now >= REMINDER_1H_WINDOW_START.getTime() &&
now < REGISTRATION_OPENS_AT.getTime();
const activeWindow = in24hWindow ? "24h" : in1hWindow ? "1h" : null;
emailLog("info", "reminders.cron.tick", { activeWindow });
if (!in24hWindow && !in1hWindow) {
return { sent: 0, skipped: true, reason: "outside_window" as const };
}
let sent = 0;
const errors: string[] = [];
if (in24hWindow) {
// Fetch reminders where the 24h email has not been sent yet
const pending = await db
.select()
.from(reminder)
.where(isNull(reminder.sent24hAt));
emailLog("info", "reminders.24h.pending", { count: pending.length });
for (const row of pending) {
try {
await sendReminder24hEmail({ to: row.email });
await db
.update(reminder)
.set({ sent24hAt: new Date() })
.where(eq(reminder.id, row.id));
sent++;
} catch (err) {
errors.push(`24h ${row.email}: ${String(err)}`);
emailLog("error", "email.catch", {
type: "reminder_24h",
to: row.email,
error: String(err),
});
}
}
}
if (in1hWindow) {
// Fetch reminders where the 1h email has not been sent yet
const pending = await db
.select()
.from(reminder)
.where(isNull(reminder.sentAt));
emailLog("info", "reminders.1h.pending", { count: pending.length });
for (const row of pending) {
try {
await sendReminderEmail({ to: row.email });
await db
.update(reminder)
.set({ sentAt: new Date() })
.where(eq(reminder.id, row.id));
sent++;
} catch (err) {
errors.push(`1h ${row.email}: ${String(err)}`);
emailLog("error", "email.catch", {
type: "reminder_1h",
to: row.email,
error: String(err),
});
}
}
}
emailLog("info", "reminders.cron.done", {
sent,
errorCount: errors.length,
});
return { sent, skipped: false, errors };
}),
// ---------------------------------------------------------------------------
// Checkout
// ---------------------------------------------------------------------------
@@ -751,12 +1100,8 @@ export const appRouter = {
}),
)
.handler(async ({ input }) => {
if (
!env.LEMON_SQUEEZY_API_KEY ||
!env.LEMON_SQUEEZY_STORE_ID ||
!env.LEMON_SQUEEZY_VARIANT_ID
) {
throw new Error("LemonSqueezy is niet geconfigureerd");
if (!env.MOLLIE_API_KEY) {
throw new Error("Mollie is niet geconfigureerd");
}
const rows = await db
@@ -809,66 +1154,37 @@ export const appRouter = {
const redirectUrl =
input.redirectUrl ?? `${env.CORS_ORIGIN}/manage/${input.token}`;
const response = await fetch(
"https://api.lemonsqueezy.com/v1/checkouts",
{
method: "POST",
headers: {
Accept: "application/vnd.api+json",
"Content-Type": "application/vnd.api+json",
Authorization: `Bearer ${env.LEMON_SQUEEZY_API_KEY}`,
},
body: JSON.stringify({
data: {
type: "checkouts",
attributes: {
custom_price: amountInCents,
product_options: {
name: "Kunstenkamp Evenement",
description: productDescription,
redirect_url: redirectUrl,
},
checkout_data: {
email: row.email,
name: `${row.firstName} ${row.lastName}`,
custom: {
registration_token: input.token,
},
},
checkout_options: {
embed: false,
locale: "nl",
},
},
relationships: {
store: {
data: {
type: "stores",
id: env.LEMON_SQUEEZY_STORE_ID,
},
},
variant: {
data: {
type: "variants",
id: env.LEMON_SQUEEZY_VARIANT_ID,
},
},
},
},
}),
// Mollie amounts must be formatted as "10.00" (string, 2 decimal places)
const amountValue = (amountInCents / 100).toFixed(2);
const webhookUrl = `${env.CORS_ORIGIN}/api/webhook/mollie`;
const response = await fetch("https://api.mollie.com/v2/payments", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${env.MOLLIE_API_KEY}`,
},
);
body: JSON.stringify({
amount: { value: amountValue, currency: "EUR" },
description: `Kunstenkamp Evenement — ${productDescription}`,
redirectUrl,
webhookUrl,
locale: "nl_NL",
metadata: { registration_token: input.token },
}),
});
if (!response.ok) {
const errorData = await response.json();
console.error("LemonSqueezy checkout error:", errorData);
console.error("Mollie checkout error:", errorData);
throw new Error("Kon checkout niet aanmaken");
}
const checkoutData = (await response.json()) as {
data?: { attributes?: { url?: string } };
_links?: { checkout?: { href?: string } };
};
const checkoutUrl = checkoutData.data?.attributes?.url;
const checkoutUrl = checkoutData._links?.checkout?.href;
if (!checkoutUrl) throw new Error("Geen checkout URL ontvangen");
@@ -878,3 +1194,181 @@ export const appRouter = {
export type AppRouter = typeof appRouter;
export type AppRouterClient = RouterClient<typeof appRouter>;
/**
* Standalone function that sends pending reminder emails.
* Exported so that the Cloudflare Cron HTTP handler can call it directly
* without needing drizzle-orm as a direct dependency of apps/web.
*
* When `emailQueue` is provided, reminder fan-outs mark the DB rows
* optimistically before calling `sendBatch()` — preventing re-enqueue on
* the next cron tick while still letting the queue handle email delivery
* and retries. Payment reminders always run directly since they need
* per-row DB updates tightly coupled to the send.
*/
export async function runSendReminders(emailQueue?: EmailQueue): Promise<{
sent: number;
skipped: boolean;
reason?: string;
errors: string[];
}> {
const now = Date.now();
const in24hWindow =
now >= REMINDER_24H_WINDOW_START.getTime() &&
now < REMINDER_24H_WINDOW_END.getTime();
const in1hWindow =
now >= REMINDER_1H_WINDOW_START.getTime() &&
now < REGISTRATION_OPENS_AT.getTime();
const activeWindow = in24hWindow ? "24h" : in1hWindow ? "1h" : null;
emailLog("info", "reminders.cron.tick", { activeWindow });
if (!in24hWindow && !in1hWindow) {
return { sent: 0, skipped: true, reason: "outside_window", errors: [] };
}
let sent = 0;
const errors: string[] = [];
if (in24hWindow) {
const pending = await db
.select()
.from(reminder)
.where(isNull(reminder.sent24hAt));
emailLog("info", "reminders.24h.pending", { count: pending.length });
if (emailQueue && pending.length > 0) {
// Mark rows optimistically before enqueuing — prevents re-enqueue on the
// next cron tick if the queue send succeeds but the consumer hasn't run yet.
for (const row of pending) {
await db
.update(reminder)
.set({ sent24hAt: new Date() })
.where(eq(reminder.id, row.id));
}
await emailQueue.sendBatch(
pending.map((row) => ({
body: {
type: "reminder24h" as const,
to: row.email,
} satisfies EmailMessage,
})),
);
sent += pending.length;
} else {
for (const row of pending) {
try {
await sendReminder24hEmail({ to: row.email });
await db
.update(reminder)
.set({ sent24hAt: new Date() })
.where(eq(reminder.id, row.id));
sent++;
} catch (err) {
errors.push(`24h ${row.email}: ${String(err)}`);
emailLog("error", "email.catch", {
type: "reminder_24h",
to: row.email,
error: String(err),
});
}
}
}
}
if (in1hWindow) {
const pending = await db
.select()
.from(reminder)
.where(isNull(reminder.sentAt));
emailLog("info", "reminders.1h.pending", { count: pending.length });
if (emailQueue && pending.length > 0) {
// Mark rows optimistically before enqueuing — prevents re-enqueue on the
// next cron tick if the queue send succeeds but the consumer hasn't run yet.
for (const row of pending) {
await db
.update(reminder)
.set({ sentAt: new Date() })
.where(eq(reminder.id, row.id));
}
await emailQueue.sendBatch(
pending.map((row) => ({
body: {
type: "reminder1h" as const,
to: row.email,
} satisfies EmailMessage,
})),
);
sent += pending.length;
} else {
for (const row of pending) {
try {
await sendReminderEmail({ to: row.email });
await db
.update(reminder)
.set({ sentAt: new Date() })
.where(eq(reminder.id, row.id));
sent++;
} catch (err) {
errors.push(`1h ${row.email}: ${String(err)}`);
emailLog("error", "email.catch", {
type: "reminder_1h",
to: row.email,
error: String(err),
});
}
}
}
}
// Payment reminders: watchers with pending payment older than 3 days.
// Always run directly (not via queue) — each row needs a DB update after send.
const threeDaysAgo = now - 3 * 24 * 60 * 60 * 1000;
const unpaidWatchers = await db
.select()
.from(registration)
.where(
and(
eq(registration.registrationType, "watcher"),
eq(registration.paymentStatus, "pending"),
isNull(registration.paymentReminderSentAt),
lte(registration.createdAt, new Date(threeDaysAgo)),
),
);
emailLog("info", "reminders.payment.pending", {
count: unpaidWatchers.length,
});
for (const reg of unpaidWatchers) {
if (!reg.managementToken) continue;
try {
await sendPaymentReminderEmail({
to: reg.email,
firstName: reg.firstName,
managementToken: reg.managementToken,
drinkCardValue: reg.drinkCardValue ?? undefined,
giftAmount: reg.giftAmount ?? undefined,
});
await db
.update(registration)
.set({ paymentReminderSentAt: new Date() })
.where(eq(registration.id, reg.id));
sent++;
} catch (err) {
errors.push(`payment-reminder ${reg.email}: ${String(err)}`);
emailLog("error", "email.catch", {
type: "payment_reminder",
to: reg.email,
error: String(err),
});
}
}
emailLog("info", "reminders.cron.done", { sent, errorCount: errors.length });
return { sent, skipped: false, errors };
}

View File

@@ -15,10 +15,12 @@
"@kk/env": "workspace:*",
"better-auth": "catalog:",
"dotenv": "catalog:",
"nodemailer": "^8.0.2",
"zod": "catalog:"
},
"devDependencies": {
"@kk/config": "workspace:*",
"@types/nodemailer": "^7.0.11",
"typescript": "catalog:"
}
}

View File

@@ -5,6 +5,96 @@ import { env } from "@kk/env/server";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { tanstackStartCookies } from "better-auth/tanstack-start";
import nodemailer from "nodemailer";
const _smtpFrom = env.SMTP_FROM ?? "Kunstenkamp <info@kunstenkamp.be>";
let _transport: nodemailer.Transporter | null | undefined;
function getTransport(): nodemailer.Transporter | null {
if (_transport !== undefined) return _transport;
if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS) {
_transport = null;
return null;
}
_transport = nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_PORT === 465,
auth: { user: env.SMTP_USER, pass: env.SMTP_PASS },
});
return _transport;
}
async function sendPasswordResetEmail(to: string, resetUrl: string) {
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping password reset email");
return;
}
const html = `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Wachtwoord opnieuw instellen</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
<tr>
<td style="padding:40px 48px 32px;">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
<h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Wachtwoord opnieuw instellen</h1>
</td>
</tr>
<tr>
<td style="padding:0 48px 32px;">
<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
We hebben een aanvraag ontvangen om het wachtwoord van je Kunstenkamp-account opnieuw in te stellen.
</p>
<p style="margin:0 0 24px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Klik op de knop hieronder om een nieuw wachtwoord in te stellen. Deze link is <strong style="color:#ffffff;">1 uur geldig</strong>.
</p>
<table cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius:2px;background:#ffffff;">
<a href="${resetUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
Stel wachtwoord in
</a>
</td>
</tr>
</table>
<p style="margin:16px 0 0;font-size:13px;color:rgba(255,255,255,0.4);">
Of kopieer deze link: <span style="color:rgba(255,255,255,0.6);">${resetUrl}</span>
</p>
<p style="margin:24px 0 0;font-size:14px;color:rgba(255,255,255,0.5);line-height:1.6;">
Heb je dit niet aangevraagd? Dan hoef je niets te doen — je wachtwoord blijft ongewijzigd.
</p>
</td>
</tr>
<tr>
<td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);line-height:1.6;">
Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a><br/>
Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
await transport.sendMail({
from: _smtpFrom,
to,
subject: "Wachtwoord opnieuw instellen — Kunstenkamp",
html,
});
}
export const auth = betterAuth({
database: drizzleAdapter(db, {
@@ -35,6 +125,9 @@ export const auth = betterAuth({
return keyBuffer.equals(hashBuffer);
},
},
sendResetPassword: async ({ user, url }) => {
await sendPasswordResetEmail(user.email, url);
},
},
user: {
additionalFields: {

Binary file not shown.

Binary file not shown.

View File

@@ -1,15 +0,0 @@
-- Migrate from Mollie back to LemonSqueezy
-- Renames payment provider columns in registration and drinkkaart_topup tables,
-- and restores the lemonsqueezy_customer_id column on registration.
-- registration table:
-- mollie_payment_id -> lemonsqueezy_order_id
-- (re-add) lemonsqueezy_customer_id
ALTER TABLE registration RENAME COLUMN mollie_payment_id TO lemonsqueezy_order_id;
ALTER TABLE registration ADD COLUMN lemonsqueezy_customer_id text;
-- drinkkaart_topup table:
-- mollie_payment_id -> lemonsqueezy_order_id
ALTER TABLE drinkkaart_topup RENAME COLUMN mollie_payment_id TO lemonsqueezy_order_id;

View File

@@ -0,0 +1,9 @@
-- Add reminder table for email reminders 1 hour before registration opens
CREATE TABLE `reminder` (
`id` text PRIMARY KEY NOT NULL,
`email` text NOT NULL,
`sent_at` integer,
`created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL
);
--> statement-breakpoint
CREATE INDEX `reminder_email_idx` ON `reminder` (`email`);

View File

@@ -1,2 +0,0 @@
ALTER TABLE registration ADD COLUMN postcode TEXT;
ALTER TABLE registration ADD COLUMN birthdate TEXT;

View File

@@ -0,0 +1,101 @@
ALTER TABLE `registration` RENAME COLUMN "wants_to_perform" TO "registration_type";--> statement-breakpoint
CREATE TABLE `drinkkaart` (
`id` text PRIMARY KEY NOT NULL,
`user_id` text NOT NULL,
`balance` integer DEFAULT 0 NOT NULL,
`version` integer DEFAULT 0 NOT NULL,
`qr_secret` text NOT NULL,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `drinkkaart_user_id_unique` ON `drinkkaart` (`user_id`);--> statement-breakpoint
CREATE TABLE `drinkkaart_topup` (
`id` text PRIMARY KEY NOT NULL,
`drinkkaart_id` text NOT NULL,
`user_id` text NOT NULL,
`amount_cents` integer NOT NULL,
`balance_before` integer NOT NULL,
`balance_after` integer NOT NULL,
`type` text NOT NULL,
`mollie_payment_id` text,
`admin_id` text,
`reason` text,
`paid_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `drinkkaart_topup_mollie_payment_id_unique` ON `drinkkaart_topup` (`mollie_payment_id`);--> statement-breakpoint
CREATE TABLE `drinkkaart_transaction` (
`id` text PRIMARY KEY NOT NULL,
`drinkkaart_id` text NOT NULL,
`user_id` text NOT NULL,
`admin_id` text NOT NULL,
`amount_cents` integer NOT NULL,
`balance_before` integer NOT NULL,
`balance_after` integer NOT NULL,
`type` text NOT NULL,
`reversed_by` text,
`reverses` text,
`note` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE TABLE `reminder` (
`id` text PRIMARY KEY NOT NULL,
`email` text NOT NULL,
`sent_24h_at` integer,
`sent_at` integer,
`created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL
);
--> statement-breakpoint
CREATE INDEX `reminder_email_idx` ON `reminder` (`email`);--> statement-breakpoint
DROP INDEX "admin_request_user_id_unique";--> statement-breakpoint
DROP INDEX "admin_request_userId_idx";--> statement-breakpoint
DROP INDEX "admin_request_status_idx";--> statement-breakpoint
DROP INDEX "account_userId_idx";--> statement-breakpoint
DROP INDEX "session_token_unique";--> statement-breakpoint
DROP INDEX "session_userId_idx";--> statement-breakpoint
DROP INDEX "user_email_unique";--> statement-breakpoint
DROP INDEX "verification_identifier_idx";--> statement-breakpoint
DROP INDEX "drinkkaart_user_id_unique";--> statement-breakpoint
DROP INDEX "drinkkaart_topup_mollie_payment_id_unique";--> statement-breakpoint
DROP INDEX "registration_management_token_unique";--> statement-breakpoint
DROP INDEX "registration_email_idx";--> statement-breakpoint
DROP INDEX "registration_registrationType_idx";--> statement-breakpoint
DROP INDEX "registration_artForm_idx";--> statement-breakpoint
DROP INDEX "registration_createdAt_idx";--> statement-breakpoint
DROP INDEX "registration_managementToken_idx";--> statement-breakpoint
DROP INDEX "registration_paymentStatus_idx";--> statement-breakpoint
DROP INDEX "registration_giftAmount_idx";--> statement-breakpoint
DROP INDEX "registration_molliePaymentId_idx";--> statement-breakpoint
DROP INDEX "reminder_email_idx";--> statement-breakpoint
ALTER TABLE `registration` ALTER COLUMN "registration_type" TO "registration_type" text NOT NULL DEFAULT 'watcher';--> statement-breakpoint
CREATE UNIQUE INDEX `admin_request_user_id_unique` ON `admin_request` (`user_id`);--> statement-breakpoint
CREATE INDEX `admin_request_userId_idx` ON `admin_request` (`user_id`);--> statement-breakpoint
CREATE INDEX `admin_request_status_idx` ON `admin_request` (`status`);--> statement-breakpoint
CREATE INDEX `account_userId_idx` ON `account` (`user_id`);--> statement-breakpoint
CREATE UNIQUE INDEX `session_token_unique` ON `session` (`token`);--> statement-breakpoint
CREATE INDEX `session_userId_idx` ON `session` (`user_id`);--> statement-breakpoint
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);--> statement-breakpoint
CREATE INDEX `verification_identifier_idx` ON `verification` (`identifier`);--> statement-breakpoint
CREATE UNIQUE INDEX `registration_management_token_unique` ON `registration` (`management_token`);--> statement-breakpoint
CREATE INDEX `registration_email_idx` ON `registration` (`email`);--> statement-breakpoint
CREATE INDEX `registration_registrationType_idx` ON `registration` (`registration_type`);--> statement-breakpoint
CREATE INDEX `registration_artForm_idx` ON `registration` (`art_form`);--> statement-breakpoint
CREATE INDEX `registration_createdAt_idx` ON `registration` (`created_at`);--> statement-breakpoint
CREATE INDEX `registration_managementToken_idx` ON `registration` (`management_token`);--> statement-breakpoint
CREATE INDEX `registration_paymentStatus_idx` ON `registration` (`payment_status`);--> statement-breakpoint
CREATE INDEX `registration_giftAmount_idx` ON `registration` (`gift_amount`);--> statement-breakpoint
CREATE INDEX `registration_molliePaymentId_idx` ON `registration` (`mollie_payment_id`);--> statement-breakpoint
ALTER TABLE `registration` ADD `is_over_16` integer DEFAULT false NOT NULL;--> statement-breakpoint
ALTER TABLE `registration` ADD `drink_card_value` integer DEFAULT 0;--> statement-breakpoint
ALTER TABLE `registration` ADD `guests` text;--> statement-breakpoint
ALTER TABLE `registration` ADD `birthdate` text DEFAULT '' NOT NULL;--> statement-breakpoint
ALTER TABLE `registration` ADD `postcode` text DEFAULT '' NOT NULL;--> statement-breakpoint
ALTER TABLE `registration` ADD `payment_status` text DEFAULT 'pending' NOT NULL;--> statement-breakpoint
ALTER TABLE `registration` ADD `payment_amount` integer DEFAULT 0;--> statement-breakpoint
ALTER TABLE `registration` ADD `gift_amount` integer DEFAULT 0;--> statement-breakpoint
ALTER TABLE `registration` ADD `mollie_payment_id` text;--> statement-breakpoint
ALTER TABLE `registration` ADD `paid_at` integer;--> statement-breakpoint
ALTER TABLE `registration` ADD `drinkkaart_credited_at` integer;--> statement-breakpoint
ALTER TABLE `registration` ADD `payment_reminder_sent_at` integer;

View File

@@ -0,0 +1,2 @@
-- Migration: add payment_reminder_sent_at column to registration table
ALTER TABLE registration ADD COLUMN payment_reminder_sent_at INTEGER;

View File

@@ -0,0 +1,2 @@
-- Add sent_24h_at column to track whether the 24-hour-before reminder was sent
ALTER TABLE `reminder` ADD `sent_24h_at` integer;

View File

@@ -0,0 +1,971 @@
{
"version": "6",
"dialect": "sqlite",
"id": "7994e607-3835-43a5-9251-fca48f0aa19a",
"prevId": "d9a4f07e-e6ae-45d0-be82-c919ae7fbe09",
"tables": {
"admin_request": {
"name": "admin_request",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"requested_at": {
"name": "requested_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
},
"reviewed_at": {
"name": "reviewed_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reviewed_by": {
"name": "reviewed_by",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"admin_request_user_id_unique": {
"name": "admin_request_user_id_unique",
"columns": ["user_id"],
"isUnique": true
},
"admin_request_userId_idx": {
"name": "admin_request_userId_idx",
"columns": ["user_id"],
"isUnique": false
},
"admin_request_status_idx": {
"name": "admin_request_status_idx",
"columns": ["status"],
"isUnique": false
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"account": {
"name": "account",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"account_userId_idx": {
"name": "account_userId_idx",
"columns": ["user_id"],
"isUnique": false
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"session": {
"name": "session",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"session_token_unique": {
"name": "session_token_unique",
"columns": ["token"],
"isUnique": true
},
"session_userId_idx": {
"name": "session_userId_idx",
"columns": ["user_id"],
"isUnique": false
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user": {
"name": "user",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email_verified": {
"name": "email_verified",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'user'"
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
}
},
"indexes": {
"user_email_unique": {
"name": "user_email_unique",
"columns": ["email"],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"verification": {
"name": "verification",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": ["identifier"],
"isUnique": false
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"drinkkaart": {
"name": "drinkkaart",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"balance": {
"name": "balance",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"version": {
"name": "version",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"qr_secret": {
"name": "qr_secret",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"drinkkaart_user_id_unique": {
"name": "drinkkaart_user_id_unique",
"columns": ["user_id"],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"drinkkaart_topup": {
"name": "drinkkaart_topup",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"drinkkaart_id": {
"name": "drinkkaart_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"amount_cents": {
"name": "amount_cents",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"balance_before": {
"name": "balance_before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"balance_after": {
"name": "balance_after",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"mollie_payment_id": {
"name": "mollie_payment_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"admin_id": {
"name": "admin_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reason": {
"name": "reason",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"paid_at": {
"name": "paid_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"drinkkaart_topup_mollie_payment_id_unique": {
"name": "drinkkaart_topup_mollie_payment_id_unique",
"columns": ["mollie_payment_id"],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"drinkkaart_transaction": {
"name": "drinkkaart_transaction",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"drinkkaart_id": {
"name": "drinkkaart_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"admin_id": {
"name": "admin_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"amount_cents": {
"name": "amount_cents",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"balance_before": {
"name": "balance_before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"balance_after": {
"name": "balance_after",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"reversed_by": {
"name": "reversed_by",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reverses": {
"name": "reverses",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"note": {
"name": "note",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"registration": {
"name": "registration",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"first_name": {
"name": "first_name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"last_name": {
"name": "last_name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"phone": {
"name": "phone",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"registration_type": {
"name": "registration_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'watcher'"
},
"art_form": {
"name": "art_form",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"experience": {
"name": "experience",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"is_over_16": {
"name": "is_over_16",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"drink_card_value": {
"name": "drink_card_value",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"guests": {
"name": "guests",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"birthdate": {
"name": "birthdate",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "''"
},
"postcode": {
"name": "postcode",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "''"
},
"extra_questions": {
"name": "extra_questions",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"management_token": {
"name": "management_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancelled_at": {
"name": "cancelled_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"payment_status": {
"name": "payment_status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"payment_amount": {
"name": "payment_amount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"gift_amount": {
"name": "gift_amount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"mollie_payment_id": {
"name": "mollie_payment_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"paid_at": {
"name": "paid_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"drinkkaart_credited_at": {
"name": "drinkkaart_credited_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"payment_reminder_sent_at": {
"name": "payment_reminder_sent_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
}
},
"indexes": {
"registration_management_token_unique": {
"name": "registration_management_token_unique",
"columns": ["management_token"],
"isUnique": true
},
"registration_email_idx": {
"name": "registration_email_idx",
"columns": ["email"],
"isUnique": false
},
"registration_registrationType_idx": {
"name": "registration_registrationType_idx",
"columns": ["registration_type"],
"isUnique": false
},
"registration_artForm_idx": {
"name": "registration_artForm_idx",
"columns": ["art_form"],
"isUnique": false
},
"registration_createdAt_idx": {
"name": "registration_createdAt_idx",
"columns": ["created_at"],
"isUnique": false
},
"registration_managementToken_idx": {
"name": "registration_managementToken_idx",
"columns": ["management_token"],
"isUnique": false
},
"registration_paymentStatus_idx": {
"name": "registration_paymentStatus_idx",
"columns": ["payment_status"],
"isUnique": false
},
"registration_giftAmount_idx": {
"name": "registration_giftAmount_idx",
"columns": ["gift_amount"],
"isUnique": false
},
"registration_molliePaymentId_idx": {
"name": "registration_molliePaymentId_idx",
"columns": ["mollie_payment_id"],
"isUnique": false
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"reminder": {
"name": "reminder",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sent_24h_at": {
"name": "sent_24h_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"sent_at": {
"name": "sent_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(cast(unixepoch('subsecond') * 1000 as integer))"
}
},
"indexes": {
"reminder_email_idx": {
"name": "reminder_email_idx",
"columns": ["email"],
"isUnique": false
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {
"\"registration\".\"wants_to_perform\"": "\"registration\".\"registration_type\""
}
},
"internal": {
"indexes": {}
}
}

View File

@@ -30,11 +30,39 @@
"tag": "0003_add_guests",
"breakpoints": true
},
{
"idx": 4,
"version": "6",
"when": 1772536320000,
"tag": "0004_drinkkaart",
"breakpoints": true
},
{
"idx": 5,
"version": "6",
"when": 1772596240000,
"tag": "0005_registration_drinkkaart_credit",
"breakpoints": true
},
{
"idx": 6,
"version": "6",
"when": 1772672880000,
"tag": "0006_mollie_migration",
"breakpoints": true
},
{
"idx": 7,
"version": "6",
"when": 1772931300000,
"tag": "0007_reminder",
"breakpoints": true
},
{
"idx": 8,
"version": "6",
"when": 1741388400000,
"tag": "0008_add_postcode_birthdate",
"when": 1773910007494,
"tag": "0008_melodic_marrow",
"breakpoints": true
}
]

View File

@@ -46,7 +46,7 @@ export const drinkkaartTopup = sqliteTable("drinkkaart_topup", {
balanceBefore: integer("balance_before").notNull(),
balanceAfter: integer("balance_after").notNull(),
type: text("type", { enum: ["payment", "admin_credit"] }).notNull(),
lemonsqueezyOrderId: text("lemonsqueezy_order_id").unique(), // nullable; only for type="payment"
molliePaymentId: text("mollie_payment_id").unique(), // nullable; only for type="payment"
adminId: text("admin_id"), // nullable; only for type="admin_credit"
reason: text("reason"),
paidAt: integer("paid_at", { mode: "timestamp_ms" }).notNull(),

View File

@@ -2,3 +2,4 @@ export * from "./admin-requests";
export * from "./auth";
export * from "./drinkkaart";
export * from "./registrations";
export * from "./reminders";

View File

@@ -19,12 +19,11 @@ export const registration = sqliteTable(
.default(false),
// Watcher-specific fields
drinkCardValue: integer("drink_card_value").default(0),
// Guests: JSON array of {firstName, lastName, email?, phone?} objects
// Guests: JSON array of {firstName, lastName, email?, phone?, birthdate, postcode} objects
guests: text("guests"),
// Contact / demographic
postcode: text("postcode"),
birthdate: text("birthdate"),
// Shared
birthdate: text("birthdate").notNull().default(""),
postcode: text("postcode").notNull().default(""),
extraQuestions: text("extra_questions"),
managementToken: text("management_token").unique(),
cancelledAt: integer("cancelled_at", { mode: "timestamp_ms" }),
@@ -32,8 +31,7 @@ export const registration = sqliteTable(
paymentStatus: text("payment_status").notNull().default("pending"),
paymentAmount: integer("payment_amount").default(0),
giftAmount: integer("gift_amount").default(0),
lemonsqueezyOrderId: text("lemonsqueezy_order_id"),
lemonsqueezyCustomerId: text("lemonsqueezy_customer_id"),
molliePaymentId: text("mollie_payment_id"),
paidAt: integer("paid_at", { mode: "timestamp_ms" }),
// Set when the drinkCardValue has been credited to the user's drinkkaart.
// Null means not yet credited (either unpaid, account doesn't exist yet, or
@@ -41,6 +39,9 @@ export const registration = sqliteTable(
drinkkaartCreditedAt: integer("drinkkaart_credited_at", {
mode: "timestamp_ms",
}),
paymentReminderSentAt: integer("payment_reminder_sent_at", {
mode: "timestamp_ms",
}),
createdAt: integer("created_at", { mode: "timestamp_ms" })
.default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
.notNull(),
@@ -53,6 +54,6 @@ export const registration = sqliteTable(
index("registration_managementToken_idx").on(table.managementToken),
index("registration_paymentStatus_idx").on(table.paymentStatus),
index("registration_giftAmount_idx").on(table.giftAmount),
index("registration_lemonsqueezyOrderId_idx").on(table.lemonsqueezyOrderId),
index("registration_molliePaymentId_idx").on(table.molliePaymentId),
],
);

View File

@@ -0,0 +1,21 @@
import { sql } from "drizzle-orm";
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const reminder = sqliteTable(
"reminder",
{
id: text("id").primaryKey(), // UUID
email: text("email").notNull(),
/** Set when the 24-hours-before reminder has been sent. */
sent24hAt: integer("sent_24h_at", { mode: "timestamp_ms" }),
/** Set when the 1-hour-before reminder has been sent. */
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
createdAt: integer("created_at", { mode: "timestamp_ms" })
.default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
.notNull(),
},
(t) => [index("reminder_email_idx").on(t.email)],
);
export type Reminder = typeof reminder.$inferSelect;
export type NewReminder = typeof reminder.$inferInsert;

View File

@@ -15,20 +15,18 @@ export const env = createEnv({
server: {
DATABASE_URL: z.string().min(1),
BETTER_AUTH_SECRET: z.string().min(32),
BETTER_AUTH_URL: z.url(),
BETTER_AUTH_URL: z.url().default("https://kunstenkamp.be"),
CORS_ORIGIN: z.url(),
SMTP_HOST: z.string().min(1).optional(),
SMTP_PORT: z.coerce.number().default(587),
SMTP_USER: z.string().min(1).optional(),
SMTP_PASS: z.string().min(1).optional(),
SMTP_FROM: z.string().min(1).optional(),
SMTP_FROM: z.string().min(1).default("Kunstenkamp <info@kunstenkamp.be>"),
NODE_ENV: z
.enum(["development", "production", "test"])
.default("development"),
LEMON_SQUEEZY_API_KEY: z.string().min(1).optional(),
LEMON_SQUEEZY_STORE_ID: z.string().min(1).optional(),
LEMON_SQUEEZY_VARIANT_ID: z.string().min(1).optional(),
LEMON_SQUEEZY_WEBHOOK_SECRET: z.string().min(1).optional(),
MOLLIE_API_KEY: z.string().min(1).optional(),
CRON_SECRET: z.string().min(1).optional(),
},
runtimeEnv: process.env,
emptyStringAsUndefined: true,

View File

@@ -1,5 +1,5 @@
import alchemy from "alchemy";
import { TanStackStart } from "alchemy/cloudflare";
import { Queue, TanStackStart } from "alchemy/cloudflare";
import { config } from "dotenv";
config({ path: "./.env" });
@@ -16,6 +16,10 @@ function getEnvVar(name: string): string {
return value;
}
const emailQueue = await Queue("email-queue", {
name: "kk-email-queue",
});
export const web = await TanStackStart("web", {
cwd: "../../apps/web",
bindings: {
@@ -30,12 +34,27 @@ export const web = await TanStackStart("web", {
SMTP_USER: getEnvVar("SMTP_USER"),
SMTP_PASS: getEnvVar("SMTP_PASS"),
SMTP_FROM: getEnvVar("SMTP_FROM"),
// Payments (LemonSqueezy)
LEMON_SQUEEZY_API_KEY: getEnvVar("LEMON_SQUEEZY_API_KEY"),
LEMON_SQUEEZY_STORE_ID: getEnvVar("LEMON_SQUEEZY_STORE_ID"),
LEMON_SQUEEZY_VARIANT_ID: getEnvVar("LEMON_SQUEEZY_VARIANT_ID"),
LEMON_SQUEEZY_WEBHOOK_SECRET: getEnvVar("LEMON_SQUEEZY_WEBHOOK_SECRET"),
// Payments (Mollie)
MOLLIE_API_KEY: getEnvVar("MOLLIE_API_KEY"),
// Cron secret for protected scheduled endpoints
CRON_SECRET: getEnvVar("CRON_SECRET"),
// Queue binding for async email sends
EMAIL_QUEUE: emailQueue,
},
// Queue consumer: the worker's queue() handler processes EmailMessage batches
eventSources: [
{
queue: emailQueue,
settings: {
batchSize: 10,
maxRetries: 3,
retryDelay: 60, // seconds before retrying a failed message
maxWaitTimeMs: 1000,
},
},
],
// Fire every hour so reminder checks can run at 19:00 on 2026-03-15 (24h) and 18:00 on 2026-03-16 (1h)
crons: ["0 * * * *"],
domains: ["kunstenkamp.be", "www.kunstenkamp.be"],
});

View File

@@ -18,14 +18,17 @@
"persistent": true
},
"db:push": {
"cache": false
"cache": false,
"interactive": true
},
"db:generate": {
"cache": false
"cache": false,
"interactive": true
},
"db:migrate": {
"cache": false,
"persistent": true
"persistent": true,
"interactive": true
},
"db:studio": {
"cache": false,