Adds a first-party analytics system with no third-party trackers and no persistent per-visitor identifiers: events are grouped into sessions via a daily-rotating pseudonymous hash (IP+UA+host, HMAC-salted, never stored raw). - New "Analytics" section in the Payload admin, gated by a canViewAnalytics permission on Users, following the existing custom-admin-view pattern used by the calendar feature - Sessions, page views, unique visitors, top/entry/exit pages, events, device/browser breakdown, date range filter with period comparison - Raw events and daily aggregate rollups as their own collections, with configurable retention and a cron endpoint that rolls up before purging - Cookie consent banner (necessary/preferences/statistics) with categories and copy editable from a new CMS global; a track() helper that is a complete no-op without statistics consent, so nothing is ever sent before a visitor opts in - track() calls wired into the booking flow, contact form, and navigation
197 lines
8.4 KiB
TypeScript
197 lines
8.4 KiB
TypeScript
import type { AdminViewServerProps } from "payload";
|
|
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: "Mobile", desktop: "Desktop", 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}>
|
|
<h1 className={styles.title}>Analytics</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}>
|
|
<h1 className={styles.title}>Analytics</h1>
|
|
<p className={styles.subtitle}>Datensparsame Reichweitenmessung — keine personenbezogenen 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 „Analytics-Einstellungen“).
|
|
</p>
|
|
)}
|
|
|
|
<div className={styles.tiles}>
|
|
<Tile label="Sessions" 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 & Sessions</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="Events"
|
|
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>Analytics & Datenschutz</h3>
|
|
<p>Erhobene Daten:</p>
|
|
<ul>
|
|
<li>Seitenaufrufe und Events (siehe „Events“-Tabelle)</li>
|
|
<li>Gerätetyp (Mobile/Desktop/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:innen 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 „Analytics-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>
|
|
);
|
|
}
|