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 ( {c.tone === 'up' ? '▲ ' : c.tone === 'down' ? '▼ ' : ''} {c.label} ); } function KpiTile({ label, hint, value, previous, format }) { return (

{label}

{format(value)}

vorher {format(previous)}
); } /** 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 (
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" > {ticks.map((t) => ( {fmtNumber(t)} ))} {current.map((d, i) => (i % labelEvery === 0 && n - 1 - i >= labelEvery / 2) || i === n - 1 ? ( {fmtDate(d.date)} ) : null, )} {h && ( )} {h && (
n / 2 ? '-105%' : '5%'})` }} >

{fmtDate(h.cur.date, true)}: {fmtNumber(h.cur[metric])}

{h.prev && (

{days} Tage davor ({fmtDate(h.prev.date)}): {fmtNumber(h.prev[metric])}

)}
)}
Gewählter Zeitraum Zeitraum davor
); } /** 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

{empty}

; const total = rows.reduce((s, r) => s + r.current, 0) || 1; const max = Math.max(...rows.map((r) => r.current), 1); return ( ); } function Realtime({ data }) { if (!data) return null; return (
{data.users > 0 && } 0 ? 'bg-brand-500' : 'bg-neutral-300 dark:bg-neutral-600'}`} />

{data.users}{' '} Besucher in den letzten 30 Minuten

{data.pages.length > 0 && (

Gerade auf: {data.pages.map((p) => `${p.name} (${p.users})`).join(' · ')}

)}
); } 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 = ( } /> ); if (report && !report.configured) { return (
Zu den Google-Diensten} />
); } return (
{header} {error && (

{error}

)} {!report && !error &&

Lädt…

} {report && (
} className="mb-6">
CHANNEL_LABELS[n] || n} /> (n === '(direct)' ? 'direkt' : n)} /> EVENT_LABELS[n]} empty="Noch keine Aktionen erfasst." />
DEVICE_LABELS[n] || n} /> (n === '(not set)' ? 'unbekannt' : n)} />

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{' '} Google Analytics .

)}
); }