Add calendar export, SEO, error monitoring, backups, audit trail, and a starter test suite

Six site improvements picked from a "what could be better" review, plus a Jest
test suite covering the two areas with the trickiest money-handling history
in this project (early-bird pricing tranches, donation-leg accounting):

- "Add to calendar" .ics download on event pages and in confirmation emails
- sitemap.xml, robots.txt, and Open Graph/Twitter metadata for public pages
- Sentry error monitoring (backend + frontend), a no-op until SENTRY_DSN is set
- Nightly local pg_dump backups with a Site Settings tab to browse/trigger/download
- Admin audit trail for refunds, donations, manual registrations, event and
  settings changes, and staff-initiated cancellations
- Jest tests reproducing and guarding against the 1.8.0 tranche-pricing bug
  and the 1.4.2 donation-balance-inflation bug

Wallet passes (Google/Apple) were scoped out of this round — Apple Wallet
needs a paid Apple Developer account the project doesn't have yet, and the
user preferred shipping both together later rather than Google alone now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-27 14:50:11 +02:00
co-authored by Claude Sonnet 5
parent 98ac26bf70
commit 54b89d4f4b
43 changed files with 8414 additions and 92 deletions
+6 -1
View File
@@ -1,4 +1,5 @@
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
const nextConfig: NextConfig = {
images: {
@@ -12,4 +13,8 @@ const nextConfig: NextConfig = {
},
};
export default nextConfig;
// A no-op wrap when SENTRY_DSN isn't configured for this deployment — safe in
// every environment (dev, or a fresh deploy that hasn't set up Sentry yet).
export default process.env.NEXT_PUBLIC_SENTRY_DSN
? withSentryConfig(nextConfig, { silent: true, disableLogger: true })
: nextConfig;
+2456 -63
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -27,6 +27,7 @@
"@radix-ui/react-tabs": "^1.1.12",
"@radix-ui/react-toast": "^1.2.14",
"@radix-ui/react-tooltip": "^1.2.7",
"@sentry/nextjs": "^10.71.0",
"@zxing/browser": "^0.1.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -0,0 +1,218 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { History } from "lucide-react";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
const ACTIONS = [
"refund_created",
"donation_assigned",
"donation_unassigned",
"registration_created_manual",
"registration_cancelled",
"event_created",
"event_updated",
"event_deleted",
"settings_updated",
] as const;
const ACTION_LABELS: Record<string, string> = {
refund_created: "Refund created",
donation_assigned: "Donation assigned",
donation_unassigned: "Donation unassigned",
registration_created_manual: "Manual registration created",
registration_cancelled: "Registration cancelled (staff)",
event_created: "Event created",
event_updated: "Event updated",
event_deleted: "Event deactivated",
settings_updated: "Settings updated",
};
interface AuditLogEntry {
id: string;
actorId: string | null;
actorRole: string;
action: string;
targetType: string;
targetId: string | null;
metadata: Record<string, unknown> | null;
ip: string | null;
createdAt: string;
actor: { id: string; name: string; email: string } | null;
}
function formatMetadata(metadata: Record<string, unknown> | null): string {
if (!metadata) return "";
try {
return Object.entries(metadata)
.filter(([, v]) => v !== null && v !== undefined && v !== "")
.map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`)
.join(" · ");
} catch {
return "";
}
}
export default function AdminAuditLogPage() {
const { user, loading, token } = useAuth();
const router = useRouter();
const isAdmin = useMemo(() => user?.role === "admin", [user]);
useEffect(() => {
if (loading) return;
if (!user) router.replace("/login");
}, [user, loading, router]);
const [entries, setEntries] = useState<AuditLogEntry[]>([]);
const [fetching, setFetching] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const pageSize = 50;
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const [actionFilter, setActionFilter] = useState<string>("");
const [fromFilter, setFromFilter] = useState<string>("");
const [toFilter, setToFilter] = useState<string>("");
const buildQuery = useCallback((p: number) => {
const qs = new URLSearchParams({ page: String(p), limit: String(pageSize) });
if (actionFilter) qs.set("action", actionFilter);
if (fromFilter) qs.set("from", fromFilter);
if (toFilter) qs.set("to", toFilter);
return `/api/admin/audit-log?${qs.toString()}`;
}, [actionFilter, fromFilter, toFilter]);
const load = useCallback(async (p = 1) => {
if (!token) return;
setError(null);
setFetching(true);
try {
const res = await apiFetch<{ rows: AuditLogEntry[]; total: number; page: number }>(buildQuery(p), { authToken: token });
setEntries(res?.rows || []);
setTotal(res?.total ?? 0);
setPage(p);
} catch (e: any) {
setError(e?.message || "Failed to load audit log");
} finally {
setFetching(false);
}
}, [token, buildQuery]);
useEffect(() => { if (token) load(1); }, [token, actionFilter, fromFilter, toFilter]);
return (
<div className="max-w-6xl mx-auto w-full p-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
<History className="w-5 h-5 text-brand-600" />
</div>
<div>
<h1 className="text-2xl font-semibold text-gray-900">Admin Audit Log</h1>
<p className="text-sm text-gray-500">{total} action{total !== 1 ? "s" : ""} recorded</p>
</div>
</div>
{!isAdmin && (
<div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">
You need admin access to view the audit log.
</div>
)}
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="flex flex-wrap items-end gap-3 mb-4">
<div>
<label className="block text-xs text-gray-600 mb-1">Action</label>
<select className="border rounded px-2 py-1.5 text-sm" value={actionFilter} onChange={e => setActionFilter(e.target.value)}>
<option value="">All actions</option>
{ACTIONS.map(a => <option key={a} value={a}>{ACTION_LABELS[a]}</option>)}
</select>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">From</label>
<input type="date" className="border rounded px-2 py-1.5 text-sm" value={fromFilter} onChange={e => setFromFilter(e.target.value)} />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">To</label>
<input type="date" className="border rounded px-2 py-1.5 text-sm" value={toFilter} onChange={e => setToFilter(e.target.value)} />
</div>
<button className="text-sm px-2 py-1.5 rounded bg-gray-100 hover:bg-gray-200" onClick={() => load(page)} disabled={fetching}>
{fetching ? "Refreshing…" : "Refresh"}
</button>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
<TableHead>Actor</TableHead>
<TableHead>Action</TableHead>
<TableHead>Target</TableHead>
<TableHead>Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{entries.map(e => (
<TableRow key={e.id}>
<TableCell className="whitespace-nowrap text-gray-600">{new Date(e.createdAt).toLocaleString()}</TableCell>
<TableCell>
{e.actor ? (
<>
<div className="font-medium">{e.actor.name}</div>
<div className="text-xs text-gray-500">{e.actor.email}</div>
</>
) : (
<span className="text-gray-400 italic">Deleted user</span>
)}
<div className="text-xs text-gray-400 capitalize">{e.actorRole}</div>
</TableCell>
<TableCell>{ACTION_LABELS[e.action] || e.action}</TableCell>
<TableCell className="text-xs text-gray-600">{e.targetType}{e.targetId ? ` #${e.targetId.slice(0, 8)}` : ""}</TableCell>
<TableCell className="text-xs text-gray-500 max-w-[280px] truncate" title={formatMetadata(e.metadata)}>{formatMetadata(e.metadata)}</TableCell>
</TableRow>
))}
{entries.length === 0 && !fetching && (
<TableRow>
<TableCell colSpan={5} className="text-gray-500">No matching audit entries.</TableCell>
</TableRow>
)}
{fetching && (
<TableRow>
<TableCell colSpan={5} className="text-gray-400">Loading</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4 text-sm">
<span className="text-gray-500">Page {page} of {totalPages}</span>
<div className="flex gap-1">
<button
className="px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 disabled:opacity-40"
disabled={page <= 1 || fetching}
onClick={() => load(page - 1)}
>
Prev
</button>
<button
className="px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 disabled:opacity-40"
disabled={page >= totalPages || fetching}
onClick={() => load(page + 1)}
>
Next
</button>
</div>
</div>
)}
</div>
</div>
);
}
+2 -1
View File
@@ -8,7 +8,7 @@ import { useStableState } from "@/hooks/useStableState";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -33,6 +33,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/email-attendees", label: "Email attendees", description: "Send a message to attendees of an event", icon: Mail },
{ href: "/dashboard/supervisor/whatsapp-attendees", label: "WhatsApp attendees", description: "Send a WhatsApp message to event attendees", icon: MessageCircle },
{ href: "/dashboard/admin/cashup", label: "Post-event Cashup", description: "Set costs, reconcile takings, and close out events", icon: Wallet },
{ href: "/dashboard/admin/audit-log", label: "Audit log", description: "Review refunds, manual registrations, event and settings changes", icon: History },
] as const;
type OverviewMetric = { thisMonth: number; lastMonth: number; pctChange: number | null };
@@ -6,13 +6,14 @@ import { useRouter, useSearchParams } from "next/navigation";
import { apiFetch, API_BASE, resolveToApiOrigin } from "@/lib/api";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, type LucideIcon } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, DatabaseBackup, type LucideIcon } from "lucide-react";
import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp";
type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "backups";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -21,6 +22,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "email", label: "Email", icon: Mail },
{ id: "legal", label: "Legal", icon: Scale },
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
{ id: "backups", label: "Backups", icon: DatabaseBackup },
];
const inputCls =
@@ -662,6 +664,9 @@ function SiteSettingsPageInner() {
{/* ── WhatsApp ──────────────────────────────────────────────────────── */}
{activeTab === "whatsapp" && <WhatsAppTab active={activeTab === "whatsapp"} />}
{/* ── Backups ───────────────────────────────────────────────────────── */}
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
</div>
{activeTab === "branding" && (
+10 -1
View File
@@ -1,7 +1,8 @@
"use client";
import { Share2, QrCode } from "lucide-react";
import { Share2, QrCode, CalendarPlus } from "lucide-react";
import QRCode from "qrcode";
import { API_BASE } from "@/lib/api";
export default function ClientActions({ event }: { event: any }) {
return (
@@ -43,6 +44,14 @@ export default function ClientActions({ event }: { event: any }) {
<QrCode className="w-4 h-4" />
Save QR
</button>
<a
href={`${API_BASE}/api/events/${event.id}/ics`}
download
className="flex items-center gap-2 px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors text-sm font-medium"
>
<CalendarPlus className="w-4 h-4" />
Add to calendar
</a>
</div>
);
}
+41 -8
View File
@@ -1,3 +1,4 @@
import { Metadata } from "next";
import { notFound } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
@@ -41,7 +42,7 @@ type Event = {
location?: string | null;
};
import { apiFetch, ApiError } from "@/lib/api";
import { apiFetch, ApiError, resolveToApiOrigin } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { formatDateTimeRange } from "@/lib/date";
@@ -105,17 +106,49 @@ function RegisterCta({ event }: { event: Event }) {
);
}
export default async function EventDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
let event: Event;
// Next dedupes an identical fetch (same URL + cache options) made during the same
// request, so calling this again from the page component below is free.
async function loadEvent(id: string): Promise<Event | null> {
try {
event = await apiFetch<Event>(`/api/events/${id}`, { nextOptions: { next: { revalidate } } });
return await apiFetch<Event>(`/api/events/${id}`, { nextOptions: { next: { revalidate } } });
} catch (e) {
// The event endpoint 404s for missing, inactive, or not-yet-live events —
// render the standard not-found page instead of crashing.
if (e instanceof ApiError && e.status === 404) notFound();
if (e instanceof ApiError && e.status === 404) return null;
throw e;
}
}
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
const { id } = await params;
const event = await loadEvent(id);
if (!event) return {};
const description = event.description
? event.description.slice(0, 200)
: `${event.title}${formatDateTimeRange(event.startDate, event.endDate)}`;
const imageUrl = event.picture ? resolveToApiOrigin(event.picture) : null;
return {
title: event.title,
description,
openGraph: {
title: event.title,
description,
type: "website",
...(imageUrl ? { images: [{ url: imageUrl }] } : {}),
},
twitter: {
card: "summary_large_image",
title: event.title,
description,
...(imageUrl ? { images: [imageUrl] } : {}),
},
};
}
export default async function EventDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const event = await loadEvent(id);
if (!event) notFound();
return (
<div className="min-h-screen flex flex-col">
+6
View File
@@ -1,3 +1,4 @@
import { Metadata } from "next";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { EventCard } from "@/components/events/EventCard";
@@ -6,6 +7,11 @@ import { Calendar, CalendarX } from "lucide-react";
export const revalidate = 60;
export const metadata: Metadata = {
title: "All Events",
description: "Browse and register for upcoming events.",
};
type Event = {
id: string;
title: string;
+19 -2
View File
@@ -10,6 +10,7 @@ import { SetupGuard } from "@/components/shared/SetupGuard";
import HelpFab from "@/components/shared/HelpFab";
import { API_BASE, resolveToApiOrigin } from "@/lib/api";
import { buildThemeCssVars } from "@/lib/colorScale";
import { appUrl } from "@/lib/siteConfig";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -44,14 +45,30 @@ async function getServerSettings(): Promise<SiteSettings> {
export async function generateMetadata(): Promise<Metadata> {
const settings = await getServerSettings();
const faviconUrl = settings.favicon_url ? resolveToApiOrigin(settings.favicon_url) : null;
const logoUrl = settings.logo_url ? resolveToApiOrigin(settings.logo_url) : null;
const displayName = settings.org_name || appName;
const description = settings.org_tagline || `Manage and register for events with ${displayName}`;
return {
title: displayName,
description: `Manage and register for events with ${displayName}`,
metadataBase: new URL(appUrl),
title: { default: displayName, template: `%s | ${displayName}` },
description,
icons: {
icon: faviconUrl || "/favicon.ico",
},
openGraph: {
type: "website",
siteName: displayName,
title: { default: displayName, template: `%s | ${displayName}` },
description,
...(logoUrl ? { images: [{ url: logoUrl }] } : {}),
},
twitter: {
card: "summary_large_image",
title: displayName,
description,
...(logoUrl ? { images: [logoUrl] } : {}),
},
};
}
+15
View File
@@ -0,0 +1,15 @@
import type { MetadataRoute } from "next";
import { appUrl } from "@/lib/siteConfig";
export default function robots(): MetadataRoute.Robots {
const base = appUrl.replace(/\/$/, "");
return {
rules: {
userAgent: "*",
allow: "/",
disallow: ["/dashboard", "/self-service", "/set-banner", "/lockdown-rules"],
},
sitemap: `${base}/sitemap.xml`,
};
}
+34
View File
@@ -0,0 +1,34 @@
import type { MetadataRoute } from "next";
import { apiFetch } from "@/lib/api";
import { appUrl } from "@/lib/siteConfig";
type Event = { id: string; updatedAt?: string; startDate: string };
export const revalidate = 3600;
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const base = appUrl.replace(/\/$/, "");
const staticEntries: MetadataRoute.Sitemap = [
{ url: `${base}/`, changeFrequency: "daily", priority: 1 },
{ url: `${base}/events`, changeFrequency: "daily", priority: 0.9 },
{ url: `${base}/contact`, changeFrequency: "monthly", priority: 0.5 },
];
let events: Event[] = [];
try {
events = await apiFetch<Event[]>("/api/events", { nextOptions: { next: { revalidate } } });
} catch {
// Backend unreachable at build/revalidate time — ship the static entries only,
// same degrade-gracefully posture as layout.tsx's getServerSettings.
}
const eventEntries: MetadataRoute.Sitemap = (events || []).map((e) => ({
url: `${base}/events/${e.id}`,
lastModified: e.updatedAt ? new Date(e.updatedAt) : undefined,
changeFrequency: "weekly",
priority: 0.7,
}));
return [...staticEntries, ...eventEntries];
}
@@ -0,0 +1,188 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, API_BASE } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { DatabaseBackup, Download } from "lucide-react";
interface BackupEntry {
filename: string;
size: number;
createdAt: string;
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function BackupsTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [backups, setBackups] = useState<BackupEntry[]>([]);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState(false);
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const [retainCount, setRetainCount] = useState("14");
const [savingRetain, setSavingRetain] = useState(false);
const load = useCallback(async () => {
if (!token) return;
setLoading(true);
try {
const [list, allSettings] = await Promise.all([
apiFetch<BackupEntry[]>("/api/backups", { authToken: token }),
apiFetch<Record<string, string>>("/api/settings/all", { authToken: token }),
]);
setBackups(list || []);
setRetainCount(allSettings?.backup_retain_count || "14");
} catch (e: any) {
setMessage({ type: "err", text: e?.message || "Failed to load backups" });
} finally {
setLoading(false);
}
}, [token]);
const saveRetainCount = async () => {
if (!token) return;
setSavingRetain(true);
try {
await apiFetch("/api/settings", { method: "PUT", authToken: token, body: { backup_retain_count: retainCount } });
setMessage({ type: "ok", text: "Retention setting saved." });
} catch (e: any) {
setMessage({ type: "err", text: e?.message || "Failed to save retention setting" });
} finally {
setSavingRetain(false);
}
};
useEffect(() => { if (active) load(); }, [active, load]);
const runBackup = async () => {
if (!token) return;
setRunning(true);
setMessage(null);
try {
const res = await apiFetch<{ filename: string }>("/api/backups/run", { method: "POST", authToken: token });
setMessage({ type: "ok", text: `Backup created: ${res.filename}` });
await load();
} catch (e: any) {
setMessage({ type: "err", text: e?.message || "Backup failed" });
} finally {
setRunning(false);
}
};
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-lg bg-brand-50 flex items-center justify-center shrink-0">
<DatabaseBackup className="w-4 h-4 text-brand-600" />
</div>
<div>
<h2 className="text-lg font-semibold text-gray-900">Database backups</h2>
<p className="text-xs text-gray-500">Nightly automatic backups, stored locally on this server. Not uploaded anywhere else.</p>
</div>
</div>
{message && (
<div className={`text-sm p-2.5 rounded-lg ${message.type === "ok" ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"}`}>
{message.text}
</div>
)}
<button
type="button"
onClick={runBackup}
disabled={running}
className="px-4 py-2 bg-brand-600 hover:bg-brand-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
>
{running ? "Running…" : "Run backup now"}
</button>
<div className="flex items-end gap-2 pt-2 border-t">
<div>
<label className="block text-xs text-gray-600 mb-1">Keep the most recent</label>
<input
type="number"
min={1}
className="w-24 border rounded-lg px-3 py-1.5 text-sm"
value={retainCount}
onChange={(e) => setRetainCount(e.target.value)}
/>
</div>
<span className="text-sm text-gray-500 pb-1.5">backups, delete the rest</span>
<button
type="button"
onClick={saveRetainCount}
disabled={savingRetain}
className="ml-auto px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50"
>
{savingRetain ? "Saving…" : "Save"}
</button>
</div>
<div className="border rounded-lg overflow-hidden mt-2">
<table className="min-w-full text-sm">
<thead>
<tr className="text-left text-gray-600 border-b bg-gray-50">
<th className="p-2.5">Created</th>
<th className="p-2.5">Size</th>
<th className="p-2.5">Download</th>
</tr>
</thead>
<tbody>
{backups.map((b) => (
<tr key={b.filename} className="border-t">
<td className="p-2.5">{new Date(b.createdAt).toLocaleString()}</td>
<td className="p-2.5 text-gray-500">{formatSize(b.size)}</td>
<td className="p-2.5">
<a
href={`${API_BASE}/api/backups/${encodeURIComponent(b.filename)}/download`}
className="inline-flex items-center gap-1.5 text-brand-600 hover:underline"
onClick={(e) => {
// authenticated download: fetch as blob rather than a bare link,
// since this route requires an admin bearer token
e.preventDefault();
if (!token) return;
fetch(`${API_BASE}/api/backups/${encodeURIComponent(b.filename)}/download`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((res) => res.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = b.filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
})
.catch(() => setMessage({ type: "err", text: "Download failed" }));
}}
>
<Download className="w-3.5 h-3.5" />
Download
</a>
</td>
</tr>
))}
{backups.length === 0 && !loading && (
<tr>
<td className="p-3 text-gray-500" colSpan={3}>No backups yet.</td>
</tr>
)}
{loading && (
<tr>
<td className="p-3 text-gray-400" colSpan={3}>Loading</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
// A no-op when NEXT_PUBLIC_SENTRY_DSN isn't set, so this is safe in every environment
// (dev, or a fresh deploy that hasn't configured Sentry yet). The dynamic import (rather
// than a top-level `import * as Sentry`) keeps the Sentry client SDK out of every visitor's
// bundle entirely when it's unconfigured — Next inlines NEXT_PUBLIC_* at build time, so an
// unset DSN lets the bundler dead-code-eliminate this whole block, import included.
if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN;
import("@sentry/nextjs").then((Sentry) => {
Sentry.init({
dsn,
environment: process.env.NODE_ENV || "development",
// Small single-VM deployment, not high-traffic — start conservative and raise
// this once real usage is visible in Sentry, rather than sampling every request.
tracesSampleRate: 0.1,
});
});
}
+17
View File
@@ -0,0 +1,17 @@
// Next.js server instrumentation entry point. A no-op when NEXT_PUBLIC_SENTRY_DSN isn't
// set — see instrumentation-client.ts for the browser-side counterpart.
//
// Node runtime only, deliberately — this app's middleware.ts (which runs in Next's edge
// runtime) is a trivial pass-through with no real error surface, so an edge-runtime branch
// here would only inflate that shared middleware bundle for no actual coverage benefit.
export async function register() {
if (!process.env.NEXT_PUBLIC_SENTRY_DSN) return;
if (process.env.NEXT_RUNTIME !== "nodejs") return;
const Sentry = await import("@sentry/nextjs");
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
environment: process.env.NODE_ENV || "development",
tracesSampleRate: 0.1,
});
}