Files
anouma/components/admin/AdminAnalyticsView.tsx
T

200 lines
8.6 KiB
TypeScript

import type { AdminViewServerProps } from "payload";
import Link from "next/link";
import { canViewAnalytics } from "@/access";
import { RANGE_OPTIONS, resolveRange } from "@/lib/analytics/range";
import { getDashboardComparison, percentDelta, type DashboardStats } from "@/lib/analytics/dashboardQueries";
import { topEntries } from "@/lib/analytics/aggregate";
import { analyticsEventLabel } from "@/lib/analytics/events";
import { AnalyticsChart } from "./AnalyticsChart";
import styles from "./AdminAnalyticsView.module.css";
const DEVICE_LABELS: Record<string, string> = { mobile: "Handy", desktop: "Computer", tablet: "Tablet" };
const BROWSER_LABELS: Record<string, string> = { chrome: "Chrome", firefox: "Firefox", safari: "Safari", edge: "Edge", other: "Sonstige" };
function fmtInt(n: number): string {
return n.toLocaleString("de-DE");
}
function DeltaBadge({ delta }: { delta: number | null }) {
if (delta === null) return null;
const cls = delta > 0 ? styles.deltaUp : delta < 0 ? styles.deltaDown : styles.deltaFlat;
const arrow = delta > 0 ? "↑" : delta < 0 ? "↓" : "→";
return (
<p className={`${styles.tileDelta} ${cls}`}>
{arrow} {Math.abs(delta).toLocaleString("de-DE")}%
</p>
);
}
function Tile({ label, value, delta }: { label: string; value: number; delta: number | null | undefined }) {
return (
<div className={styles.tile}>
<p className={styles.tileLabel}>{label}</p>
<p className={styles.tileValue}>{fmtInt(value)}</p>
{delta !== undefined && <DeltaBadge delta={delta} />}
</div>
);
}
function EntryTable({ title, entries }: { title: string; entries: [string, number][] }) {
return (
<div>
<h2 className={styles.sectionTitle}>{title}</h2>
{entries.length === 0 ? (
<p className={styles.tableEmpty}>Keine Daten in diesem Zeitraum.</p>
) : (
<table className={styles.table}>
<tbody>
{entries.map(([key, count]) => (
<tr key={key}>
<td>{key}</td>
<td style={{ textAlign: "right", fontWeight: 600 }}>{fmtInt(count)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
function buildHref(base: URLSearchParams, overrides: Record<string, string | null>): string {
const params = new URLSearchParams(base);
for (const [key, value] of Object.entries(overrides)) {
if (value === null) params.delete(key);
else params.set(key, value);
}
const qs = params.toString();
return qs ? `?${qs}` : "?";
}
export async function AdminAnalyticsView({ initPageResult }: AdminViewServerProps) {
const req = initPageResult.req;
if (!canViewAnalytics({ req })) {
return (
<div className={styles.page}>
<Link href="/admin" className="anouma-admin-back">Zur Übersicht</Link>
<h1 className={styles.title}>Auswertung</h1>
<p className={styles.subtitle}>Du hast keine Berechtigung, diesen Bereich zu sehen.</p>
</div>
);
}
const settings = await req.payload.findGlobal({ slug: "analytics-settings" });
const maxDaysBack = settings.rawRetentionDays ?? 90;
const searchParams = req.searchParams;
const compareEnabled = searchParams.get("compare") === "1";
const { key: activeRange, range, compareRange } = resolveRange(searchParams, maxDaysBack);
const { current, previous }: { current: DashboardStats; previous: DashboardStats } = await getDashboardComparison(
req.payload,
range,
compareRange,
);
const delta = (metric: keyof Pick<DashboardStats, "sessions" | "pageViews" | "uniqueVisitors" | "avgPagesPerSession">) =>
compareEnabled ? percentDelta(current[metric], previous[metric]) : undefined;
const eventDelta = (name: string) =>
compareEnabled ? percentDelta(current.eventCounts[name] ?? 0, previous.eventCounts[name] ?? 0) : undefined;
const fromParam = range.from.toISOString().slice(0, 10);
const toParam = range.to.toISOString().slice(0, 10);
return (
<div className={styles.page}>
<Link href="/admin" className="anouma-admin-back">Zur Übersicht</Link>
<h1 className={styles.title}>Auswertung</h1>
<p className={styles.subtitle}>Datensparsame Reichweitenmessung ohne personenbezogene Profile. Rohdaten werden {maxDaysBack} Tage aufbewahrt.</p>
<div className={styles.filterBar}>
{RANGE_OPTIONS.map((option) => (
<a
key={option.key}
href={buildHref(searchParams, { range: option.key, from: null, to: null })}
className={`${styles.rangeLink} ${activeRange === option.key ? styles.rangeLinkActive : ""}`}
>
{option.label}
</a>
))}
<form method="get" className={styles.customForm}>
<input type="hidden" name="range" value="custom" />
{compareEnabled && <input type="hidden" name="compare" value="1" />}
<input type="date" name="from" defaultValue={fromParam} max={toParam} />
<span>bis</span>
<input type="date" name="to" defaultValue={toParam} max={new Date().toISOString().slice(0, 10)} />
<button type="submit">Anwenden</button>
</form>
<div className={styles.compareToggle}>
<a href={buildHref(searchParams, { compare: compareEnabled ? null : "1" })}>
{compareEnabled ? "Vergleich ausblenden" : "Mit Vorperiode vergleichen"}
</a>
</div>
</div>
{RANGE_OPTIONS.some((o) => typeof o.days === "number" && o.days > maxDaysBack) && (
<p style={{ color: "#888", fontSize: 12, marginTop: -16, marginBottom: 20 }}>
Zeiträume sind auf die konfigurierte Rohdaten-Aufbewahrung von {maxDaysBack} Tagen begrenzt (siehe „Auswertungs-Einstellungen“).
</p>
)}
<div className={styles.tiles}>
<Tile label="Besuche" value={current.sessions} delta={delta("sessions")} />
<Tile label="Seitenaufrufe" value={current.pageViews} delta={delta("pageViews")} />
<Tile label="Eindeutige Besucher" value={current.uniqueVisitors} delta={delta("uniqueVisitors")} />
<Tile label="Ø Seiten / Session" value={current.avgPagesPerSession} delta={delta("avgPagesPerSession")} />
<Tile label="Buchungsstarts" value={current.eventCounts.booking_started ?? 0} delta={eventDelta("booking_started")} />
<Tile label="Buchungen abgeschlossen" value={current.eventCounts.booking_completed ?? 0} delta={eventDelta("booking_completed")} />
</div>
<div className={styles.chartCard}>
<h2 className={styles.sectionTitle}>Seitenaufrufe und Besuche</h2>
<AnalyticsChart series={current.series} />
</div>
<div className={styles.tableGrid}>
<EntryTable title="Beliebteste Seiten" entries={topEntries(current.topPaths)} />
<EntryTable title="Einstiegsseiten" entries={topEntries(current.entryPaths)} />
<EntryTable title="Ausstiegsseiten" entries={topEntries(current.exitPaths)} />
<EntryTable
title="Ereignisse"
entries={topEntries(current.eventCounts).map(([name, count]) => [analyticsEventLabel(name), count])}
/>
<EntryTable
title="Geräte"
entries={topEntries(current.deviceCounts).map(([key, count]) => [DEVICE_LABELS[key] ?? key, count])}
/>
<EntryTable
title="Browser"
entries={topEntries(current.browserCounts).map(([key, count]) => [BROWSER_LABELS[key] ?? key, count])}
/>
</div>
<div className={styles.privacyPanel}>
<h3>Auswertung und Datenschutz</h3>
<p>Erhobene Daten:</p>
<ul>
<li>Seitenaufrufe und Ereignisse (siehe Tabelle „Ereignisse“)</li>
<li>Gerätetyp (Handy/Computer/Tablet)</li>
<li>Browser-Familie</li>
<li>Referrer-Hostname (nur die Domain, keine vollständige URL)</li>
</ul>
<p>
Keine Namen, E-Mail-Adressen, Telefonnummern, vollständigen IP-Adressen oder Formularinhalte. Kein Fingerprinting, keine
dauerhaften individuellen Nutzerprofile - Besucher werden über einen täglich rotierenden, nicht zurückverfolgbaren Hash
gruppiert.
</p>
<p>
<strong>Aufbewahrung:</strong> {settings.rawRetentionDays} Tage für Rohdaten, {settings.aggregateRetentionMonths} Monate für
aggregierte Tagesstatistiken (konfigurierbar unter „Auswertungs-Einstellungen“).
</p>
<p style={{ fontStyle: "italic", color: "#777" }}>
Rechtliche Einordnung (z. B. ob dies für eure Website ausreichend ist) ist keine technische Aussage dieses Panels - bitte im
Zweifel rechtlich prüfen lassen, wie auch beim Impressum/Datenschutztext der Website.
</p>
</div>
</div>
);
}