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>
);
}

107
bun.lock
View File

@@ -45,9 +45,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",
@@ -66,6 +68,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",
@@ -919,6 +922,8 @@
"@types/offscreencanvas": ["@types/offscreencanvas@2019.7.3", "", {}, "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A=="],
"@types/qrcode": ["@types/qrcode@1.5.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
"@types/react": ["@types/react@19.2.7", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg=="],
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
@@ -1019,6 +1024,8 @@
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
"camelcase": ["camelcase@5.3.1", "", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="],
"camera-controls": ["camera-controls@3.1.2", "", { "peerDependencies": { "three": ">=0.126.1" } }, "sha512-xkxfpG2ECZ6Ww5/9+kf4mfg1VEYAoe9aDSY+IwF0UEs7qEzwy0aVRfs2grImIECs/PoBtWFrh7RXsQkwG922JA=="],
"caniuse-lite": ["caniuse-lite@1.0.30001774", "", {}, "sha512-DDdwPGz99nmIEv216hKSgLD+D4ikHQHjBC/seF98N9CPqRX4M5mSxT9eTV6oyisnJcuzxtZy4n17yKKQYmYQOA=="],
@@ -1039,7 +1046,7 @@
"cli-width": ["cli-width@4.1.0", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
"cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
"clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
@@ -1089,6 +1096,8 @@
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
"decimal.js": ["decimal.js@10.6.0", "", {}, "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg=="],
"dedent": ["dedent@1.7.1", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-9JmrhGZpOlEgOLdQgSm0zxFaYoQon408V1v49aqTWuXENVlnCuY9JBZcXZiCsZQWDjTm5Qf/nIvAy77mXDAjEg=="],
@@ -1113,6 +1122,8 @@
"diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
"dijkstrajs": ["dijkstrajs@1.0.3", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
"dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],
"dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
@@ -1141,7 +1152,7 @@
"electron-to-chromium": ["electron-to-chromium@1.5.302", "", {}, "sha512-sM6HAN2LyK82IyPBpznDRqlTQAtuSaO+ShzFiWTvoMJLHyZ+Y39r8VMfHzwbU8MVBzQ4Wdn85+wlZl2TLGIlwg=="],
"emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
@@ -1217,6 +1228,8 @@
"find-process": ["find-process@2.0.0", "", { "dependencies": { "chalk": "~4.1.2", "commander": "^12.1.0", "loglevel": "^1.9.2" }, "bin": { "find-process": "dist/bin/find-process.js" } }, "sha512-YUBQnteWGASJoEVVsOXy6XtKAY2O1FCsWnnvQ8y0YwgY1rZiKeVptnFvMu6RSELZAJOGklqseTnUGGs5D0bKmg=="],
"find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
"foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="],
"formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="],
@@ -1283,6 +1296,8 @@
"html-encoding-sniffer": ["html-encoding-sniffer@4.0.0", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="],
"html5-qrcode": ["html5-qrcode@2.3.8", "", {}, "sha512-jsr4vafJhwoLVEDW3n1KvPnCCXWaQfRng0/EEYk1vNcQGcG/htAdhJX0be8YyqMoSz7+hZvOZSTAepsabiuhiQ=="],
"htmlparser2": ["htmlparser2@10.1.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "entities": "^7.0.1" } }, "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
@@ -1421,6 +1436,8 @@
"lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="],
"locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
"log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="],
"loglevel": ["loglevel@1.9.2", "", {}, "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg=="],
@@ -1521,6 +1538,12 @@
"outvariant": ["outvariant@1.4.3", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
"p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
"p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
"p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
"package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="],
"package-manager-detector": ["package-manager-detector@1.6.0", "", {}, "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA=="],
@@ -1543,6 +1566,8 @@
"path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="],
@@ -1557,6 +1582,8 @@
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
"postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
"postcss-selector-parser": ["postcss-selector-parser@7.1.1", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg=="],
@@ -1585,6 +1612,8 @@
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
"qrcode": ["qrcode@1.5.4", "", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
"qs": ["qs@6.15.0", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ=="],
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
@@ -1615,6 +1644,8 @@
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"require-main-filename": ["require-main-filename@2.0.0", "", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="],
"reselect": ["reselect@5.1.1", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
"resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
@@ -1659,6 +1690,8 @@
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
"set-cookie-parser": ["set-cookie-parser@2.7.2", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
"setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
@@ -1705,7 +1738,7 @@
"strict-event-emitter": ["strict-event-emitter@0.5.1", "", {}, "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ=="],
"string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"string-width-cjs": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
@@ -1867,13 +1900,15 @@
"which": ["which@4.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="],
"which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
"wildcard-match": ["wildcard-match@5.1.4", "", {}, "sha512-wldeCaczs8XXq7hj+5d/F38JE2r7EXgb6WQDM84RVwxy81T/sxB5e9+uZLK9Q9oNz1mlvjut+QtvgaOQFPVq/g=="],
"workerd": ["workerd@1.20260302.0", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260302.0", "@cloudflare/workerd-darwin-arm64": "1.20260302.0", "@cloudflare/workerd-linux-64": "1.20260302.0", "@cloudflare/workerd-linux-arm64": "1.20260302.0", "@cloudflare/workerd-windows-64": "1.20260302.0" }, "bin": { "workerd": "bin/workerd" } }, "sha512-FhNdC8cenMDllI6bTktFgxP5Bn5ZEnGtofgKipY6pW9jtq708D1DeGI6vGad78KQLBGaDwFy1eThjCoLYgFfog=="],
"wrangler": ["wrangler@4.68.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.14.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260302.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260302.0" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260302.0" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-DCjl2ZfjwWV10iH4Zn+97isitPkb7BYxpbt4E/Okd/QKLFTp9xdwoa999UN9lugToqPm5Zz/UsRu6hpKZuT8BA=="],
"wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="],
"wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"wrap-ansi-cjs": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
@@ -1889,15 +1924,15 @@
"xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"y18n": ["y18n@4.0.3", "", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="],
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["yaml@2.8.2", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="],
"yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
"yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="],
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="],
"yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="],
@@ -1939,10 +1974,10 @@
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@inquirer/core/wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"@isaacs/cliui/wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="],
"@jridgewell/gen-mapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@jridgewell/remapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
@@ -1993,12 +2028,8 @@
"cheerio/undici": ["undici@7.22.0", "", {}, "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg=="],
"cliui/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"cosmiconfig/env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
"cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
@@ -2027,10 +2058,14 @@
"msw/tough-cookie": ["tough-cookie@6.0.0", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
"msw/yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
"ora/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
"ora/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
"prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
"proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
@@ -2059,7 +2094,7 @@
"stats-gl/three": ["three@0.170.0", "", {}, "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ=="],
"string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"string-width-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
@@ -2079,18 +2114,14 @@
"wrangler/unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],
"wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],
"wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"wrap-ansi/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"wrap-ansi/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"wrap-ansi-cjs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"wrap-ansi-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
"@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
@@ -2153,26 +2184,26 @@
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="],
"@inquirer/core/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"@inquirer/core/wrap-ansi/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"@inquirer/core/wrap-ansi/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"@isaacs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],
"@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@24.2.0", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
"@octokit/plugin-rest-endpoint-methods/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@24.2.0", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
"cliui/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"msw/tough-cookie/tldts": ["tldts@7.0.23", "", { "dependencies": { "tldts-core": "^7.0.23" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-ASdhgQIBSay0R/eXggAkQ53G4nTJqTXqC2kbaBbdDwM7SkjyZyO0OaaN1/FH7U/yCeqOHDwFO5j8+Os/IS1dXw=="],
"msw/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"msw/yargs/y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"msw/yargs/yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"ora/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
"shadcn/open/wsl-utils": ["wsl-utils@0.3.1", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="],
"tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.3", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="],
@@ -2331,20 +2362,16 @@
"wrangler/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.3", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],
"wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"wrap-ansi/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@inquirer/core/wrap-ansi/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"msw/tough-cookie/tldts/tldts-core": ["tldts-core@7.0.23", "", {}, "sha512-0g9vrtDQLrNIiCj22HSe9d4mLVG3g5ph5DZ8zCKBr4OtrspmNB6ss7hVyzArAeE88ceZocIEGkyW1Ime7fxPtQ=="],
"msw/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"msw/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"msw/yargs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
}
}

View File

@@ -1,4 +1,5 @@
import { auth } from "@kk/auth";
import { env } from "@kk/env/server";
export async function createContext({ req }: { req: Request }) {
const session = await auth.api.getSession({
@@ -6,6 +7,7 @@ export async function createContext({ req }: { req: Request }) {
});
return {
session,
env,
};
}

View File

@@ -13,6 +13,7 @@ const requireAuth = o.middleware(async ({ context, next }) => {
return next({
context: {
session: context.session,
env: context.env,
},
});
});
@@ -29,6 +30,7 @@ const requireAdmin = o.middleware(async ({ context, next }) => {
return next({
context: {
session: context.session,
env: context.env,
},
});
});

View File

@@ -0,0 +1,159 @@
import { env } from "@kk/env/server";
import nodemailer from "nodemailer";
// Re-use the same SMTP transport strategy as email.ts.
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;
}
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",
currency: "EUR",
}).format(cents / 100);
}
function deductionHtml(params: {
firstName: string;
amountCents: number;
newBalanceCents: number;
dateTime: string;
drinkkaartUrl: string;
}) {
return `<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Drinkkaart afschrijving</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;">Drinkkaart afschrijving</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 24px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
Er is zojuist een bedrag afgeschreven van je Drinkkaart.
</p>
<!-- Summary -->
<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:0 0 24px;">
<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;">Afschrijving</p>
<p style="margin:0 0 8px;font-size:22px;color:#ffffff;font-weight:700;">&minus; ${formatEuro(params.amountCents)}</p>
<p style="margin:8px 0 0;font-size:14px;color:rgba(255,255,255,0.55);">${params.dateTime}</p>
</td>
</tr>
<tr>
<td style="padding:0 24px 20px;border-top:1px solid rgba(255,255,255,0.08);">
<p style="margin:12px 0 4px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Nieuw saldo</p>
<p style="margin:0;font-size:20px;color:#ffffff;font-weight:600;">${formatEuro(params.newBalanceCents)}</p>
</td>
</tr>
</table>
<!-- CTA -->
<table cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius:2px;background:#ffffff;">
<a href="${params.drinkkaartUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
Bekijk mijn Drinkkaart
</a>
</td>
</tr>
</table>
<p style="margin:16px 0 0;font-size:13px;color:rgba(255,255,255,0.4);">
Klopt er iets niet? Neem contact op via <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a>.
</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;">
Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
}
/**
* Send a deduction notification email to the cardholder.
* Fire-and-forget: errors are logged but not re-thrown.
*/
export async function sendDeductionEmail(params: {
to: string;
firstName: string;
amountCents: number;
newBalanceCents: number;
}): Promise<void> {
const transport = getTransport();
if (!transport) {
console.warn("SMTP not configured — skipping deduction email");
return;
}
const now = new Date();
const dateTime = now.toLocaleString("nl-BE", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
const amountFormatted = new Intl.NumberFormat("nl-BE", {
style: "currency",
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`,
}),
});
}

View File

@@ -0,0 +1,120 @@
// QR token utilities for Drinkkaart using Web Crypto API
// Compatible with Cloudflare Workers (no node:crypto dependency).
const QR_TOKEN_TTL_MS = 5 * 60 * 1000; // 5 minutes
interface QrPayload {
drinkkaartId: string;
userId: string;
iat: number;
exp: number;
}
function toBase64Url(buffer: ArrayBuffer): string {
return btoa(String.fromCharCode(...new Uint8Array(buffer)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
}
function base64UrlToBuffer(str: string): Uint8Array<ArrayBuffer> {
const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
// Ensure the underlying buffer is a plain ArrayBuffer (required by crypto.subtle)
return new Uint8Array(bytes.buffer.slice(0));
}
/** Generate a cryptographically secure 32-byte hex secret for a new Drinkkaart. */
export function generateQrSecret(): string {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
/**
* Sign a QR token for the given drinkkaart / user.
* Returns the compact token string and the expiry date.
*/
export async function signQrToken(
payload: Omit<QrPayload, "iat" | "exp">,
qrSecret: string,
authSecret: string,
): Promise<{ token: string; expiresAt: Date }> {
const now = Date.now();
const exp = now + QR_TOKEN_TTL_MS;
const full: QrPayload = { ...payload, iat: now, exp };
const encodedPayload = btoa(JSON.stringify(full))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
const keyData = new TextEncoder().encode(qrSecret + authSecret);
const key = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const sigBuffer = await crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(encodedPayload),
);
const sig = toBase64Url(sigBuffer);
return { token: `${encodedPayload}.${sig}`, expiresAt: new Date(exp) };
}
/**
* Verify a QR token. Throws if the signature is invalid or the token is expired.
* Returns the decoded payload.
*/
export async function verifyQrToken(
token: string,
qrSecret: string,
authSecret: string,
): Promise<QrPayload> {
const parts = token.split(".");
if (parts.length !== 2) throw new Error("MALFORMED");
const [encodedPayload, providedSig] = parts as [string, string];
const keyData = new TextEncoder().encode(qrSecret + authSecret);
const key = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"],
);
const sigBytes = base64UrlToBuffer(providedSig);
const valid = await crypto.subtle.verify(
"HMAC",
key,
sigBytes,
new TextEncoder().encode(encodedPayload),
);
if (!valid) throw new Error("INVALID_SIGNATURE");
const payload: QrPayload = JSON.parse(
atob(encodedPayload.replace(/-/g, "+").replace(/_/g, "/")),
);
if (Date.now() > payload.exp) throw new Error("EXPIRED");
return payload;
}
/** 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

@@ -0,0 +1,742 @@
import { randomUUID } from "node:crypto";
import { db } from "@kk/db";
import {
drinkkaart,
drinkkaartTopup,
drinkkaartTransaction,
} from "@kk/db/schema";
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 { adminProcedure, protectedProcedure } from "../index";
import { sendDeductionEmail } from "../lib/drinkkaart-email";
import {
formatCents,
generateQrSecret,
signQrToken,
verifyQrToken,
} from "../lib/drinkkaart-utils";
// ---------------------------------------------------------------------------
// Internal helper: get or create the drinkkaart row for a user
// ---------------------------------------------------------------------------
async function getOrCreateDrinkkaart(userId: string) {
const rows = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.userId, userId))
.limit(1);
if (rows[0]) return rows[0];
const now = new Date();
const newCard = {
id: randomUUID(),
userId,
balance: 0,
version: 0,
qrSecret: generateQrSecret(),
createdAt: now,
updatedAt: now,
};
await db.insert(drinkkaart).values(newCard);
return newCard;
}
// ---------------------------------------------------------------------------
// Router procedures
// ---------------------------------------------------------------------------
export const drinkkaartRouter = {
// -------------------------------------------------------------------------
// 4.1 getMyDrinkkaart
// -------------------------------------------------------------------------
getMyDrinkkaart: protectedProcedure.handler(async ({ context }) => {
const userId = context.session.user.id;
const card = await getOrCreateDrinkkaart(userId);
const [topups, transactions] = await Promise.all([
db
.select()
.from(drinkkaartTopup)
.where(eq(drinkkaartTopup.drinkkaartId, card.id))
.orderBy(desc(drinkkaartTopup.paidAt))
.limit(50),
db
.select()
.from(drinkkaartTransaction)
.where(eq(drinkkaartTransaction.drinkkaartId, card.id))
.orderBy(desc(drinkkaartTransaction.createdAt))
.limit(50),
]);
return {
id: card.id,
balance: card.balance,
balanceFormatted: formatCents(card.balance),
createdAt: card.createdAt,
updatedAt: card.updatedAt,
topups: topups.map((t) => ({
id: t.id,
type: t.type,
amountCents: t.amountCents,
balanceBefore: t.balanceBefore,
balanceAfter: t.balanceAfter,
reason: t.reason,
paidAt: t.paidAt,
})),
transactions: transactions.map((t) => ({
id: t.id,
type: t.type,
amountCents: t.amountCents,
balanceBefore: t.balanceBefore,
balanceAfter: t.balanceAfter,
note: t.note,
reversedBy: t.reversedBy,
reverses: t.reverses,
createdAt: t.createdAt,
})),
};
}),
// -------------------------------------------------------------------------
// 4.2 getMyQrToken
// -------------------------------------------------------------------------
getMyQrToken: protectedProcedure.handler(async ({ context }) => {
const userId = context.session.user.id;
const card = await getOrCreateDrinkkaart(userId);
const authSecret = context.env.BETTER_AUTH_SECRET;
const { token, expiresAt } = await signQrToken(
{ drinkkaartId: card.id, userId },
card.qrSecret,
authSecret,
);
return { token, expiresAt };
}),
// -------------------------------------------------------------------------
// 4.3 getTopUpCheckoutUrl
// -------------------------------------------------------------------------
getTopUpCheckoutUrl: protectedProcedure
.input(
z.object({
amountCents: z
.number()
.int()
.min(100, "Minimumbedrag is € 1,00")
.max(50000, "Maximumbedrag is € 500,00"),
}),
)
.handler(async ({ input, context }) => {
const { env: serverEnv, session } = context;
if (
!serverEnv.LEMON_SQUEEZY_API_KEY ||
!serverEnv.LEMON_SQUEEZY_STORE_ID ||
!serverEnv.LEMON_SQUEEZY_DRINKKAART_VARIANT_ID
) {
throw new ORPCError("INTERNAL_SERVER_ERROR", {
message: "Lemon Squeezy Drinkkaart variant 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: `Drinkkaart top-up — ${formatCents(input.amountCents)}`,
redirect_url: `${serverEnv.BETTER_AUTH_URL}/drinkkaart?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_DRINKKAART_VARIANT_ID,
},
},
},
},
}),
},
);
if (!response.ok) {
const errorData = await response.json();
console.error("Lemon Squeezy 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 } };
};
const checkoutUrl = data.data?.attributes?.url;
if (!checkoutUrl) {
throw new ORPCError("INTERNAL_SERVER_ERROR", {
message: "Geen checkout URL ontvangen",
});
}
return { checkoutUrl };
}),
// -------------------------------------------------------------------------
// 4.4 resolveQrToken (admin)
// -------------------------------------------------------------------------
resolveQrToken: adminProcedure
.input(z.object({ token: z.string().min(1) }))
.handler(async ({ input, context }) => {
let drinkkaartId: string;
let userId: string;
// Decode payload first to get the drinkkaartId for key lookup
const parts = input.token.split(".");
if (parts.length !== 2) {
throw new ORPCError("BAD_REQUEST", {
message: "Ongeldig QR-token formaat",
});
}
let rawPayload: { drinkkaartId: string; userId: string; exp: number };
try {
rawPayload = JSON.parse(
atob((parts[0] as string).replace(/-/g, "+").replace(/_/g, "/")),
);
drinkkaartId = rawPayload.drinkkaartId;
userId = rawPayload.userId;
} catch {
throw new ORPCError("BAD_REQUEST", { message: "Ongeldig QR-token" });
}
// Fetch the card to get the per-user secret
const card = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.id, drinkkaartId))
.limit(1)
.then((r) => r[0]);
if (!card) {
throw new ORPCError("NOT_FOUND", {
message: "Drinkkaart niet gevonden",
});
}
// Verify HMAC and expiry
try {
await verifyQrToken(
input.token,
card.qrSecret,
context.env.BETTER_AUTH_SECRET,
);
} catch (err: unknown) {
const msg = (err as Error).message;
if (msg === "EXPIRED") {
throw new ORPCError("GONE", { message: "QR-token is verlopen" });
}
throw new ORPCError("UNAUTHORIZED", { message: "Ongeldig QR-token" });
}
// Fetch user
const cardUser = await db
.select({ id: user.id, name: user.name, email: user.email })
.from(user)
.where(eq(user.id, userId))
.limit(1)
.then((r) => r[0]);
if (!cardUser) {
throw new ORPCError("NOT_FOUND", {
message: "Gebruiker niet gevonden",
});
}
return {
drinkkaartId: card.id,
userId: cardUser.id,
userName: cardUser.name,
userEmail: cardUser.email,
balance: card.balance,
balanceFormatted: formatCents(card.balance),
};
}),
// -------------------------------------------------------------------------
// 4.5 deductBalance (admin)
// -------------------------------------------------------------------------
deductBalance: adminProcedure
.input(
z.object({
drinkkaartId: z.string().min(1),
amountCents: z.number().int().min(1),
note: z.string().max(200).optional(),
}),
)
.handler(async ({ input, context }) => {
const adminId = context.session.user.id;
const card = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.id, input.drinkkaartId))
.limit(1)
.then((r) => r[0]);
if (!card) {
throw new ORPCError("NOT_FOUND", {
message: "Drinkkaart niet gevonden",
});
}
if (card.balance < input.amountCents) {
throw new ORPCError("UNPROCESSABLE_CONTENT", {
message: `Onvoldoende saldo. Huidig saldo: ${formatCents(card.balance)}`,
});
}
const balanceBefore = card.balance;
const balanceAfter = balanceBefore - input.amountCents;
const now = new Date();
// Optimistic lock update
const result = await db
.update(drinkkaart)
.set({
balance: balanceAfter,
version: card.version + 1,
updatedAt: now,
})
.where(
and(
eq(drinkkaart.id, input.drinkkaartId),
eq(drinkkaart.version, card.version),
),
);
if (result.rowsAffected === 0) {
throw new ORPCError("CONFLICT", {
message: "Gelijktijdige wijziging gedetecteerd. Probeer opnieuw.",
});
}
const transactionId = randomUUID();
await db.insert(drinkkaartTransaction).values({
id: transactionId,
drinkkaartId: card.id,
userId: card.userId,
adminId,
amountCents: input.amountCents,
balanceBefore,
balanceAfter,
type: "deduction",
note: input.note ?? null,
createdAt: now,
});
// Fire-and-forget deduction email
const cardUser = await db
.select({ email: user.email, name: user.name })
.from(user)
.where(eq(user.id, card.userId))
.limit(1)
.then((r) => r[0]);
if (cardUser) {
sendDeductionEmail({
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),
);
}
return {
transactionId,
balanceBefore,
balanceAfter,
balanceFormatted: formatCents(balanceAfter),
};
}),
// -------------------------------------------------------------------------
// 4.6 adminCreditBalance (admin)
// -------------------------------------------------------------------------
adminCreditBalance: adminProcedure
.input(
z.object({
drinkkaartId: z.string().min(1),
amountCents: z.number().int().min(1),
reason: z.string().min(1).max(200),
}),
)
.handler(async ({ input, context }) => {
const adminId = context.session.user.id;
const card = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.id, input.drinkkaartId))
.limit(1)
.then((r) => r[0]);
if (!card) {
throw new ORPCError("NOT_FOUND", {
message: "Drinkkaart niet gevonden",
});
}
const balanceBefore = card.balance;
const balanceAfter = balanceBefore + input.amountCents;
const now = new Date();
const result = await db
.update(drinkkaart)
.set({
balance: balanceAfter,
version: card.version + 1,
updatedAt: now,
})
.where(
and(
eq(drinkkaart.id, input.drinkkaartId),
eq(drinkkaart.version, card.version),
),
);
if (result.rowsAffected === 0) {
throw new ORPCError("CONFLICT", {
message: "Gelijktijdige wijziging gedetecteerd. Probeer opnieuw.",
});
}
const topupId = randomUUID();
await db.insert(drinkkaartTopup).values({
id: topupId,
drinkkaartId: card.id,
userId: card.userId,
amountCents: input.amountCents,
balanceBefore,
balanceAfter,
type: "admin_credit",
adminId,
reason: input.reason,
paidAt: now,
});
return {
topupId,
balanceBefore,
balanceAfter,
balanceFormatted: formatCents(balanceAfter),
};
}),
// -------------------------------------------------------------------------
// 4.7 reverseTransaction (admin)
// -------------------------------------------------------------------------
reverseTransaction: adminProcedure
.input(
z.object({
transactionId: z.string().min(1),
note: z.string().max(200).optional(),
}),
)
.handler(async ({ input, context }) => {
const adminId = context.session.user.id;
const original = await db
.select()
.from(drinkkaartTransaction)
.where(eq(drinkkaartTransaction.id, input.transactionId))
.limit(1)
.then((r) => r[0]);
if (!original) {
throw new ORPCError("NOT_FOUND", {
message: "Transactie niet gevonden",
});
}
if (original.type !== "deduction") {
throw new ORPCError("BAD_REQUEST", {
message: "Alleen afschrijvingen kunnen worden teruggedraaid",
});
}
if (original.reversedBy) {
throw new ORPCError("CONFLICT", {
message: "Deze transactie is al teruggedraaid",
});
}
const card = await db
.select()
.from(drinkkaart)
.where(eq(drinkkaart.id, original.drinkkaartId))
.limit(1)
.then((r) => r[0]);
if (!card) {
throw new ORPCError("NOT_FOUND", {
message: "Drinkkaart niet gevonden",
});
}
const balanceBefore = card.balance;
const balanceAfter = balanceBefore + original.amountCents;
const now = new Date();
const result = await db
.update(drinkkaart)
.set({
balance: balanceAfter,
version: card.version + 1,
updatedAt: now,
})
.where(
and(eq(drinkkaart.id, card.id), eq(drinkkaart.version, card.version)),
);
if (result.rowsAffected === 0) {
throw new ORPCError("CONFLICT", {
message: "Gelijktijdige wijziging gedetecteerd. Probeer opnieuw.",
});
}
const reversalId = randomUUID();
await db.insert(drinkkaartTransaction).values({
id: reversalId,
drinkkaartId: card.id,
userId: card.userId,
adminId,
amountCents: original.amountCents,
balanceBefore,
balanceAfter,
type: "reversal",
reverses: original.id,
note: input.note ?? null,
createdAt: now,
});
// Mark original as reversed
await db
.update(drinkkaartTransaction)
.set({ reversedBy: reversalId })
.where(eq(drinkkaartTransaction.id, original.id));
return {
reversalId,
balanceBefore,
balanceAfter,
balanceFormatted: formatCents(balanceAfter),
};
}),
// -------------------------------------------------------------------------
// 4.8 getTransactionLog (admin) — paginated audit log
// -------------------------------------------------------------------------
getTransactionLog: adminProcedure
.input(
z.object({
page: z.number().int().min(1).default(1),
pageSize: z.number().int().min(1).max(200).default(50),
userId: z.string().optional(),
adminId: z.string().optional(),
type: z.enum(["deduction", "reversal"]).optional(),
dateFrom: z.string().optional(),
dateTo: z.string().optional(),
}),
)
.handler(async ({ input }) => {
// Build conditions
const conditions = [];
if (input.userId) {
conditions.push(eq(drinkkaartTransaction.userId, input.userId));
}
if (input.adminId) {
conditions.push(eq(drinkkaartTransaction.adminId, input.adminId));
}
if (input.type) {
conditions.push(eq(drinkkaartTransaction.type, input.type));
}
if (input.dateFrom) {
conditions.push(
gte(drinkkaartTransaction.createdAt, new Date(input.dateFrom)),
);
}
if (input.dateTo) {
conditions.push(
lte(drinkkaartTransaction.createdAt, new Date(input.dateTo)),
);
}
const where = conditions.length > 0 ? and(...conditions) : undefined;
// Paginated results with user names
const offset = (input.page - 1) * input.pageSize;
const rows = await db
.select({
id: drinkkaartTransaction.id,
type: drinkkaartTransaction.type,
userId: drinkkaartTransaction.userId,
adminId: drinkkaartTransaction.adminId,
amountCents: drinkkaartTransaction.amountCents,
balanceBefore: drinkkaartTransaction.balanceBefore,
balanceAfter: drinkkaartTransaction.balanceAfter,
note: drinkkaartTransaction.note,
reversedBy: drinkkaartTransaction.reversedBy,
reverses: drinkkaartTransaction.reverses,
createdAt: drinkkaartTransaction.createdAt,
})
.from(drinkkaartTransaction)
.where(where)
.orderBy(desc(drinkkaartTransaction.createdAt))
.limit(input.pageSize)
.offset(offset);
// Collect unique user IDs
const userIds = [
...new Set([
...rows.map((r) => r.userId),
...rows.map((r) => r.adminId),
]),
];
const users =
userIds.length > 0
? await db
.select({ id: user.id, name: user.name, email: user.email })
.from(user)
.where(
userIds.length === 1
? eq(user.id, userIds[0] as string)
: sql`${user.id} IN (${sql.join(
userIds.map((id) => sql`${id}`),
sql`, `,
)})`,
)
: [];
const userMap = new Map(users.map((u) => [u.id, u]));
// Count total
const countResult = await db
.select({ count: sql<number>`count(*)` })
.from(drinkkaartTransaction)
.where(where);
const total = Number(countResult[0]?.count ?? 0);
return {
transactions: rows.map((r) => ({
id: r.id,
type: r.type,
userId: r.userId,
userName: userMap.get(r.userId)?.name ?? "Onbekend",
userEmail: userMap.get(r.userId)?.email ?? "",
adminId: r.adminId,
adminName: userMap.get(r.adminId)?.name ?? "Onbekend",
amountCents: r.amountCents,
balanceBefore: r.balanceBefore,
balanceAfter: r.balanceAfter,
note: r.note,
reversedBy: r.reversedBy,
reverses: r.reverses,
createdAt: r.createdAt,
})),
total,
page: input.page,
pageSize: input.pageSize,
};
}),
// -------------------------------------------------------------------------
// Extra: getDrinkkaartByUserId (admin) — for manual credit user search
// -------------------------------------------------------------------------
getDrinkkaartByUserId: adminProcedure
.input(z.object({ userId: z.string().min(1) }))
.handler(async ({ input }) => {
const cardUser = await db
.select({ id: user.id, name: user.name, email: user.email })
.from(user)
.where(eq(user.id, input.userId))
.limit(1)
.then((r) => r[0]);
if (!cardUser) {
throw new ORPCError("NOT_FOUND", {
message: "Gebruiker niet gevonden",
});
}
const card = await getOrCreateDrinkkaart(input.userId);
return {
drinkkaartId: card.id,
userId: cardUser.id,
userName: cardUser.name,
userEmail: cardUser.email,
balance: card.balance,
balanceFormatted: formatCents(card.balance),
};
}),
// -------------------------------------------------------------------------
// Extra: searchUsers (admin) — for manual credit user search UI
// -------------------------------------------------------------------------
searchUsers: adminProcedure
.input(z.object({ query: z.string().min(1) }))
.handler(async ({ input }) => {
const term = `%${input.query}%`;
const results = await db
.select({ id: user.id, name: user.name, email: user.email })
.from(user)
.where(
sql`lower(${user.name}) LIKE lower(${term}) OR lower(${user.email}) LIKE lower(${term})`,
)
.limit(20);
return results;
}),
};

View File

@@ -12,6 +12,7 @@ import {
sendUpdateEmail,
} from "../email";
import { adminProcedure, protectedProcedure, publicProcedure } from "../index";
import { drinkkaartRouter } from "./drinkkaart";
// ---------------------------------------------------------------------------
// Shared helpers
@@ -110,6 +111,7 @@ const getRegistrationsSchema = z.object({
export const appRouter = {
healthCheck: publicProcedure.handler(() => "OK"),
drinkkaart: drinkkaartRouter,
privateData: protectedProcedure.handler(({ context }) => ({
message: "This is private",

View File

@@ -12,7 +12,11 @@ export const auth = betterAuth({
schema: schema,
}),
trustedOrigins: [env.CORS_ORIGIN],
trustedOrigins: [
env.CORS_ORIGIN,
"http://localhost:3000",
"http://localhost:3001",
],
emailAndPassword: {
enabled: true,
// Use Cloudflare's native scrypt via node:crypto for better performance

View File

@@ -0,0 +1,56 @@
-- Migration: Add Drinkkaart digital balance card tables
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,
UNIQUE(`user_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 `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,
`lemonsqueezy_order_id` text,
`lemonsqueezy_customer_id` text,
`admin_id` text,
`reason` text,
`paid_at` integer NOT NULL,
UNIQUE(`lemonsqueezy_order_id`)
);
--> statement-breakpoint
CREATE INDEX `idx_drinkkaart_user_id` ON `drinkkaart` (`user_id`);
--> statement-breakpoint
CREATE INDEX `idx_dkt_drinkkaart_id` ON `drinkkaart_transaction` (`drinkkaart_id`);
--> statement-breakpoint
CREATE INDEX `idx_dkt_user_id` ON `drinkkaart_transaction` (`user_id`);
--> statement-breakpoint
CREATE INDEX `idx_dkt_admin_id` ON `drinkkaart_transaction` (`admin_id`);
--> statement-breakpoint
CREATE INDEX `idx_dkt_created_at` ON `drinkkaart_transaction` (`created_at`);
--> statement-breakpoint
CREATE INDEX `idx_dktu_drinkkaart_id` ON `drinkkaart_topup` (`drinkkaart_id`);
--> statement-breakpoint
CREATE INDEX `idx_dktu_user_id` ON `drinkkaart_topup` (`user_id`);

View File

@@ -22,6 +22,13 @@
"when": 1772520000000,
"tag": "0002_registration_type_redesign",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1772530000000,
"tag": "0003_add_guests",
"breakpoints": true
}
]
}

View File

@@ -0,0 +1,69 @@
import type { InferInsertModel, InferSelectModel } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
// ---------------------------------------------------------------------------
// drinkkaart — one row per user account (1:1 with user)
// ---------------------------------------------------------------------------
export const drinkkaart = sqliteTable("drinkkaart", {
id: text("id").primaryKey(),
userId: text("user_id").notNull().unique(),
balance: integer("balance").notNull().default(0), // in cents
version: integer("version").notNull().default(0), // optimistic lock counter
qrSecret: text("qr_secret").notNull(), // CSPRNG 32-byte hex; signs QR tokens
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
});
// ---------------------------------------------------------------------------
// drinkkaart_transaction — immutable audit log of deductions and reversals
// ---------------------------------------------------------------------------
export const drinkkaartTransaction = sqliteTable("drinkkaart_transaction", {
id: text("id").primaryKey(),
drinkkaartId: text("drinkkaart_id").notNull(),
userId: text("user_id").notNull(), // denormalized for fast audit queries
adminId: text("admin_id").notNull(), // FK → user.id (admin who processed it)
amountCents: integer("amount_cents").notNull(),
balanceBefore: integer("balance_before").notNull(),
balanceAfter: integer("balance_after").notNull(),
type: text("type", { enum: ["deduction", "reversal"] }).notNull(),
reversedBy: text("reversed_by"), // nullable; id of the reversal transaction
reverses: text("reverses"), // nullable; id of the original deduction
note: text("note"),
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
});
// ---------------------------------------------------------------------------
// drinkkaart_topup — immutable log of every credited amount
// ---------------------------------------------------------------------------
export const drinkkaartTopup = sqliteTable("drinkkaart_topup", {
id: text("id").primaryKey(),
drinkkaartId: text("drinkkaart_id").notNull(),
userId: text("user_id").notNull(), // denormalized
amountCents: integer("amount_cents").notNull(),
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"
lemonsqueezyCustomerId: text("lemonsqueezy_customer_id"),
adminId: text("admin_id"), // nullable; only for type="admin_credit"
reason: text("reason"),
paidAt: integer("paid_at", { mode: "timestamp_ms" }).notNull(),
});
// ---------------------------------------------------------------------------
// Inferred Drizzle types
// ---------------------------------------------------------------------------
export type Drinkkaart = InferSelectModel<typeof drinkkaart>;
export type NewDrinkkaart = InferInsertModel<typeof drinkkaart>;
export type DrinkkaartTransaction = InferSelectModel<
typeof drinkkaartTransaction
>;
export type NewDrinkkaartTransaction = InferInsertModel<
typeof drinkkaartTransaction
>;
export type DrinkkaartTopup = InferSelectModel<typeof drinkkaartTopup>;
export type NewDrinkkaartTopup = InferInsertModel<typeof drinkkaartTopup>;

View File

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

View File

@@ -28,6 +28,7 @@ export const env = createEnv({
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_DRINKKAART_VARIANT_ID: z.string().min(1).optional(),
LEMON_SQUEEZY_WEBHOOK_SECRET: z.string().min(1).optional(),
},
runtimeEnv: process.env,