feat:drinkkaart

This commit is contained in:
2026-03-03 23:52:49 +01:00
parent b8cefd373d
commit 79869a9a21
35 changed files with 3189 additions and 76 deletions

View File

@@ -33,9 +33,11 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dotenv": "catalog:",
"html5-qrcode": "^2.3.8",
"libsql": "catalog:",
"lucide-react": "^0.525.0",
"next-themes": "^0.4.6",
"qrcode": "^1.5.4",
"react": "19.2.3",
"react-dom": "19.2.3",
"shadcn": "^3.6.2",
@@ -54,6 +56,7 @@
"@tanstack/react-router-devtools": "^1.141.1",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0",
"@types/qrcode": "^1.5.6",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",
"@types/three": "^0.183.1",

View File

@@ -0,0 +1,63 @@
import { Link, useNavigate } from "@tanstack/react-router";
import { LogOut } from "lucide-react";
import { authClient } from "@/lib/auth-client";
interface HeaderProps {
userName?: string;
isAdmin?: boolean;
}
export function Header({ userName, isAdmin }: HeaderProps) {
const navigate = useNavigate();
const handleSignOut = async () => {
await authClient.signOut();
navigate({ to: "/" });
};
if (!userName) return null;
return (
<header className="border-white/10 border-b bg-[#214e51]/95 backdrop-blur-sm">
<div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">
<nav className="flex items-center gap-6">
<Link
to="/"
className="font-['Intro',sans-serif] text-lg text-white/80 transition-opacity hover:opacity-100"
>
Kunstenkamp
</Link>
<Link
to="/drinkkaart"
search={{ topup: undefined }}
className="text-sm text-white/70 transition-colors hover:text-white"
activeProps={{ className: "text-white font-medium" }}
>
Drinkkaart
</Link>
{isAdmin && (
<Link
to="/admin"
className="text-sm text-white/70 transition-colors hover:text-white"
activeProps={{ className: "text-white font-medium" }}
>
Admin
</Link>
)}
</nav>
<div className="flex items-center gap-3">
<span className="text-sm text-white/60">{userName}</span>
<button
type="button"
onClick={handleSignOut}
className="flex items-center gap-1.5 rounded px-2 py-1 text-sm text-white/50 transition-colors hover:bg-white/10 hover:text-white"
>
<LogOut className="h-3.5 w-3.5" />
Uitloggen
</button>
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,18 @@
"use client";
import { authClient } from "@/lib/auth-client";
import { Header } from "./Header";
/**
* Client-side header wrapper.
* Reads the current session and renders <Header> only when the user is logged in.
* Rendered in __root.tsx so it appears on every page.
*/
export function SiteHeader() {
const { data: session } = authClient.useSession();
if (!session?.user) return null;
const user = session.user as { name: string; role?: string };
return <Header userName={user.name} isAdmin={user.role === "admin"} />;
}

View File

@@ -0,0 +1,197 @@
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
import { ReverseDialog } from "./ReverseDialog";
interface TransactionRow {
id: string;
type: "deduction" | "reversal";
userId: string;
userName: string;
userEmail: string;
adminId: string;
adminName: string;
amountCents: number;
balanceBefore: number;
balanceAfter: number;
note: string | null;
reversedBy: string | null;
reverses: string | null;
createdAt: Date;
}
export function AdminTransactionLog() {
const [page, setPage] = useState(1);
const [reverseTarget, setReverseTarget] = useState<TransactionRow | null>(
null,
);
const { data, isLoading, refetch } = useQuery({
...orpc.drinkkaart.getTransactionLog.queryOptions({
input: { page, pageSize: 50 },
}),
refetchInterval: 30_000,
});
const transactions = (data?.transactions ?? []) as TransactionRow[];
const total = data?.total ?? 0;
const totalPages = Math.ceil(total / 50);
if (isLoading) {
return <p className="text-sm text-white/40">Laden...</p>;
}
if (transactions.length === 0) {
return <p className="text-sm text-white/40">Geen transacties gevonden.</p>;
}
return (
<div>
<div className="mb-3 flex items-center justify-between">
<p className="text-sm text-white/50">{total} transacties</p>
<Button
onClick={() => refetch()}
size="sm"
variant="outline"
className="border-white/20 bg-transparent text-sm text-white hover:bg-white/10"
>
Vernieuwen
</Button>
</div>
<div className="overflow-x-auto rounded-xl border border-white/10">
<table className="w-full text-sm">
<thead>
<tr className="border-white/10 border-b bg-white/5">
<th className="px-4 py-3 text-left font-medium text-white/50">
Tijdstip
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Gebruiker
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Bedrag
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Type
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Admin
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Opmerking
</th>
<th className="px-4 py-3 text-left font-medium text-white/50">
Actie
</th>
</tr>
</thead>
<tbody>
{transactions.map((t) => {
const date = new Date(t.createdAt).toLocaleString("nl-BE", {
day: "2-digit",
month: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
const isReversal = t.type === "reversal";
const canReverse = t.type === "deduction" && !t.reversedBy;
return (
<tr
key={t.id}
className={`border-white/5 border-b ${isReversal ? "bg-green-400/5" : ""}`}
>
<td className="px-4 py-3 text-white/60 tabular-nums">
{date}
</td>
<td className="px-4 py-3">
<p className="font-medium text-white">{t.userName}</p>
<p className="text-white/40 text-xs">{t.userEmail}</p>
</td>
<td className="px-4 py-3">
<span
className={`font-medium ${isReversal ? "text-green-400" : "text-red-400"}`}
>
{isReversal ? "+ " : " "}
{formatCents(t.amountCents)}
</span>
</td>
<td className="px-4 py-3">
{isReversal ? (
<span className="rounded-full border border-green-400/30 bg-green-400/10 px-2 py-0.5 text-green-300 text-xs">
Teruggedraaid
</span>
) : t.reversedBy ? (
<span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-white/40 text-xs">
Teruggedraaid
</span>
) : (
<span className="rounded-full border border-red-400/20 bg-red-400/10 px-2 py-0.5 text-red-300 text-xs">
Afschrijving
</span>
)}
</td>
<td className="px-4 py-3 text-sm text-white/60">
{t.adminName}
</td>
<td className="px-4 py-3 text-sm text-white/50">
{t.note || "—"}
</td>
<td className="px-4 py-3">
{canReverse && (
<Button
size="sm"
variant="outline"
onClick={() => setReverseTarget(t)}
className="border-orange-400/30 bg-transparent text-orange-300 hover:bg-orange-400/10"
>
Draai terug
</Button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="mt-4 flex items-center justify-center gap-3">
<Button
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
variant="outline"
size="sm"
className="border-white/20 bg-transparent text-white hover:bg-white/10 disabled:opacity-50"
>
Vorige
</Button>
<span className="text-sm text-white/60">
{page} / {totalPages}
</span>
<Button
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={page === totalPages}
variant="outline"
size="sm"
className="border-white/20 bg-transparent text-white hover:bg-white/10 disabled:opacity-50"
>
Volgende
</Button>
</div>
)}
{reverseTarget && (
<ReverseDialog
transaction={reverseTarget}
onClose={() => setReverseTarget(null)}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,191 @@
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DEDUCTION_PRESETS_CENTS, formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
interface DeductionPanelProps {
drinkkaartId: string;
userName: string;
userEmail: string;
balance: number;
onSuccess: (transactionId: string, balanceAfter: number) => void;
onCancel: () => void;
}
export function DeductionPanel({
drinkkaartId,
userName,
balance,
onSuccess,
onCancel,
}: DeductionPanelProps) {
const [selectedCents, setSelectedCents] = useState<number>(200);
const [customCents, setCustomCents] = useState("");
const [useCustom, setUseCustom] = useState(false);
const [note, setNote] = useState("");
const [confirming, setConfirming] = useState(false);
const amountCents = useCustom
? Math.round((Number.parseFloat(customCents || "0") || 0) * 100)
: selectedCents;
const isValid =
Number.isInteger(amountCents) && amountCents >= 1 && amountCents <= balance;
const deductMutation = useMutation(
orpc.drinkkaart.deductBalance.mutationOptions(),
);
const handleConfirm = () => {
if (!isValid) return;
deductMutation.mutate(
{ drinkkaartId, amountCents, note: note || undefined },
{
onSuccess: (data) => {
onSuccess(data.transactionId, data.balanceAfter);
},
},
);
};
if (confirming) {
return (
<div className="rounded-xl border border-red-400/20 bg-red-400/5 p-5">
<p className="mb-2 text-white">
Bevestig afschrijving van{" "}
<strong className="text-red-300">{formatCents(amountCents)}</strong>{" "}
voor <strong>{userName}</strong>
</p>
<p className="mb-4 text-sm text-white/50">
Nieuw saldo: {formatCents(balance - amountCents)}
</p>
{deductMutation.isError && (
<p className="mb-3 text-red-400 text-sm">
{(deductMutation.error as Error)?.message ??
"Fout bij afschrijving"}
</p>
)}
<div className="flex gap-3">
<Button
onClick={handleConfirm}
disabled={deductMutation.isPending}
className="flex-1 bg-red-500 text-white hover:bg-red-600"
>
{deductMutation.isPending ? "Verwerken..." : "Bevestigen"}
</Button>
<Button
onClick={() => {
setConfirming(false);
deductMutation.reset();
}}
variant="outline"
disabled={deductMutation.isPending}
className="border-white/20 bg-transparent text-white hover:bg-white/10"
>
Terug
</Button>
</div>
</div>
);
}
return (
<div className="space-y-4">
{/* Preset amounts */}
<div>
<p className="mb-2 text-sm text-white/60">Bedrag</p>
<div className="grid grid-cols-4 gap-2">
{DEDUCTION_PRESETS_CENTS.map((cents) => (
<button
key={cents}
type="button"
onClick={() => {
setSelectedCents(cents);
setUseCustom(false);
}}
className={`rounded-lg border py-3 font-medium text-sm transition-colors ${
!useCustom && selectedCents === cents
? "border-white bg-white text-[#214e51]"
: "border-white/20 text-white hover:border-white/50"
}`}
>
{formatCents(cents)}
</button>
))}
</div>
</div>
{/* Custom amount */}
<div>
<label
htmlFor="deduct-custom"
className="mb-1 block text-sm text-white/60"
>
Eigen bedrag ()
</label>
<div className="relative">
<span className="absolute top-1/2 left-3 -translate-y-1/2 text-white/50">
</span>
<Input
id="deduct-custom"
type="number"
min="0.01"
step="0.01"
placeholder="Bijv. 2.50"
value={customCents}
onChange={(e) => {
setCustomCents(e.target.value);
setUseCustom(true);
}}
className="border-white/20 bg-white/10 pl-8 text-white placeholder:text-white/30"
/>
</div>
</div>
{/* Note */}
<div>
<label
htmlFor="deduct-note"
className="mb-1 block text-sm text-white/60"
>
Opmerking (optioneel)
</label>
<Input
id="deduct-note"
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="Bijv. 'Wijn'"
maxLength={200}
className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
/>
</div>
{/* Insufficient balance warning */}
{amountCents > balance && (
<p className="text-red-400 text-sm">
Onvoldoende saldo. Huidig saldo: {formatCents(balance)}
</p>
)}
<div className="flex gap-3">
<Button
onClick={() => setConfirming(true)}
disabled={!isValid}
className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90 disabled:opacity-50"
>
Afschrijven {isValid ? formatCents(amountCents) : "—"}
</Button>
<Button
onClick={onCancel}
variant="outline"
className="border-white/20 bg-transparent text-white hover:bg-white/10"
>
Annuleren
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,204 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
interface ManualCreditFormProps {
onDone: () => void;
}
export function ManualCreditForm({ onDone }: ManualCreditFormProps) {
const [query, setQuery] = useState("");
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
const [selectedUserName, setSelectedUserName] = useState("");
const [amountEuros, setAmountEuros] = useState("");
const [reason, setReason] = useState("");
const searchQuery = useQuery({
...orpc.drinkkaart.searchUsers.queryOptions({ input: { query } }),
enabled: query.length >= 2,
});
const getDrinkkaartQuery = useQuery({
...orpc.drinkkaart.getDrinkkaartByUserId.queryOptions({
input: { userId: selectedUserId ?? "" },
}),
enabled: !!selectedUserId,
});
const creditMutation = useMutation(
orpc.drinkkaart.adminCreditBalance.mutationOptions(),
);
const amountCents = Math.round(
(Number.parseFloat(amountEuros || "0") || 0) * 100,
);
const isValid =
selectedUserId &&
getDrinkkaartQuery.data &&
amountCents >= 1 &&
reason.trim().length >= 1;
const handleSubmit = () => {
if (!isValid || !getDrinkkaartQuery.data) return;
creditMutation.mutate(
{
drinkkaartId: getDrinkkaartQuery.data.drinkkaartId,
amountCents,
reason: reason.trim(),
},
{
onSuccess: () => {
toast.success(
`${formatCents(amountCents)} opgeladen voor ${selectedUserName}`,
);
onDone();
},
onError: (err: Error) => {
toast.error(err.message ?? "Fout bij opladen");
},
},
);
};
return (
<div className="space-y-4">
<h3 className="font-['Intro',sans-serif] text-lg text-white">
Handmatig opladen
</h3>
{/* User search */}
<div>
<label
htmlFor="user-search"
className="mb-1 block text-sm text-white/60"
>
Gebruiker zoeken (naam of email)
</label>
<Input
id="user-search"
value={selectedUserId ? selectedUserName : query}
onChange={(e) => {
setQuery(e.target.value);
setSelectedUserId(null);
}}
placeholder="Naam of email..."
className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
/>
{!selectedUserId && query.length >= 2 && searchQuery.data && (
<ul className="mt-1 rounded-lg border border-white/10 bg-[#1a3d40]">
{searchQuery.data.length === 0 ? (
<li className="px-4 py-2 text-sm text-white/40">
Geen gebruikers gevonden
</li>
) : (
searchQuery.data.map((u) => (
<li key={u.id}>
<button
type="button"
className="w-full px-4 py-2 text-left text-sm text-white hover:bg-white/10"
onClick={() => {
setSelectedUserId(u.id);
setSelectedUserName(u.name);
setQuery("");
}}
>
<span className="font-medium">{u.name}</span>
<span className="ml-2 text-white/50">{u.email}</span>
</button>
</li>
))
)}
</ul>
)}
{selectedUserId && getDrinkkaartQuery.data && (
<p className="mt-1 text-sm text-white/50">
Huidig saldo: {formatCents(getDrinkkaartQuery.data.balance)}
{" · "}
<button
type="button"
className="text-white/60 underline"
onClick={() => {
setSelectedUserId(null);
setSelectedUserName("");
}}
>
Wijzigen
</button>
</p>
)}
</div>
{/* Amount */}
<div>
<label
htmlFor="credit-amount"
className="mb-1 block text-sm text-white/60"
>
Bedrag ()
</label>
<div className="relative">
<span className="absolute top-1/2 left-3 -translate-y-1/2 text-white/50">
</span>
<Input
id="credit-amount"
type="number"
min="0.01"
step="0.01"
placeholder="Bijv. 10"
value={amountEuros}
onChange={(e) => setAmountEuros(e.target.value)}
className="border-white/20 bg-white/10 pl-8 text-white placeholder:text-white/30"
/>
</div>
</div>
{/* Reason */}
<div>
<label
htmlFor="credit-reason"
className="mb-1 block text-sm text-white/60"
>
Reden (verplicht)
</label>
<Input
id="credit-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="Bijv. 'Cash betaling', 'Gift', 'Terugbetaling'"
maxLength={200}
className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
/>
</div>
{creditMutation.isError && (
<p className="text-red-400 text-sm">
{(creditMutation.error as Error)?.message ?? "Fout bij opladen"}
</p>
)}
<div className="flex gap-3">
<Button
onClick={handleSubmit}
disabled={!isValid || creditMutation.isPending}
className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90 disabled:opacity-50"
>
{creditMutation.isPending
? "Verwerken..."
: `Opladen — ${amountCents >= 1 ? formatCents(amountCents) : "—"}`}
</Button>
<Button
onClick={onDone}
variant="outline"
className="border-white/20 bg-transparent text-white hover:bg-white/10"
>
Annuleren
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,127 @@
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { orpc } from "@/utils/orpc";
interface QrCodeCanvasProps {
token: string;
}
function QrCodeCanvas({ token }: QrCodeCanvasProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (!canvasRef.current || !token) return;
// Dynamic import to avoid SSR issues
import("qrcode").then((QRCode) => {
if (canvasRef.current) {
QRCode.toCanvas(canvasRef.current, token, {
width: 280,
margin: 2,
color: { dark: "#214e51", light: "#ffffff" },
});
}
});
}, [token]);
return <canvas ref={canvasRef} className="rounded-xl" />;
}
function useCountdown(expiresAt: Date | undefined) {
const [secondsLeft, setSecondsLeft] = useState<number>(0);
useEffect(() => {
if (!expiresAt) return;
const tick = () => {
const diff = Math.max(
0,
Math.floor((expiresAt.getTime() - Date.now()) / 1000),
);
setSecondsLeft(diff);
};
tick();
const interval = setInterval(tick, 1000);
return () => clearInterval(interval);
}, [expiresAt]);
return secondsLeft;
}
export function QrCodeDisplay() {
const { data, refetch, isLoading, isError } = useQuery(
orpc.drinkkaart.getMyQrToken.queryOptions(),
);
const expiresAt = data?.expiresAt ? new Date(data.expiresAt) : undefined;
const secondsLeft = useCountdown(expiresAt);
// Auto-refresh 60s before expiry
useEffect(() => {
if (!expiresAt) return;
const refreshAt = expiresAt.getTime() - 60_000;
const delay = refreshAt - Date.now();
if (delay <= 0) {
refetch();
return;
}
const timer = setTimeout(() => refetch(), delay);
return () => clearTimeout(timer);
}, [expiresAt, refetch]);
// Refresh on tab focus if token is about to expire
useEffect(() => {
const onVisibility = () => {
if (document.visibilityState === "visible" && expiresAt) {
if (Date.now() >= expiresAt.getTime() - 10_000) refetch();
}
};
document.addEventListener("visibilitychange", onVisibility);
return () => document.removeEventListener("visibilitychange", onVisibility);
}, [expiresAt, refetch]);
const minutes = Math.floor(secondsLeft / 60);
const seconds = secondsLeft % 60;
const countdownLabel = `${minutes}:${String(seconds).padStart(2, "0")}`;
if (isLoading) {
return (
<div className="flex h-[280px] w-[280px] items-center justify-center rounded-xl bg-white/10">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white" />
</div>
);
}
if (isError || !data?.token) {
return (
<div className="flex h-[280px] w-[280px] flex-col items-center justify-center gap-2 rounded-xl bg-white/10">
<p className="text-sm text-white/60">Kon QR-code niet laden</p>
<button
type="button"
onClick={() => refetch()}
className="text-sm text-white underline"
>
Opnieuw proberen
</button>
</div>
);
}
return (
<div className="flex flex-col items-center gap-3">
<div className="rounded-xl bg-white p-3 shadow-lg">
<QrCodeCanvas token={data.token} />
</div>
<p className="text-sm text-white/60">
{secondsLeft > 0 ? (
<>
Vervalt over{" "}
<span className="text-white/80 tabular-nums">{countdownLabel}</span>
</>
) : (
<span className="text-yellow-400">Verlopen vernieuwen...</span>
)}
</p>
</div>
);
}

View File

@@ -0,0 +1,116 @@
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
interface QrScannerProps {
onScan: (token: string) => void;
onCancel: () => void;
}
export function QrScanner({ onScan, onCancel }: QrScannerProps) {
const scannerDivId = "qr-reader-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
const onScanRef = useRef(onScan);
useEffect(() => {
onScanRef.current = onScan;
}, [onScan]);
useEffect(() => {
let stopped = false;
import("html5-qrcode")
.then(({ Html5QrcodeScanner }) => {
if (stopped) return;
const scanner = new Html5QrcodeScanner(
scannerDivId,
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
false,
);
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);
}
},
);
})
.catch((err) => {
console.error("Failed to load html5-qrcode:", err);
setHasError(true);
});
return () => {
stopped = true;
if (scannerRef.current) {
(scannerRef.current as { clear: () => Promise<void> })
.clear()
.catch(console.error);
}
};
}, []); // empty deps — runs once on mount, cleans up on unmount
const handleManualSubmit = () => {
const token = manualToken.trim();
if (token) {
onScan(token);
}
};
return (
<div className="space-y-4">
{!hasError ? (
<div id={scannerDivId} className="overflow-hidden rounded-xl" />
) : (
<div className="rounded-xl border border-white/10 bg-white/5 p-4 text-center">
<p className="mb-2 text-sm text-white/60">
Camera niet beschikbaar. Plak het QR-token hieronder.
</p>
</div>
)}
{/* Manual fallback */}
<div>
<p className="mb-2 text-white/40 text-xs">Of plak token handmatig:</p>
<div className="flex gap-2">
<Input
value={manualToken}
onChange={(e) => setManualToken(e.target.value)}
placeholder="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="bg-white text-[#214e51] hover:bg-white/90"
>
OK
</Button>
</div>
</div>
<Button
onClick={onCancel}
variant="outline"
className="w-full border-white/20 bg-transparent text-white hover:bg-white/10"
>
Annuleren
</Button>
</div>
);
}

View File

@@ -0,0 +1,99 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
interface TransactionRow {
id: string;
amountCents: number;
userName: string;
}
interface ReverseDialogProps {
transaction: TransactionRow;
onClose: () => void;
}
export function ReverseDialog({ transaction, onClose }: ReverseDialogProps) {
const queryClient = useQueryClient();
const reverseMutation = useMutation(
orpc.drinkkaart.reverseTransaction.mutationOptions(),
);
const handleConfirm = () => {
reverseMutation.mutate(
{ transactionId: transaction.id },
{
onSuccess: () => {
toast.success(
`${formatCents(transaction.amountCents)} teruggestort aan ${transaction.userName}`,
);
queryClient.invalidateQueries({
queryKey: orpc.drinkkaart.getTransactionLog.key(),
});
onClose();
},
onError: (err: Error) => {
toast.error(err.message ?? "Fout bij terugdraaien");
},
},
);
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<button
type="button"
className="absolute inset-0 bg-black/60"
aria-label="Sluiten"
onClick={onClose}
/>
<div className="relative z-10 w-full max-w-sm rounded-2xl bg-[#1a3d40] p-6">
<h3 className="mb-3 font-['Intro',sans-serif] text-white text-xl">
Transactie terugdraaien
</h3>
<p className="mb-1 text-white/80">
Weet je zeker dat je{" "}
<strong className="text-white">
{formatCents(transaction.amountCents)}
</strong>{" "}
wil terugdraaien voor{" "}
<strong className="text-white">{transaction.userName}</strong>?
</p>
<p className="mb-5 text-sm text-white/50">
Dit voegt {formatCents(transaction.amountCents)} terug toe aan het
saldo.
</p>
{reverseMutation.isError && (
<p className="mb-3 text-red-400 text-sm">
{(reverseMutation.error as Error)?.message ??
"Fout bij terugdraaien"}
</p>
)}
<div className="flex gap-3">
<Button
onClick={handleConfirm}
disabled={reverseMutation.isPending}
className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90"
>
{reverseMutation.isPending
? "Verwerken..."
: "Terugdraaien bevestigen"}
</Button>
<Button
onClick={onClose}
variant="outline"
disabled={reverseMutation.isPending}
className="border-white/20 bg-transparent text-white hover:bg-white/10"
>
Annuleren
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,30 @@
import { formatCents } from "@/lib/drinkkaart";
interface ScanResultCardProps {
userName: string;
userEmail: string;
balance: number;
}
export function ScanResultCard({
userName,
userEmail,
balance,
}: ScanResultCardProps) {
return (
<div className="rounded-xl border border-white/10 bg-white/5 p-5">
<div className="mb-4 flex items-start justify-between">
<div>
<p className="font-semibold text-lg text-white">{userName}</p>
<p className="text-sm text-white/50">{userEmail}</p>
</div>
<div className="text-right">
<p className="text-white/40 text-xs">Saldo</p>
<p className="font-['Intro',sans-serif] text-2xl text-white">
{formatCents(balance)}
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,57 @@
import { formatCents } from "@/lib/drinkkaart";
interface TopupRow {
id: string;
type: "payment" | "admin_credit";
amountCents: number;
balanceBefore: number;
balanceAfter: number;
reason: string | null;
paidAt: Date;
}
interface TopUpHistoryProps {
topups: TopupRow[];
}
export function TopUpHistory({ topups }: TopUpHistoryProps) {
if (topups.length === 0) {
return <p className="text-sm text-white/40">Nog geen opladingen.</p>;
}
return (
<ul className="space-y-2">
{topups.map((t) => {
const date = new Date(t.paidAt).toLocaleDateString("nl-BE", {
day: "numeric",
month: "short",
year: "numeric",
});
return (
<li
key={t.id}
className="flex items-start justify-between rounded-lg border border-white/10 bg-white/5 px-4 py-3"
>
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-green-400">
+ {formatCents(t.amountCents)}
</span>
{t.type === "admin_credit" && (
<span className="rounded-full border border-yellow-400/30 bg-yellow-400/10 px-2 py-0.5 text-xs text-yellow-300">
Admin credit
</span>
)}
</div>
{t.reason && (
<p className="mt-0.5 text-white/50 text-xs">{t.reason}</p>
)}
</div>
<span className="text-sm text-white/50 tabular-nums">{date}</span>
</li>
);
})}
</ul>
);
}

View File

@@ -0,0 +1,144 @@
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
formatCents,
TOPUP_MAX_CENTS,
TOPUP_MIN_CENTS,
TOPUP_PRESETS_CENTS,
} from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
interface TopUpModalProps {
onClose: () => void;
}
export function TopUpModal({ onClose }: TopUpModalProps) {
const [selectedCents, setSelectedCents] = useState<number>(1000);
const [customEuros, setCustomEuros] = useState("");
const [useCustom, setUseCustom] = useState(false);
const checkoutMutation = useMutation({
...orpc.drinkkaart.getTopUpCheckoutUrl.mutationOptions(),
onSuccess: (data: { checkoutUrl: string }) => {
window.location.href = data.checkoutUrl;
},
onError: (err: Error) => {
console.error("Checkout error:", err);
},
});
const amountCents = useCustom
? Math.round((Number.parseFloat(customEuros || "0") || 0) * 100)
: selectedCents;
const isValidAmount =
Number.isInteger(amountCents) &&
amountCents >= TOPUP_MIN_CENTS &&
amountCents <= TOPUP_MAX_CENTS;
const handleSubmit = () => {
if (!isValidAmount) return;
checkoutMutation.mutate({ amountCents });
};
return (
<div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center">
<button
type="button"
className="absolute inset-0 bg-black/60"
aria-label="Sluiten"
onClick={onClose}
/>
<div className="relative z-10 w-full max-w-sm rounded-t-2xl bg-[#1a3d40] p-6 sm:rounded-2xl">
<div className="mb-5 flex items-center justify-between">
<h2 className="font-['Intro',sans-serif] text-white text-xl">
Drinkkaart opladen
</h2>
<button
type="button"
onClick={onClose}
className="text-white/50 hover:text-white"
aria-label="Sluiten"
>
</button>
</div>
{/* Preset amounts */}
<div className="mb-4 grid grid-cols-4 gap-2">
{TOPUP_PRESETS_CENTS.map((cents) => (
<button
key={cents}
type="button"
onClick={() => {
setSelectedCents(cents);
setUseCustom(false);
}}
className={`rounded-lg border py-3 font-medium text-sm transition-colors ${
!useCustom && selectedCents === cents
? "border-white bg-white text-[#214e51]"
: "border-white/20 text-white hover:border-white/50"
}`}
>
{formatCents(cents)}
</button>
))}
</div>
{/* Custom amount */}
<div className="mb-5">
<label
htmlFor="custom-amount"
className="mb-2 block text-sm text-white/60"
>
Eigen bedrag ( 1 500)
</label>
<div className="relative">
<span className="absolute top-1/2 left-3 -translate-y-1/2 text-white/50">
</span>
<Input
id="custom-amount"
type="number"
min="1"
max="500"
step="0.50"
placeholder="Bijv. 15"
value={customEuros}
onChange={(e) => {
setCustomEuros(e.target.value);
setUseCustom(true);
}}
className="border-white/20 bg-white/10 pl-8 text-white placeholder:text-white/30"
/>
</div>
{useCustom && !isValidAmount && customEuros !== "" && (
<p className="mt-1 text-red-400 text-sm">
Bedrag moet tussen {formatCents(TOPUP_MIN_CENTS)} en{" "}
{formatCents(TOPUP_MAX_CENTS)} liggen
</p>
)}
</div>
<div className="mb-3 rounded-lg bg-white/5 px-4 py-3">
<span className="text-sm text-white/60">Te betalen: </span>
<span className="font-semibold text-white">
{isValidAmount ? formatCents(amountCents) : "—"}
</span>
</div>
<Button
onClick={handleSubmit}
disabled={!isValidAmount || checkoutMutation.isPending}
className="w-full bg-white font-semibold text-[#214e51] hover:bg-white/90 disabled:opacity-50"
>
{checkoutMutation.isPending
? "Doorsturen naar betaling..."
: "Naar betaling"}
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,77 @@
import { formatCents } from "@/lib/drinkkaart";
interface TransactionRow {
id: string;
type: "deduction" | "reversal";
amountCents: number;
balanceBefore: number;
balanceAfter: number;
note: string | null;
reversedBy: string | null;
reverses: string | null;
createdAt: Date;
}
interface TransactionHistoryProps {
transactions: TransactionRow[];
}
export function TransactionHistory({ transactions }: TransactionHistoryProps) {
if (transactions.length === 0) {
return <p className="text-sm text-white/40">Nog geen transacties.</p>;
}
return (
<ul className="space-y-2">
{transactions.map((t) => {
const date = new Date(t.createdAt).toLocaleString("nl-BE", {
day: "numeric",
month: "short",
hour: "2-digit",
minute: "2-digit",
});
const isReversal = t.type === "reversal";
const isReversed = !!t.reversedBy;
return (
<li
key={t.id}
className={`flex items-start justify-between rounded-lg border px-4 py-3 ${
isReversal
? "border-green-400/20 bg-green-400/5"
: isReversed
? "border-white/5 bg-white/3 opacity-60"
: "border-white/10 bg-white/5"
}`}
>
<div>
<div className="flex items-center gap-2">
<span
className={`font-medium ${isReversal ? "text-green-400" : "text-red-400"}`}
>
{isReversal ? "+ " : " "}
{formatCents(t.amountCents)}
</span>
{isReversal && (
<span className="rounded-full border border-green-400/30 bg-green-400/10 px-2 py-0.5 text-green-300 text-xs">
Teruggedraaid
</span>
)}
{isReversed && !isReversal && (
<span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-white/40 text-xs">
Teruggedraaid
</span>
)}
</div>
{t.note && (
<p className="mt-0.5 text-white/50 text-xs">{t.note}</p>
)}
</div>
<span className="text-sm text-white/50 tabular-nums">{date}</span>
</li>
);
})}
</ul>
);
}

View File

@@ -1,3 +1,5 @@
import { useState } from "react";
interface Props {
token: string;
onReset: () => void;
@@ -9,6 +11,28 @@ export function SuccessScreen({ token, onReset }: Props) {
? `${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);
};
return (
<section
id="registration"
@@ -65,6 +89,34 @@ export function SuccessScreen({ token, onReset }: Props) {
Nog een inschrijving
</button>
</div>
{/* Drinkkaart account prompt */}
{!drinkkaartPromptDismissed && (
<div className="mt-8 rounded-lg border border-white/20 bg-white/10 p-6">
<h3 className="mb-2 font-['Intro',sans-serif] text-lg text-white">
Wil je een Drinkkaart?
</h3>
<p className="mb-4 text-sm text-white/70">
Maak een gratis account aan om je digitale Drinkkaart te
activeren en saldo op te laden vóór het evenement.
</p>
<div className="flex flex-wrap gap-3">
<a
href="/login"
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:bg-gray-100"
>
Account aanmaken
</a>
<button
type="button"
onClick={handleDismissPrompt}
className="text-sm text-white/50 underline underline-offset-2 transition-colors hover:text-white/80"
>
Overslaan
</button>
</div>
</div>
)}
</div>
</div>
</section>

View File

@@ -217,7 +217,7 @@ export function WatcherForm({ onBack }: Props) {
<div>
<p className="font-semibold text-white">Drinkkaart inbegrepen</p>
<p className="text-sm text-white/70">
Je betaald bij registratie{" "}
Je betaald bij registratie
<strong className="text-teal-300">5</strong> (+ 2 per
medebezoeker) dat gaat naar je drinkkaart.
{guests.length > 0 && (

View File

@@ -0,0 +1,18 @@
// Frontend constants and utilities for the Drinkkaart feature.
export const TOPUP_PRESETS_CENTS = [500, 1000, 2000, 5000] as const;
// = €5, €10, €20, €50
export const DEDUCTION_PRESETS_CENTS = [150, 200, 300, 500] as const;
// = €1,50 / €2,00 / €3,00 / €5,00 — typical drink prices
export const TOPUP_MIN_CENTS = 100; // €1
export const TOPUP_MAX_CENTS = 50000; // €500
/** Format a cents integer as a Belgian euro string, e.g. 1250 → "€ 12,50". */
export function formatCents(cents: number): string {
return new Intl.NumberFormat("nl-BE", {
style: "currency",
currency: "EUR",
}).format(cents / 100);
}

View File

@@ -12,10 +12,12 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as TermsRouteImport } from './routes/terms'
import { Route as PrivacyRouteImport } from './routes/privacy'
import { Route as LoginRouteImport } from './routes/login'
import { Route as DrinkkaartRouteImport } from './routes/drinkkaart'
import { Route as ContactRouteImport } from './routes/contact'
import { Route as AdminRouteImport } from './routes/admin'
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 ApiRpcSplatRouteImport } from './routes/api/rpc/$'
import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
@@ -35,26 +37,36 @@ const LoginRoute = LoginRouteImport.update({
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
const DrinkkaartRoute = DrinkkaartRouteImport.update({
id: '/drinkkaart',
path: '/drinkkaart',
getParentRoute: () => rootRouteImport,
} as any)
const ContactRoute = ContactRouteImport.update({
id: '/contact',
path: '/contact',
getParentRoute: () => rootRouteImport,
} as any)
const AdminRoute = AdminRouteImport.update({
id: '/admin',
path: '/admin',
getParentRoute: () => rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const AdminIndexRoute = AdminIndexRouteImport.update({
id: '/admin/',
path: '/admin/',
getParentRoute: () => rootRouteImport,
} as any)
const ManageTokenRoute = ManageTokenRouteImport.update({
id: '/manage/$token',
path: '/manage/$token',
getParentRoute: () => rootRouteImport,
} as any)
const AdminDrinkkaartRoute = AdminDrinkkaartRouteImport.update({
id: '/admin/drinkkaart',
path: '/admin/drinkkaart',
getParentRoute: () => rootRouteImport,
} as any)
const ApiWebhookLemonsqueezyRoute = ApiWebhookLemonsqueezyRouteImport.update({
id: '/api/webhook/lemonsqueezy',
path: '/api/webhook/lemonsqueezy',
@@ -73,24 +85,28 @@ const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/admin': typeof AdminRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin/': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/admin': typeof AdminRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
@@ -98,12 +114,14 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/admin': typeof AdminRoute
'/contact': typeof ContactRoute
'/drinkkaart': typeof DrinkkaartRoute
'/login': typeof LoginRoute
'/privacy': typeof PrivacyRoute
'/terms': typeof TermsRoute
'/admin/drinkkaart': typeof AdminDrinkkaartRoute
'/manage/$token': typeof ManageTokenRoute
'/admin/': typeof AdminIndexRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
'/api/webhook/lemonsqueezy': typeof ApiWebhookLemonsqueezyRoute
@@ -112,36 +130,42 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
| '/admin'
| '/contact'
| '/drinkkaart'
| '/login'
| '/privacy'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin/'
| '/api/auth/$'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
| '/admin'
| '/contact'
| '/drinkkaart'
| '/login'
| '/privacy'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin'
| '/api/auth/$'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
id:
| '__root__'
| '/'
| '/admin'
| '/contact'
| '/drinkkaart'
| '/login'
| '/privacy'
| '/terms'
| '/admin/drinkkaart'
| '/manage/$token'
| '/admin/'
| '/api/auth/$'
| '/api/rpc/$'
| '/api/webhook/lemonsqueezy'
@@ -149,12 +173,14 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
AdminRoute: typeof AdminRoute
ContactRoute: typeof ContactRoute
DrinkkaartRoute: typeof DrinkkaartRoute
LoginRoute: typeof LoginRoute
PrivacyRoute: typeof PrivacyRoute
TermsRoute: typeof TermsRoute
AdminDrinkkaartRoute: typeof AdminDrinkkaartRoute
ManageTokenRoute: typeof ManageTokenRoute
AdminIndexRoute: typeof AdminIndexRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
ApiWebhookLemonsqueezyRoute: typeof ApiWebhookLemonsqueezyRoute
@@ -183,6 +209,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
'/drinkkaart': {
id: '/drinkkaart'
path: '/drinkkaart'
fullPath: '/drinkkaart'
preLoaderRoute: typeof DrinkkaartRouteImport
parentRoute: typeof rootRouteImport
}
'/contact': {
id: '/contact'
path: '/contact'
@@ -190,13 +223,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ContactRouteImport
parentRoute: typeof rootRouteImport
}
'/admin': {
id: '/admin'
path: '/admin'
fullPath: '/admin'
preLoaderRoute: typeof AdminRouteImport
parentRoute: typeof rootRouteImport
}
'/': {
id: '/'
path: '/'
@@ -204,6 +230,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
'/admin/': {
id: '/admin/'
path: '/admin'
fullPath: '/admin/'
preLoaderRoute: typeof AdminIndexRouteImport
parentRoute: typeof rootRouteImport
}
'/manage/$token': {
id: '/manage/$token'
path: '/manage/$token'
@@ -211,6 +244,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ManageTokenRouteImport
parentRoute: typeof rootRouteImport
}
'/admin/drinkkaart': {
id: '/admin/drinkkaart'
path: '/admin/drinkkaart'
fullPath: '/admin/drinkkaart'
preLoaderRoute: typeof AdminDrinkkaartRouteImport
parentRoute: typeof rootRouteImport
}
'/api/webhook/lemonsqueezy': {
id: '/api/webhook/lemonsqueezy'
path: '/api/webhook/lemonsqueezy'
@@ -237,12 +277,14 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
AdminRoute: AdminRoute,
ContactRoute: ContactRoute,
DrinkkaartRoute: DrinkkaartRoute,
LoginRoute: LoginRoute,
PrivacyRoute: PrivacyRoute,
TermsRoute: TermsRoute,
AdminDrinkkaartRoute: AdminDrinkkaartRoute,
ManageTokenRoute: ManageTokenRoute,
AdminIndexRoute: AdminIndexRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
ApiRpcSplatRoute: ApiRpcSplatRoute,
ApiWebhookLemonsqueezyRoute: ApiWebhookLemonsqueezyRoute,

View File

@@ -9,6 +9,7 @@ import {
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import { CookieConsent } from "@/components/CookieConsent";
import { SiteHeader } from "@/components/SiteHeader";
import { Toaster } from "@/components/ui/sonner";
import type { orpc } from "@/utils/orpc";
@@ -165,6 +166,7 @@ function RootDocument() {
>
Ga naar hoofdinhoud
</a>
<SiteHeader />
<div id="main-content">
<Outlet />
</div>

View File

@@ -0,0 +1,236 @@
import { useMutation } from "@tanstack/react-query";
import { createFileRoute, Link, redirect } from "@tanstack/react-router";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { AdminTransactionLog } from "@/components/drinkkaart/AdminTransactionLog";
import { DeductionPanel } from "@/components/drinkkaart/DeductionPanel";
import { ManualCreditForm } from "@/components/drinkkaart/ManualCreditForm";
import { QrScanner } from "@/components/drinkkaart/QrScanner";
import { ScanResultCard } from "@/components/drinkkaart/ScanResultCard";
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
export const Route = createFileRoute("/admin/drinkkaart")({
component: AdminDrinkkaartPage,
beforeLoad: async () => {
const session = await authClient.getSession();
if (!session.data?.user) {
throw redirect({ to: "/login" });
}
const user = session.data.user as { role?: string };
if (user.role !== "admin") {
throw redirect({ to: "/" });
}
},
});
type ScanState =
| { step: "idle" }
| { step: "scanning" }
| { step: "resolving" }
| {
step: "resolved";
drinkkaartId: string;
userId: string;
userName: string;
userEmail: string;
balance: number;
}
| {
step: "success";
transactionId: string;
userName: string;
balanceAfter: number;
}
| { step: "error"; message: string; retryable: boolean }
| { step: "manual_credit" };
function AdminDrinkkaartPage() {
const [scanState, setScanState] = useState<ScanState>({ step: "idle" });
const resolveQrMutation = useMutation(
orpc.drinkkaart.resolveQrToken.mutationOptions(),
);
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",
retryable: true,
});
},
},
);
},
[resolveQrMutation],
);
const handleDeductSuccess = (transactionId: string, balanceAfter: number) => {
const userName =
scanState.step === "resolved" ? scanState.userName : "Gebruiker";
const amountDeducted =
scanState.step === "resolved"
? scanState.balance - balanceAfter
: undefined;
toast.success(
`Afschrijving verwerkt${amountDeducted !== undefined ? `${formatCents(amountDeducted)}` : ""}`,
);
setScanState({ step: "success", transactionId, userName, balanceAfter });
};
return (
<div className="min-h-screen bg-[#214e51]">
{/* Header */}
<header className="border-white/10 border-b bg-[#214e51]/95 px-6 py-5">
<div className="mx-auto flex max-w-2xl items-center gap-4">
<Link to="/admin" className="text-sm text-white/60 hover:text-white">
Admin
</Link>
<h1 className="font-['Intro',sans-serif] text-2xl text-white">
Drinkkaart Beheer
</h1>
</div>
</header>
<main className="mx-auto max-w-2xl space-y-8 px-6 py-8">
{/* Scan / State machine */}
<div className="rounded-2xl border border-white/10 bg-white/5 p-6">
{scanState.step === "idle" && (
<div className="space-y-4">
<p className="text-sm text-white/60">
Scan een QR-code of laad handmatig op.
</p>
<div className="flex flex-col gap-3 sm:flex-row">
<Button
onClick={() => setScanState({ step: "scanning" })}
className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90"
>
Scan QR
</Button>
<Button
onClick={() => setScanState({ step: "manual_credit" })}
variant="outline"
className="flex-1 border-white/30 bg-transparent text-white hover:bg-white/10"
>
Handmatig opladen
</Button>
</div>
</div>
)}
{scanState.step === "scanning" && (
<QrScanner
onScan={handleScan}
onCancel={() => setScanState({ step: "idle" })}
/>
)}
{scanState.step === "resolving" && (
<div className="py-8 text-center">
<p className="text-white/60">QR-code wordt gecontroleerd...</p>
</div>
)}
{scanState.step === "resolved" && (
<div className="space-y-5">
<ScanResultCard
userName={scanState.userName}
userEmail={scanState.userEmail}
balance={scanState.balance}
/>
<DeductionPanel
drinkkaartId={scanState.drinkkaartId}
userName={scanState.userName}
userEmail={scanState.userEmail}
balance={scanState.balance}
onSuccess={handleDeductSuccess}
onCancel={() => setScanState({ step: "idle" })}
/>
</div>
)}
{scanState.step === "success" && (
<div className="space-y-5">
<div className="rounded-xl border border-green-400/20 bg-green-400/5 p-5 text-center">
<p className="font-semibold text-green-300 text-lg">
Betaling verwerkt
</p>
<p className="mt-1 text-sm text-white/60">
{scanState.userName} nieuw saldo:{" "}
<strong className="text-white">
{formatCents(scanState.balanceAfter)}
</strong>
</p>
</div>
<Button
onClick={() => setScanState({ step: "idle" })}
className="w-full bg-white font-semibold text-[#214e51] hover:bg-white/90"
>
Volgende scan
</Button>
</div>
)}
{scanState.step === "error" && (
<div className="space-y-4">
<div className="rounded-xl border border-red-400/20 bg-red-400/5 p-4">
<p className="font-medium text-red-300">Fout</p>
<p className="mt-1 text-sm text-white/60">
{scanState.message}
</p>
</div>
<div className="flex gap-3">
{scanState.retryable && (
<Button
onClick={() => setScanState({ step: "scanning" })}
className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90"
>
Opnieuw proberen
</Button>
)}
<Button
onClick={() => setScanState({ step: "idle" })}
variant="outline"
className="flex-1 border-white/20 bg-transparent text-white hover:bg-white/10"
>
Annuleren
</Button>
</div>
</div>
)}
{scanState.step === "manual_credit" && (
<ManualCreditForm onDone={() => setScanState({ step: "idle" })} />
)}
</div>
{/* Transaction log */}
<div>
<h2 className="mb-4 font-['Intro',sans-serif] text-white text-xl">
Transactieoverzicht
</h2>
<AdminTransactionLog />
</div>
</main>
</div>
);
}

View File

@@ -32,7 +32,7 @@ import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { orpc } from "@/utils/orpc";
export const Route = createFileRoute("/admin")({
export const Route = createFileRoute("/admin/")({
component: AdminPage,
beforeLoad: async () => {
const session = await authClient.getSession();
@@ -286,14 +286,22 @@ function AdminPage() {
Admin Dashboard
</h1>
</div>
<Button
onClick={handleSignOut}
variant="outline"
className="border-white/30 bg-transparent text-white hover:bg-white/10"
>
<LogOut className="mr-2 h-4 w-4" />
Uitloggen
</Button>
<div className="flex items-center gap-3">
<Link
to="/admin/drinkkaart"
className="inline-flex items-center rounded-lg border border-white/30 px-4 py-2 text-sm text-white/80 transition-colors hover:bg-white/10 hover:text-white"
>
Drinkkaart beheer
</Link>
<Button
onClick={handleSignOut}
variant="outline"
className="border-white/30 bg-transparent text-white hover:bg-white/10"
>
<LogOut className="mr-2 h-4 w-4" />
Uitloggen
</Button>
</div>
</div>
</header>

View File

@@ -1,9 +1,9 @@
import { createHmac } from "node:crypto";
import { createHmac, randomUUID } from "node:crypto";
import { db } from "@kk/db";
import { registration } from "@kk/db/schema";
import { drinkkaart, drinkkaartTopup, registration } from "@kk/db/schema";
import { env } from "@kk/env/server";
import { createFileRoute } from "@tanstack/react-router";
import { eq } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
// Webhook payload types
interface LemonSqueezyWebhookPayload {
@@ -11,6 +11,9 @@ interface LemonSqueezyWebhookPayload {
event_name: string;
custom_data?: {
registration_token?: string;
type?: string;
drinkkaartId?: string;
userId?: string;
};
};
data: {
@@ -20,6 +23,7 @@ interface LemonSqueezyWebhookPayload {
customer_id: number;
order_number: number;
status: string;
total: number;
};
};
}
@@ -68,7 +72,102 @@ async function handleWebhook({ request }: { request: Request }) {
return new Response("Event ignored", { status: 200 });
}
const registrationToken = event.meta.custom_data?.registration_token;
const customData = event.meta.custom_data;
// ---------------------------------------------------------------------------
// Branch: Drinkkaart top-up
// ---------------------------------------------------------------------------
if (customData?.type === "drinkkaart_topup") {
const { drinkkaartId, userId } = customData;
if (!drinkkaartId || !userId) {
console.error(
"Missing drinkkaartId or userId in drinkkaart_topup webhook",
);
return new Response("Missing drinkkaart data", { status: 400 });
}
const orderId = event.data.id;
const customerId = String(event.data.attributes.customer_id);
// Use Lemon Squeezy's confirmed total (in cents)
const amountCents = event.data.attributes.total;
// Idempotency: skip if already processed
const existing = await db
.select({ id: drinkkaartTopup.id })
.from(drinkkaartTopup)
.where(eq(drinkkaartTopup.lemonsqueezyOrderId, orderId))
.limit(1)
.then((r) => r[0]);
if (existing) {
console.log(`Drinkkaart topup already processed for order ${orderId}`);
return new Response("OK", { status: 200 });
}
const card = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.id, drinkkaartId))
.limit(1)
.then((r) => r[0]);
if (!card) {
console.error(`Drinkkaart not found: ${drinkkaartId}`);
return new Response("Not found", { status: 404 });
}
const balanceBefore = card.balance;
const balanceAfter = balanceBefore + amountCents;
// Optimistic lock update
const result = await db
.update(drinkkaart)
.set({
balance: balanceAfter,
version: card.version + 1,
updatedAt: new Date(),
})
.where(
and(
eq(drinkkaart.id, drinkkaartId),
eq(drinkkaart.version, card.version),
),
);
if (result.rowsAffected === 0) {
// Return 500 so Lemon Squeezy retries; idempotency check prevents double-credit
console.error(
`Drinkkaart optimistic lock conflict for ${drinkkaartId}`,
);
return new Response("Conflict — please retry", { status: 500 });
}
await db.insert(drinkkaartTopup).values({
id: randomUUID(),
drinkkaartId,
userId,
amountCents,
balanceBefore,
balanceAfter,
type: "payment",
lemonsqueezyOrderId: orderId,
lemonsqueezyCustomerId: customerId,
adminId: null,
reason: null,
paidAt: new Date(),
});
console.log(
`Drinkkaart topup successful: drinkkaart=${drinkkaartId}, amount=${amountCents}c, order=${orderId}`,
);
return new Response("OK", { status: 200 });
}
// ---------------------------------------------------------------------------
// Branch: Registration payment
// ---------------------------------------------------------------------------
const registrationToken = customData?.registration_token;
if (!registrationToken) {
console.error("No registration token in webhook payload");
return new Response("Missing registration token", { status: 400 });

View File

@@ -0,0 +1,138 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { QrCode, Wallet } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { QrCodeDisplay } from "@/components/drinkkaart/QrCodeDisplay";
import { TopUpHistory } from "@/components/drinkkaart/TopUpHistory";
import { TopUpModal } from "@/components/drinkkaart/TopUpModal";
import { TransactionHistory } from "@/components/drinkkaart/TransactionHistory";
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";
export const Route = createFileRoute("/drinkkaart")({
validateSearch: (search: Record<string, unknown>) => ({
topup: search.topup as string | undefined,
}),
component: DrinkkaartPage,
beforeLoad: async () => {
const session = await authClient.getSession();
if (!session.data?.user) {
throw redirect({ to: "/login" });
}
},
});
function DrinkkaartPage() {
const queryClient = useQueryClient();
const search = Route.useSearch();
const [showQr, setShowQr] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
const { data, isLoading } = useQuery(
orpc.drinkkaart.getMyDrinkkaart.queryOptions(),
);
// Handle topup=success redirect
useEffect(() => {
if (search.topup === "success") {
toast.success("Oplading geslaagd! Je saldo is bijgewerkt.");
queryClient.invalidateQueries({
queryKey: orpc.drinkkaart.getMyDrinkkaart.key(),
});
// Remove query param without full navigation
const url = new URL(window.location.href);
url.searchParams.delete("topup");
window.history.replaceState({}, "", url.toString());
}
}, [search.topup, queryClient]);
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center bg-[#214e51]">
<div className="h-10 w-10 animate-spin rounded-full border-2 border-white/20 border-t-white" />
</div>
);
}
return (
<div className="min-h-screen bg-[#214e51]">
<main className="mx-auto max-w-lg px-4 py-10">
<h1 className="mb-6 font-['Intro',sans-serif] text-3xl text-white">
Mijn Drinkkaart
</h1>
{/* Balance card */}
<div className="mb-6 rounded-2xl border border-white/10 bg-white/5 p-6">
<p className="mb-1 text-sm text-white/50">Huidig saldo</p>
<p className="mb-4 font-['Intro',sans-serif] text-5xl text-white">
{data ? formatCents(data.balance) : "—"}
</p>
<div className="flex flex-wrap gap-3">
<Button
onClick={() => setShowQr((v) => !v)}
variant="outline"
className="border-white/30 bg-transparent text-white hover:bg-white/10"
>
<QrCode className="mr-2 h-4 w-4" />
{showQr ? "Verberg QR-code" : "Toon QR-code"}
</Button>
<Button
onClick={() => setShowTopUp(true)}
className="bg-white font-semibold text-[#214e51] hover:bg-white/90"
>
<Wallet className="mr-2 h-4 w-4" />
Opladen
</Button>
</div>
</div>
{/* QR code */}
{showQr && (
<div className="mb-6 flex justify-center rounded-2xl border border-white/10 bg-white/5 p-6">
<QrCodeDisplay />
</div>
)}
{/* Top-up history */}
<section className="mb-8">
<h2 className="mb-3 font-['Intro',sans-serif] text-lg text-white/80">
Opladingen
</h2>
{data ? (
<TopUpHistory
topups={
data.topups as Parameters<typeof TopUpHistory>[0]["topups"]
}
/>
) : (
<p className="text-sm text-white/40">Laden...</p>
)}
</section>
{/* Transaction history */}
<section>
<h2 className="mb-3 font-['Intro',sans-serif] text-lg text-white/80">
Transacties
</h2>
{data ? (
<TransactionHistory
transactions={
data.transactions as Parameters<
typeof TransactionHistory
>[0]["transactions"]
}
/>
) : (
<p className="text-sm text-white/40">Laden...</p>
)}
</section>
</main>
{showTopUp && <TopUpModal onClose={() => setShowTopUp(false)} />}
</div>
);
}