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

234 lines
11 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
Users,
Eye,
Clock,
TrendingUp,
RefreshCw,
Radio,
Loader2,
} 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 dataCardShell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const secondaryButton =
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
const statValue = (value: number | undefined) => (loading ? '—' : (value ?? 0).toLocaleString());
const propertyId = status?.property_id || overview?.property_id || '—';
const ready = Boolean(status?.is_ready);
const credentials = Boolean(status?.credentials_configured);
return (
<div className="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Google Analytics</h1>
<button type="button" onClick={fetchData} disabled={loading} className={secondaryButton}>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
Refresh Analytics
</button>
</div>
<div className={`${dataCardShell} p-4 flex flex-wrap items-center justify-between gap-3`}>
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Property</p>
<p className="text-[15px] font-semibold text-foreground mt-0.5 truncate">{loading ? '—' : propertyId}</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
credentials ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'
}`}>
{loading ? '—' : credentials ? 'Credentials configured' : 'Credentials missing'}
</span>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
ready ? 'bg-success/15 text-success' : 'bg-warning/15 text-warning'
}`}>
{loading ? '—' : ready ? 'Ready' : 'Not ready'}
</span>
<span className="text-[12px] text-muted-foreground">Last 30 days</span>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-4">
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Realtime users</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{statValue(overview?.realtime_active_users)}</p>
<p className="text-[12px] text-muted-foreground mt-2">Last 30 minutes</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Radio className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Active users</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{statValue(overview?.metrics?.active_users)}</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Users className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Sessions</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{statValue(overview?.metrics?.sessions)}</p>
<p className="text-[12px] text-muted-foreground mt-2">
{loading ? '—' : `${(overview?.metrics?.engaged_sessions ?? 0).toLocaleString()} engaged`}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<TrendingUp className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Page views</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{statValue(overview?.metrics?.screen_page_views)}</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Eye className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Avg session</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">
{loading ? '—' : `${Math.round(overview?.metrics?.average_session_duration ?? 0)}s`}
</p>
<p className="text-[12px] text-muted-foreground mt-2">
Bounce {loading ? '—' : `${overview?.metrics?.bounce_rate ?? 0}%`}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Clock className="w-4 h-4" />
</span>
</div>
</div>
</div>
<div className={dataCardShell}>
<div className="px-4 py-3 border-b border-border">
<h2 className="text-[13px] font-semibold text-foreground">Traffic sources</h2>
</div>
{loading ? (
<div className="py-16 flex justify-center">
<Loader2 className="w-6 h-6 animate-spin text-primary" />
</div>
) : (
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[720px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Source</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Users</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Sessions</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Engaged</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Share</th>
</tr>
</thead>
<tbody>
{sources.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No traffic sources</td>
</tr>
) : sources.map((src, index) => {
const totalUsers = overview?.metrics?.active_users || 1;
const pct = Math.min(100, Math.round((src.users / totalUsers) * 100));
return (
<tr key={`${src.source_medium}-${index}`} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{src.source_medium}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-foreground">{src.users.toLocaleString()}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{src.sessions.toLocaleString()}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{src.engaged_sessions.toLocaleString()}</td>
<td className="px-4 py-2.5">
<div className="flex items-center justify-end gap-2">
<div className="w-16 h-1.5 rounded-full bg-muted overflow-hidden">
<div className="h-full bg-primary rounded-full" style={{ width: `${pct}%` }} />
</div>
<span className="text-[12px] font-semibold text-muted-foreground w-8 text-right">{pct}%</span>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}