Neue Seite /admin/traffic (Seitenleiste unter Übersicht, Recht system.admin) mit Zeitraum 7/28/90 Tage bzw. 12 Monate: Echtzeit-Besucher, sechs Kennzahlen mit Vergleich zum Vorzeitraum, Verlaufsdiagramm (aktuell gegen davor), Kanäle, Quellen, Seiten, Einstiegsseiten, eigene Events, Geräte und Orte. API GET /analytics/traffic (batchRunReports + runRealtimeReport), Ergebnis 5 Minuten im Temp-Ordner zwischengespeichert (?refresh=1 umgeht das). Dashboard-Widget verlinkt auf die neue Seite. Build neu. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TFDXmUdWg4Ai8x5ehhJvva
394 lines
18 KiB
JavaScript
394 lines
18 KiB
JavaScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import { api } from '../../api/client.js';
|
||
import { Button, Card, EmptyState, PageHeader, Segmented } from '../../components/ui/index.jsx';
|
||
|
||
// Ausfuehrliche Besucher-Statistik aus Google Analytics (GA4 Data API, siehe
|
||
// GoogleAnalyticsReporting::fetchTrafficReport). Jede Zahl wird mit dem vorherigen Zeitraum
|
||
// gleicher Laenge verglichen, damit man sofort sieht, ob es aufwaerts oder abwaerts geht.
|
||
|
||
const RANGES = [
|
||
{ value: 7, label: '7 Tage' },
|
||
{ value: 28, label: '28 Tage' },
|
||
{ value: 90, label: '90 Tage' },
|
||
{ value: 365, label: '12 Monate' },
|
||
];
|
||
|
||
const CHART_METRICS = [
|
||
{ value: 'users', label: 'Besucher' },
|
||
{ value: 'sessions', label: 'Sitzungen' },
|
||
{ value: 'pageviews', label: 'Seitenaufrufe' },
|
||
];
|
||
|
||
const CHANNEL_LABELS = {
|
||
Direct: 'Direkt (Adresse/Lesezeichen)',
|
||
'Organic Search': 'Google & Co. (unbezahlt)',
|
||
'Paid Search': 'Suchanzeigen',
|
||
Referral: 'Verweise von anderen Seiten',
|
||
'Organic Social': 'Social Media',
|
||
'Paid Social': 'Social-Media-Anzeigen',
|
||
Email: 'E-Mail',
|
||
'Organic Maps': 'Google Maps',
|
||
'Organic Video': 'Video (YouTube & Co.)',
|
||
Display: 'Bannerwerbung',
|
||
Unassigned: 'Nicht zugeordnet',
|
||
};
|
||
|
||
const DEVICE_LABELS = { desktop: 'Computer', mobile: 'Handy', tablet: 'Tablet', 'smart tv': 'Smart-TV' };
|
||
|
||
// Eigene Events der Website (utils/analytics.js) mit verstaendlichem Namen. Automatische
|
||
// GA-Events wie session_start bringen hier nichts und werden ausgeblendet.
|
||
const EVENT_LABELS = {
|
||
generate_lead: 'Anfrage gesendet',
|
||
select_package: 'Paket angeklickt',
|
||
contact_call: 'Telefonnummer angetippt',
|
||
contact_whatsapp: 'WhatsApp geöffnet',
|
||
scroll: 'Bis zum Seitenende gescrollt',
|
||
click: 'Link zu anderer Website',
|
||
file_download: 'Datei heruntergeladen',
|
||
form_start: 'Formular angefangen',
|
||
};
|
||
|
||
const nf = new Intl.NumberFormat('de-DE');
|
||
const fmtNumber = (n) => nf.format(Math.round(n));
|
||
const fmtPercent = (n) => `${new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 }).format(n * 100)} %`;
|
||
const fmtDuration = (seconds) => {
|
||
const s = Math.round(seconds);
|
||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} min`;
|
||
};
|
||
const fmtDate = (ymd, withYear = false) => `${ymd.slice(6, 8)}.${ymd.slice(4, 6)}.${withYear ? ymd.slice(0, 4) : ''}`;
|
||
|
||
function change(current, previous) {
|
||
if (!previous) return current > 0 ? { label: 'neu', tone: 'up' } : null;
|
||
const pct = ((current - previous) / previous) * 100;
|
||
if (Math.abs(pct) < 0.5) return { label: '±0 %', tone: 'flat' };
|
||
return {
|
||
label: `${pct > 0 ? '+' : '−'}${new Intl.NumberFormat('de-DE', { maximumFractionDigits: Math.abs(pct) < 10 ? 1 : 0 }).format(Math.abs(pct))} %`,
|
||
tone: pct > 0 ? 'up' : 'down',
|
||
};
|
||
}
|
||
|
||
const TREND_TONES = {
|
||
up: 'bg-brand-100 text-brand-800 dark:bg-brand-900/50 dark:text-brand-300',
|
||
down: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
|
||
flat: 'bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300',
|
||
};
|
||
|
||
function Trend({ current, previous, className = '' }) {
|
||
const c = change(current, previous);
|
||
if (!c) return null;
|
||
return (
|
||
<span className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[11px] font-semibold tabular-nums ${TREND_TONES[c.tone]} ${className}`}>
|
||
{c.tone === 'up' ? '▲ ' : c.tone === 'down' ? '▼ ' : ''}
|
||
{c.label}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
function KpiTile({ label, hint, value, previous, format }) {
|
||
return (
|
||
<div className="rounded-xl border border-neutral-200/80 bg-white p-4 shadow-sm shadow-neutral-900/[0.03] dark:border-neutral-800 dark:bg-neutral-900 dark:shadow-none">
|
||
<p className="text-xs font-medium text-neutral-500 dark:text-neutral-400" title={hint}>
|
||
{label}
|
||
</p>
|
||
<p className="mt-1 text-2xl font-bold tabular-nums tracking-tight text-neutral-900 dark:text-white">{format(value)}</p>
|
||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||
<Trend current={value} previous={previous} />
|
||
<span className="text-[11px] text-neutral-400">vorher {format(previous)}</span>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Verlauf als Liniendiagramm: aktueller Zeitraum (Flaeche) gegen den vorherigen (gestrichelt). */
|
||
function TrendChart({ current, previous, metric, days }) {
|
||
const [hover, setHover] = useState(null);
|
||
// In echter Pixelbreite zeichnen statt per viewBox zu skalieren - sonst wird die Schrift
|
||
// auf dem Handy winzig.
|
||
const boxRef = useRef(null);
|
||
const [W, setW] = useState(720);
|
||
useEffect(() => {
|
||
const el = boxRef.current;
|
||
if (!el) return undefined;
|
||
const ro = new ResizeObserver(([entry]) => setW(Math.max(260, Math.round(entry.contentRect.width))));
|
||
ro.observe(el);
|
||
return () => ro.disconnect();
|
||
}, []);
|
||
const H = W < 500 ? 200 : 240;
|
||
const pad = { top: 12, right: 8, bottom: 26, left: 36 };
|
||
const innerW = W - pad.left - pad.right;
|
||
const innerH = H - pad.top - pad.bottom;
|
||
|
||
const max = Math.max(1, ...current.map((d) => d[metric]), ...previous.map((d) => d[metric]));
|
||
const niceMax = (() => {
|
||
const step = 10 ** Math.floor(Math.log10(max));
|
||
return Math.ceil(max / step) * step;
|
||
})();
|
||
const n = current.length;
|
||
const x = (i) => pad.left + (n <= 1 ? innerW / 2 : (i / (n - 1)) * innerW);
|
||
const y = (v) => pad.top + innerH - (v / niceMax) * innerH;
|
||
const line = (points) => points.map((d, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(d[metric]).toFixed(1)}`).join('');
|
||
const area = `${line(current)}L${x(n - 1).toFixed(1)},${pad.top + innerH}L${x(0).toFixed(1)},${pad.top + innerH}Z`;
|
||
|
||
const ticks = [0, 0.5, 1].map((f) => Math.round(niceMax * f));
|
||
const labelEvery = Math.max(1, Math.ceil(n / Math.max(3, Math.floor(W / 100))));
|
||
|
||
const onMove = (e) => {
|
||
const rect = e.currentTarget.getBoundingClientRect();
|
||
const px = ((e.clientX - rect.left) / rect.width) * W;
|
||
const i = Math.round(((px - pad.left) / innerW) * (n - 1));
|
||
setHover(Math.min(n - 1, Math.max(0, i)));
|
||
};
|
||
|
||
const h = hover !== null ? { cur: current[hover], prev: previous[hover] } : null;
|
||
|
||
return (
|
||
<div ref={boxRef} className="relative">
|
||
<svg
|
||
width={W}
|
||
height={H}
|
||
viewBox={`0 0 ${W} ${H}`}
|
||
className="block max-w-full touch-none select-none"
|
||
onMouseMove={onMove}
|
||
onTouchMove={(e) => onMove(e.touches[0] ? { ...e, clientX: e.touches[0].clientX, currentTarget: e.currentTarget } : e)}
|
||
onMouseLeave={() => setHover(null)}
|
||
role="img"
|
||
aria-label="Verlauf im gewählten Zeitraum im Vergleich zum vorherigen"
|
||
>
|
||
<defs>
|
||
<linearGradient id="traffic-area" x1="0" x2="0" y1="0" y2="1">
|
||
<stop offset="0%" stopColor="#6ba626" stopOpacity="0.28" />
|
||
<stop offset="100%" stopColor="#6ba626" stopOpacity="0" />
|
||
</linearGradient>
|
||
</defs>
|
||
{ticks.map((t) => (
|
||
<g key={t}>
|
||
<line x1={pad.left} x2={W - pad.right} y1={y(t)} y2={y(t)} className="stroke-neutral-200 dark:stroke-neutral-800" strokeWidth="1" />
|
||
<text x={pad.left - 6} y={y(t) + 4} textAnchor="end" className="fill-neutral-400 text-[11px]">
|
||
{fmtNumber(t)}
|
||
</text>
|
||
</g>
|
||
))}
|
||
{current.map((d, i) =>
|
||
(i % labelEvery === 0 && n - 1 - i >= labelEvery / 2) || i === n - 1 ? (
|
||
<text key={d.date} x={x(i)} y={H - 6} textAnchor={i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle'} className="fill-neutral-400 text-[11px]">
|
||
{fmtDate(d.date)}
|
||
</text>
|
||
) : null,
|
||
)}
|
||
<path d={line(previous)} fill="none" className="stroke-neutral-400 dark:stroke-neutral-500" strokeWidth="1.5" strokeDasharray="4 4" />
|
||
<path d={area} fill="url(#traffic-area)" />
|
||
<path d={line(current)} fill="none" stroke="#6ba626" strokeWidth="2.25" strokeLinejoin="round" strokeLinecap="round" />
|
||
{h && (
|
||
<g>
|
||
<line x1={x(hover)} x2={x(hover)} y1={pad.top} y2={pad.top + innerH} className="stroke-neutral-300 dark:stroke-neutral-700" />
|
||
<circle cx={x(hover)} cy={y(h.cur[metric])} r="4" fill="#6ba626" className="stroke-white dark:stroke-neutral-900" strokeWidth="2" />
|
||
</g>
|
||
)}
|
||
</svg>
|
||
{h && (
|
||
<div
|
||
className="pointer-events-none absolute top-0 z-10 rounded-lg border border-neutral-200 bg-white px-3 py-2 text-xs shadow-lg dark:border-neutral-700 dark:bg-neutral-900"
|
||
style={{ left: `${(x(hover) / W) * 100}%`, transform: `translateX(${hover > n / 2 ? '-105%' : '5%'})` }}
|
||
>
|
||
<p className="font-semibold text-neutral-900 dark:text-white">
|
||
{fmtDate(h.cur.date, true)}: {fmtNumber(h.cur[metric])}
|
||
</p>
|
||
{h.prev && (
|
||
<p className="text-neutral-500 dark:text-neutral-400">
|
||
{days} Tage davor ({fmtDate(h.prev.date)}): {fmtNumber(h.prev[metric])}
|
||
</p>
|
||
)}
|
||
</div>
|
||
)}
|
||
<div className="mt-2 flex flex-wrap gap-4 text-xs text-neutral-500 dark:text-neutral-400">
|
||
<span className="flex items-center gap-1.5">
|
||
<span className="h-0.5 w-4 rounded bg-brand-500" /> Gewählter Zeitraum
|
||
</span>
|
||
<span className="flex items-center gap-1.5">
|
||
<span className="w-4 border-t-2 border-dashed border-neutral-400" /> Zeitraum davor
|
||
</span>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Liste mit Balken, Anteil und Trend je Zeile (Kanaele, Seiten, Quellen ...). */
|
||
function BreakdownList({ rows, label = (n) => n, mono = false, showTrend = true, empty = 'Noch keine Daten.' }) {
|
||
if (!rows?.length) return <p className="text-sm text-neutral-400">{empty}</p>;
|
||
const total = rows.reduce((s, r) => s + r.current, 0) || 1;
|
||
const max = Math.max(...rows.map((r) => r.current), 1);
|
||
return (
|
||
<ul className="space-y-2.5">
|
||
{rows.map((r) => (
|
||
<li key={r.name}>
|
||
<div className="mb-1 flex items-baseline justify-between gap-3 text-sm">
|
||
<span className={`min-w-0 truncate text-neutral-700 dark:text-neutral-200 ${mono ? 'font-mono text-xs' : ''}`} title={r.name}>
|
||
{label(r.name) || '(nicht gesetzt)'}
|
||
</span>
|
||
<span className="flex shrink-0 items-center gap-2">
|
||
{showTrend && <Trend current={r.current} previous={r.previous} />}
|
||
<span className="w-12 text-right font-semibold tabular-nums text-neutral-900 dark:text-white">{fmtNumber(r.current)}</span>
|
||
</span>
|
||
</div>
|
||
<div className="flex items-center gap-2">
|
||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-neutral-100 dark:bg-neutral-800">
|
||
<div className="h-full rounded-full bg-brand-500/80" style={{ width: `${(r.current / max) * 100}%` }} />
|
||
</div>
|
||
<span className="w-10 text-right text-[11px] tabular-nums text-neutral-400">{Math.round((r.current / total) * 100)} %</span>
|
||
</div>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|
||
|
||
function Realtime({ data }) {
|
||
if (!data) return null;
|
||
return (
|
||
<Card className="mb-6">
|
||
<div className="flex flex-wrap items-center gap-x-6 gap-y-3">
|
||
<div className="flex items-center gap-3">
|
||
<span className="relative flex h-3 w-3">
|
||
{data.users > 0 && <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-brand-400 opacity-75" />}
|
||
<span className={`relative inline-flex h-3 w-3 rounded-full ${data.users > 0 ? 'bg-brand-500' : 'bg-neutral-300 dark:bg-neutral-600'}`} />
|
||
</span>
|
||
<p className="text-sm text-neutral-600 dark:text-neutral-300">
|
||
<span className="text-2xl font-bold tabular-nums text-neutral-900 dark:text-white">{data.users}</span>{' '}
|
||
Besucher in den letzten 30 Minuten
|
||
</p>
|
||
</div>
|
||
{data.pages.length > 0 && (
|
||
<p className="min-w-0 text-xs text-neutral-500 dark:text-neutral-400">
|
||
Gerade auf: {data.pages.map((p) => `${p.name} (${p.users})`).join(' · ')}
|
||
</p>
|
||
)}
|
||
</div>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
export default function Traffic() {
|
||
const [days, setDays] = useState(28);
|
||
const [metric, setMetric] = useState('users');
|
||
const [report, setReport] = useState(null);
|
||
const [error, setError] = useState('');
|
||
const [loading, setLoading] = useState(false);
|
||
|
||
const load = (refresh = false) => {
|
||
setLoading(true);
|
||
setError('');
|
||
api
|
||
.get(`/analytics/traffic?days=${days}${refresh ? '&refresh=1' : ''}`)
|
||
.then(setReport)
|
||
.catch((e) => setError(e.message))
|
||
.finally(() => setLoading(false));
|
||
};
|
||
|
||
useEffect(() => {
|
||
load();
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
}, [days]);
|
||
|
||
const events = useMemo(
|
||
() => (report?.events || []).filter((e) => EVENT_LABELS[e.name]).sort((a, b) => Object.keys(EVENT_LABELS).indexOf(a.name) - Object.keys(EVENT_LABELS).indexOf(b.name)),
|
||
[report],
|
||
);
|
||
|
||
const header = (
|
||
<PageHeader
|
||
title="Besucher"
|
||
description="Zahlen aus Google Analytics. Jede Zahl zeigt den Vergleich zum gleich langen Zeitraum davor."
|
||
actions={
|
||
<>
|
||
<Segmented value={days} onChange={setDays} options={RANGES} size="sm" />
|
||
<Button variant="secondary" size="sm" icon="refresh" onClick={() => load(true)} disabled={loading}>
|
||
Aktualisieren
|
||
</Button>
|
||
</>
|
||
}
|
||
/>
|
||
);
|
||
|
||
if (report && !report.configured) {
|
||
return (
|
||
<div>
|
||
<PageHeader title="Besucher" />
|
||
<Card>
|
||
<EmptyState
|
||
icon="gauge"
|
||
title="Google Analytics ist noch nicht verbunden"
|
||
description="Trage unter System › Google-Dienste die Property-ID und den Service-Account ein, dann erscheinen hier die Besucherzahlen."
|
||
actions={<Button to="/admin/settings/google">Zu den Google-Diensten</Button>}
|
||
/>
|
||
</Card>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div>
|
||
{header}
|
||
{error && (
|
||
<Card className="mb-6">
|
||
<p className="text-sm text-red-600">{error}</p>
|
||
</Card>
|
||
)}
|
||
{!report && !error && <p className="text-sm text-neutral-400">Lädt…</p>}
|
||
|
||
{report && (
|
||
<div className={loading ? 'opacity-60 transition-opacity' : 'transition-opacity'}>
|
||
<Realtime data={report.realtime} />
|
||
|
||
<div className="mb-6 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-3 xl:grid-cols-6">
|
||
<KpiTile label="Besucher" hint="Aktive Nutzer im Zeitraum" value={report.kpis.activeUsers.current} previous={report.kpis.activeUsers.previous} format={fmtNumber} />
|
||
<KpiTile label="Neue Besucher" hint="Zum ersten Mal auf der Seite" value={report.kpis.newUsers.current} previous={report.kpis.newUsers.previous} format={fmtNumber} />
|
||
<KpiTile label="Sitzungen" hint="Besuche (ein Besucher kann mehrmals kommen)" value={report.kpis.sessions.current} previous={report.kpis.sessions.previous} format={fmtNumber} />
|
||
<KpiTile label="Seitenaufrufe" value={report.kpis.screenPageViews.current} previous={report.kpis.screenPageViews.previous} format={fmtNumber} />
|
||
<KpiTile label="Ø Besuchsdauer" value={report.kpis.averageSessionDuration.current} previous={report.kpis.averageSessionDuration.previous} format={fmtDuration} />
|
||
<KpiTile label="Interessierte Besuche" hint="Anteil der Sitzungen über 10 Sekunden, mit 2+ Seiten oder einer Aktion (GA: Engagement-Rate)" value={report.kpis.engagementRate.current} previous={report.kpis.engagementRate.previous} format={fmtPercent} />
|
||
</div>
|
||
|
||
<Card title="Verlauf" actions={<Segmented value={metric} onChange={setMetric} options={CHART_METRICS} size="sm" />} className="mb-6">
|
||
<TrendChart current={report.daily.current} previous={report.daily.previous} metric={metric} days={report.days} />
|
||
</Card>
|
||
|
||
<div className="grid gap-6 lg:grid-cols-2">
|
||
<Card title="Woher die Besucher kommen" description="Sitzungen nach Kanal">
|
||
<BreakdownList rows={report.channels} label={(n) => CHANNEL_LABELS[n] || n} />
|
||
</Card>
|
||
<Card title="Quellen" description="Sitzungen nach Website bzw. Suchmaschine">
|
||
<BreakdownList rows={report.sources} label={(n) => (n === '(direct)' ? 'direkt' : n)} />
|
||
</Card>
|
||
<Card title="Meistbesuchte Seiten" description="Seitenaufrufe">
|
||
<BreakdownList rows={report.pages} mono />
|
||
</Card>
|
||
<Card title="Einstiegsseiten" description="Auf welcher Seite ein Besuch beginnt (Sitzungen)">
|
||
<BreakdownList rows={report.landing_pages} mono showTrend={false} />
|
||
</Card>
|
||
<Card title="Was Besucher tun" description="Anzahl im Zeitraum – die wichtigsten Aktionen auf der Website">
|
||
<BreakdownList rows={events} label={(n) => EVENT_LABELS[n]} empty="Noch keine Aktionen erfasst." />
|
||
</Card>
|
||
<div className="grid gap-6">
|
||
<Card title="Geräte" description="Besucher">
|
||
<BreakdownList rows={report.devices} label={(n) => DEVICE_LABELS[n] || n} />
|
||
</Card>
|
||
<Card title="Orte" description="Besucher nach Stadt (ungefähr, aus der IP-Adresse)">
|
||
<BreakdownList rows={report.cities} showTrend={false} label={(n) => (n === '(not set)' ? 'unbekannt' : n)} />
|
||
</Card>
|
||
</div>
|
||
</div>
|
||
|
||
<p className="mt-6 text-xs text-neutral-400">
|
||
Gezählt werden nur Besucher, die im Cookie-Banner der Statistik zugestimmt haben. Stand{' '}
|
||
{new Date(report.generated_at).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })} Uhr, wird bis zu 5 Minuten
|
||
zwischengespeichert. Noch mehr Auswertungen gibt es direkt in{' '}
|
||
<a href="https://analytics.google.com/" target="_blank" rel="noreferrer" className="text-brand-600 hover:underline dark:text-brand-400">
|
||
Google Analytics
|
||
</a>
|
||
.
|
||
</p>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|