ifixkart-admin/app/(admin)/analytics/google/page.tsx

319 lines
14 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
BarChart3,
Users,
Eye,
Clock,
Globe,
TrendingUp,
RefreshCw,
CheckCircle2,
Radio,
ArrowUpRight,
Compass
} from 'lucide-react';
import { apiFetch } from '@/services/api/client';
import { API_ENDPOINTS } from '@/services/api/config';
import { toast } from 'sonner';
interface GA4Status {
enabled: boolean;
property_id: string;
is_ready: boolean;
credentials_configured: boolean;
}
interface GA4Overview {
property_id: string;
period: string;
metrics: {
active_users: number;
sessions: number;
screen_page_views: number;
engaged_sessions: number;
average_session_duration: number;
bounce_rate: number;
};
realtime_active_users: number;
}
interface GA4Source {
source_medium: string;
users: number;
sessions: number;
engaged_sessions: number;
}
export default function GoogleAnalyticsPage() {
const [status, setStatus] = useState<GA4Status | null>(null);
const [overview, setOverview] = useState<GA4Overview | null>(null);
const [sources, setSources] = useState<GA4Source[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const fetchData = async () => {
try {
setLoading(true);
const [statusRes, overviewRes, sourcesRes] = await Promise.all([
apiFetch<GA4Status>(API_ENDPOINTS.GOOGLE_ANALYTICS_STATUS),
apiFetch<{ status: string; data: GA4Overview }>(`${API_ENDPOINTS.GOOGLE_ANALYTICS_OVERVIEW}?days=30`),
apiFetch<{ status: string; data: GA4Source[] }>(`${API_ENDPOINTS.GOOGLE_ANALYTICS_SOURCES}?days=30`),
]);
if (statusRes) setStatus(statusRes);
if (overviewRes && overviewRes.data) setOverview(overviewRes.data);
if (sourcesRes && sourcesRes.data) setSources(sourcesRes.data);
} catch (err: unknown) {
console.error('Failed to load GA4 data:', err);
toast.error('Could not load Google Analytics data');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
const realtimeUsers = overview?.realtime_active_users ?? 0;
return (
<div className="space-y-6 pb-12">
{/* Top Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-border/60 pb-5">
<div>
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-primary mb-1">
<BarChart3 className="w-4 h-4 text-primary" />
<span>Google Analytics 4 (GA4) Service</span>
</div>
<h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-foreground">
Web & App Analytics
</h1>
<p className="text-sm text-muted-foreground mt-1">
Realtime traffic telemetry, 30-day user engagement, and acquisition channel breakdowns.
</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={fetchData}
disabled={loading}
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-xl bg-card border border-border shadow-xs hover:bg-muted/60 transition disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin text-primary' : 'text-muted-foreground'}`} />
<span>Refresh Analytics</span>
</button>
</div>
</div>
{/* Property Status & Realtime Live Banner */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Realtime Active Ticker */}
<div className="md:col-span-1 rounded-2xl border border-emerald-500/30 bg-gradient-to-br from-emerald-500/10 via-card to-card p-6 shadow-xs flex flex-col justify-between">
<div className="flex items-center justify-between">
<span className="text-xs font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400 flex items-center gap-2">
<span className="relative flex h-3 w-3">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-3 w-3 bg-emerald-500"></span>
</span>
Realtime Active Visitors
</span>
<Radio className="w-4 h-4 text-emerald-500 animate-pulse" />
</div>
<div className="my-4">
<div className="text-5xl font-black text-foreground tracking-tight font-mono">
{loading ? '...' : realtimeUsers}
</div>
<p className="text-xs text-muted-foreground mt-1">
Active users browsing the storefront in the last 30 minutes
</p>
</div>
<div className="text-[11px] font-medium text-emerald-600 dark:text-emerald-400 flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>GA4 Measurement Stream Connected</span>
</div>
</div>
{/* Property Credentials Overview */}
<div className="md:col-span-2 rounded-2xl border border-border/80 bg-card p-6 shadow-xs flex flex-col justify-between">
<div>
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-bold uppercase tracking-wider text-foreground flex items-center gap-2">
<Globe className="w-4 h-4 text-primary" />
<span>GA4 Property Profile</span>
</h3>
<span className="px-2.5 py-0.5 rounded-full bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 text-[10px] font-bold uppercase">
Ready & Ingesting
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4 text-xs">
<div className="p-3 rounded-xl bg-muted/40 border border-border/60">
<span className="text-muted-foreground block mb-1">GA4 Property ID</span>
<code className="font-mono text-sm font-bold text-foreground">
{status?.property_id || '521198579'}
</code>
</div>
<div className="p-3 rounded-xl bg-muted/40 border border-border/60">
<span className="text-muted-foreground block mb-1">Service Account Auth</span>
<span className="font-semibold text-emerald-500 flex items-center gap-1">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>google-analytics-service-account.json</span>
</span>
</div>
</div>
</div>
<div className="mt-4 pt-3 border-t border-border/60 flex items-center justify-between text-xs text-muted-foreground">
<span>Reporting Window: Last 30 Days</span>
<span className="font-mono text-primary font-medium">Google Analytics Data API v1beta</span>
</div>
</div>
</div>
{/* 30-Day Metrics Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="rounded-2xl border border-border/80 bg-card p-5 shadow-xs transition hover:shadow-md">
<div className="flex items-center justify-between text-muted-foreground mb-3">
<span className="text-xs font-medium uppercase tracking-wider">Total Active Users</span>
<div className="p-2 rounded-xl bg-blue-500/10 text-blue-500">
<Users className="w-5 h-5" />
</div>
</div>
<div className="text-3xl font-black text-foreground">
{loading ? '...' : (overview?.metrics?.active_users ?? 0).toLocaleString()}
</div>
<p className="text-xs text-muted-foreground mt-2">
Unique storefront visitors
</p>
</div>
<div className="rounded-2xl border border-border/80 bg-card p-5 shadow-xs transition hover:shadow-md">
<div className="flex items-center justify-between text-muted-foreground mb-3">
<span className="text-xs font-medium uppercase tracking-wider">Total Sessions</span>
<div className="p-2 rounded-xl bg-indigo-500/10 text-indigo-500">
<TrendingUp className="w-5 h-5" />
</div>
</div>
<div className="text-3xl font-black text-foreground">
{loading ? '...' : (overview?.metrics?.sessions ?? 0).toLocaleString()}
</div>
<p className="text-xs text-muted-foreground mt-2">
{(overview?.metrics?.engaged_sessions ?? 0).toLocaleString()} engaged sessions
</p>
</div>
<div className="rounded-2xl border border-border/80 bg-card p-5 shadow-xs transition hover:shadow-md">
<div className="flex items-center justify-between text-muted-foreground mb-3">
<span className="text-xs font-medium uppercase tracking-wider">Page Views</span>
<div className="p-2 rounded-xl bg-purple-500/10 text-purple-500">
<Eye className="w-5 h-5" />
</div>
</div>
<div className="text-3xl font-black text-foreground">
{loading ? '...' : (overview?.metrics?.screen_page_views ?? 0).toLocaleString()}
</div>
<p className="text-xs text-muted-foreground mt-2">
Catalog & PDP impressions
</p>
</div>
<div className="rounded-2xl border border-border/80 bg-card p-5 shadow-xs transition hover:shadow-md">
<div className="flex items-center justify-between text-muted-foreground mb-3">
<span className="text-xs font-medium uppercase tracking-wider">Avg Session Time</span>
<div className="p-2 rounded-xl bg-amber-500/10 text-amber-500">
<Clock className="w-5 h-5" />
</div>
</div>
<div className="text-3xl font-black text-foreground">
{loading ? '...' : `${Math.round(overview?.metrics?.average_session_duration ?? 0)}s`}
</div>
<p className="text-xs text-muted-foreground mt-2">
Bounce rate: {loading ? '...' : `${overview?.metrics?.bounce_rate ?? 0}%`}
</p>
</div>
</div>
{/* Traffic Sources & Channels Table */}
<div className="rounded-2xl border border-border/80 bg-card shadow-xs overflow-hidden">
<div className="p-5 border-b border-border/80 flex items-center justify-between">
<div>
<h2 className="text-base font-bold text-foreground flex items-center gap-2">
<Compass className="w-5 h-5 text-primary" />
<span>Acquisition Traffic Sources & Mediums</span>
</h2>
<p className="text-xs text-muted-foreground mt-0.5">
Breakdown of visitors arriving via search engines, social media, and direct URLs
</p>
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-muted/40 text-muted-foreground border-b border-border/60">
<tr>
<th className="px-4 py-3 font-semibold">Source / Medium</th>
<th className="px-4 py-3 font-semibold">Visitors (Users)</th>
<th className="px-4 py-3 font-semibold">Sessions</th>
<th className="px-4 py-3 font-semibold">Engaged Sessions</th>
<th className="px-4 py-3 font-semibold">Share of Traffic</th>
</tr>
</thead>
<tbody className="divide-y divide-border/60">
{loading ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
<RefreshCw className="w-5 h-5 animate-spin mx-auto mb-2 text-primary" />
<span>Loading traffic sources...</span>
</td>
</tr>
) : sources.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
No traffic source records available.
</td>
</tr>
) : (
sources.map((src, i) => {
const totalUsers = overview?.metrics?.active_users || 1;
const pct = Math.min(100, Math.round((src.users / totalUsers) * 100));
return (
<tr key={i} className="hover:bg-muted/30 transition">
<td className="px-4 py-3 font-medium text-foreground">
<span className="font-mono text-primary">{src.source_medium}</span>
</td>
<td className="px-4 py-3 font-bold text-foreground">
{src.users.toLocaleString()}
</td>
<td className="px-4 py-3 text-muted-foreground">
{src.sessions.toLocaleString()}
</td>
<td className="px-4 py-3 text-muted-foreground">
{src.engaged_sessions.toLocaleString()}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<div className="flex-1 max-w-[100px] h-2 rounded-full bg-muted overflow-hidden">
<div
className="h-full bg-primary rounded-full transition-all duration-500"
style={{ width: `${pct}%` }}
/>
</div>
<span className="text-[11px] font-semibold text-muted-foreground">{pct}%</span>
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
</div>
);
}