Add growth analytics chart and service integration
Introduces a new GrowthAnalyticsChart component and integrates growth analytics data into the dashboard. Updates analytics-service to support growth analytics API, adds types, and exposes helper functions for fetching growth analytics with store context. The dashboard UI now includes a 'Growth' tab for visualizing store growth metrics and trends.
This commit is contained in:
@@ -1,11 +1,23 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, Suspense } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useState, useEffect, Suspense } from "react";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
TrendingUp,
|
||||
ShoppingCart,
|
||||
@@ -18,14 +30,17 @@ import {
|
||||
RefreshCw,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Calculator
|
||||
Calculator,
|
||||
} from "lucide-react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import MetricsCard from "./MetricsCard";
|
||||
import { getAnalyticsOverviewWithStore, type AnalyticsOverview } from "@/lib/services/analytics-service";
|
||||
import {
|
||||
getAnalyticsOverviewWithStore,
|
||||
type AnalyticsOverview,
|
||||
} from "@/lib/services/analytics-service";
|
||||
import { formatGBP } from "@/utils/format";
|
||||
import { MetricsCardSkeleton } from './SkeletonLoaders';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { MetricsCardSkeleton } from "./SkeletonLoaders";
|
||||
import dynamic from "next/dynamic";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { DateRangePicker } from "@/components/ui/date-picker";
|
||||
import { DateRange } from "react-day-picker";
|
||||
@@ -33,24 +48,31 @@ import { addDays, startOfDay, endOfDay } from "date-fns";
|
||||
import type { DateRange as ProfitDateRange } from "@/lib/services/profit-analytics-service";
|
||||
|
||||
// Lazy load chart components
|
||||
const RevenueChart = dynamic(() => import('./RevenueChart'), {
|
||||
loading: () => <ChartSkeleton />
|
||||
const RevenueChart = dynamic(() => import("./RevenueChart"), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
const ProductPerformanceChart = dynamic(() => import('./ProductPerformanceChart'), {
|
||||
loading: () => <ChartSkeleton />
|
||||
const ProductPerformanceChart = dynamic(
|
||||
() => import("./ProductPerformanceChart"),
|
||||
{
|
||||
loading: () => <ChartSkeleton />,
|
||||
},
|
||||
);
|
||||
|
||||
const CustomerInsightsChart = dynamic(() => import("./CustomerInsightsChart"), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
const CustomerInsightsChart = dynamic(() => import('./CustomerInsightsChart'), {
|
||||
loading: () => <ChartSkeleton />
|
||||
const OrderAnalyticsChart = dynamic(() => import("./OrderAnalyticsChart"), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
const OrderAnalyticsChart = dynamic(() => import('./OrderAnalyticsChart'), {
|
||||
loading: () => <ChartSkeleton />
|
||||
const ProfitAnalyticsChart = dynamic(() => import("./ProfitAnalyticsChart"), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
const ProfitAnalyticsChart = dynamic(() => import('./ProfitAnalyticsChart'), {
|
||||
loading: () => <ChartSkeleton />
|
||||
const GrowthAnalyticsChart = dynamic(() => import("./GrowthAnalyticsChart"), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
// Chart loading skeleton
|
||||
@@ -77,15 +99,19 @@ interface AnalyticsDashboardProps {
|
||||
initialData: AnalyticsOverview;
|
||||
}
|
||||
|
||||
export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardProps) {
|
||||
export default function AnalyticsDashboard({
|
||||
initialData,
|
||||
}: AnalyticsDashboardProps) {
|
||||
const [data, setData] = useState<AnalyticsOverview>(initialData);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [timeRange, setTimeRange] = useState('30');
|
||||
const [timeRange, setTimeRange] = useState("30");
|
||||
const [hideNumbers, setHideNumbers] = useState(false);
|
||||
const [profitDateRange, setProfitDateRange] = useState<DateRange | undefined>({
|
||||
const [profitDateRange, setProfitDateRange] = useState<DateRange | undefined>(
|
||||
{
|
||||
from: startOfDay(addDays(new Date(), -29)),
|
||||
to: endOfDay(new Date())
|
||||
});
|
||||
to: endOfDay(new Date()),
|
||||
},
|
||||
);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Function to mask sensitive numbers
|
||||
@@ -93,14 +119,14 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
if (!hideNumbers) return value;
|
||||
|
||||
// For currency values (£X.XX), show £***
|
||||
if (value.includes('£')) {
|
||||
return '£***';
|
||||
if (value.includes("£")) {
|
||||
return "£***";
|
||||
}
|
||||
|
||||
// For regular numbers, replace with asterisks maintaining similar length
|
||||
if (value.match(/^\d/)) {
|
||||
const numLength = value.replace(/[,\.]/g, '').length;
|
||||
return '*'.repeat(Math.min(numLength, 4));
|
||||
const numLength = value.replace(/[,\.]/g, "").length;
|
||||
return "*".repeat(Math.min(numLength, 4));
|
||||
}
|
||||
|
||||
return value;
|
||||
@@ -132,16 +158,18 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
value: maskValue(formatGBP(data.revenue.total)),
|
||||
description: "All-time revenue",
|
||||
icon: DollarSign,
|
||||
trend: data.revenue.monthly > 0 ? "up" as const : "neutral" as const,
|
||||
trendValue: hideNumbers ? "Hidden" : `${formatGBP(data.revenue.monthly)} this month`
|
||||
trend: data.revenue.monthly > 0 ? ("up" as const) : ("neutral" as const),
|
||||
trendValue: hideNumbers
|
||||
? "Hidden"
|
||||
: `${formatGBP(data.revenue.monthly)} this month`,
|
||||
},
|
||||
{
|
||||
title: "Total Orders",
|
||||
value: maskValue(data.orders.total.toLocaleString()),
|
||||
description: "All-time orders",
|
||||
icon: ShoppingCart,
|
||||
trend: data.orders.completed > 0 ? "up" as const : "neutral" as const,
|
||||
trendValue: hideNumbers ? "Hidden" : `${data.orders.completed} completed`
|
||||
trend: data.orders.completed > 0 ? ("up" as const) : ("neutral" as const),
|
||||
trendValue: hideNumbers ? "Hidden" : `${data.orders.completed} completed`,
|
||||
},
|
||||
{
|
||||
title: "Unique Customers",
|
||||
@@ -149,7 +177,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
description: "Total customers",
|
||||
icon: Users,
|
||||
trend: "neutral" as const,
|
||||
trendValue: "Lifetime customers"
|
||||
trendValue: "Lifetime customers",
|
||||
},
|
||||
{
|
||||
title: "Products",
|
||||
@@ -157,8 +185,8 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
description: "Active products",
|
||||
icon: Package,
|
||||
trend: "neutral" as const,
|
||||
trendValue: "In your store"
|
||||
}
|
||||
trendValue: "In your store",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -166,7 +194,9 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
{/* Header with Privacy Toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold tracking-tight">Analytics Dashboard</h2>
|
||||
<h2 className="text-3xl font-bold tracking-tight">
|
||||
Analytics Dashboard
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Overview of your store's performance and metrics.
|
||||
</p>
|
||||
@@ -197,7 +227,9 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
<RefreshCw
|
||||
className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
|
||||
/>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
@@ -205,15 +237,11 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
|
||||
{/* Key Metrics Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 lg:gap-6">
|
||||
{isLoading ? (
|
||||
[...Array(4)].map((_, i) => (
|
||||
<MetricsCardSkeleton key={i} />
|
||||
))
|
||||
) : (
|
||||
metrics.map((metric) => (
|
||||
{isLoading
|
||||
? [...Array(4)].map((_, i) => <MetricsCardSkeleton key={i} />)
|
||||
: metrics.map((metric) => (
|
||||
<MetricsCard key={metric.title} {...metric} />
|
||||
))
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Completion Rate Card */}
|
||||
@@ -245,12 +273,18 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
<div className="w-full bg-secondary rounded-full h-2">
|
||||
<div
|
||||
className="bg-primary h-2 rounded-full transition-all duration-300"
|
||||
style={{ width: hideNumbers ? "0%" : `${data.orders.completionRate}%` }}
|
||||
style={{
|
||||
width: hideNumbers
|
||||
? "0%"
|
||||
: `${data.orders.completionRate}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="secondary">
|
||||
{hideNumbers ? "** / **" : `${data.orders.completed} / ${data.orders.total}`}
|
||||
{hideNumbers
|
||||
? "** / **"
|
||||
: `${data.orders.completed} / ${data.orders.total}`}
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
@@ -262,7 +296,8 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">Time Period</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Revenue, Profit, and Orders tabs use time filtering. Products and Customers show all-time data.
|
||||
Revenue, Profit, and Orders tabs use time filtering. Products and
|
||||
Customers show all-time data.
|
||||
</p>
|
||||
</div>
|
||||
<Select value={timeRange} onValueChange={setTimeRange}>
|
||||
@@ -279,8 +314,12 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
|
||||
{/* Analytics Tabs */}
|
||||
<div className="space-y-6">
|
||||
<Tabs defaultValue="revenue" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<Tabs defaultValue="growth" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">
|
||||
<TabsTrigger value="growth" className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4" />
|
||||
Growth
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="revenue" className="flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Revenue
|
||||
@@ -303,6 +342,12 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="growth" className="space-y-6">
|
||||
<Suspense fallback={<ChartSkeleton />}>
|
||||
<GrowthAnalyticsChart hideNumbers={hideNumbers} />
|
||||
</Suspense>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="revenue" className="space-y-6">
|
||||
<Suspense fallback={<ChartSkeleton />}>
|
||||
<RevenueChart timeRange={timeRange} hideNumbers={hideNumbers} />
|
||||
@@ -330,7 +375,8 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
{profitDateRange?.from && profitDateRange?.to && (
|
||||
<div className="text-sm text-muted-foreground flex items-center">
|
||||
<span>
|
||||
{profitDateRange.from.toLocaleDateString()} - {profitDateRange.to.toLocaleDateString()}
|
||||
{profitDateRange.from.toLocaleDateString()} -{" "}
|
||||
{profitDateRange.to.toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -339,10 +385,14 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
||||
</Card>
|
||||
<Suspense fallback={<ChartSkeleton />}>
|
||||
<ProfitAnalyticsChart
|
||||
dateRange={profitDateRange?.from && profitDateRange?.to ? {
|
||||
dateRange={
|
||||
profitDateRange?.from && profitDateRange?.to
|
||||
? {
|
||||
from: profitDateRange.from,
|
||||
to: profitDateRange.to
|
||||
} : undefined}
|
||||
to: profitDateRange.to,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
hideNumbers={hideNumbers}
|
||||
/>
|
||||
</Suspense>
|
||||
|
||||
522
components/analytics/GrowthAnalyticsChart.tsx
Normal file
522
components/analytics/GrowthAnalyticsChart.tsx
Normal file
@@ -0,0 +1,522 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import {
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Users,
|
||||
ShoppingCart,
|
||||
DollarSign,
|
||||
Package,
|
||||
ArrowUpRight,
|
||||
ArrowDownRight,
|
||||
Minus,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
getGrowthAnalyticsWithStore,
|
||||
type GrowthAnalytics,
|
||||
} from "@/lib/services/analytics-service";
|
||||
import { formatGBP } from "@/utils/format";
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
AreaChart,
|
||||
Area,
|
||||
BarChart,
|
||||
Bar,
|
||||
} from "recharts";
|
||||
import { ChartSkeleton } from "./SkeletonLoaders";
|
||||
|
||||
interface GrowthAnalyticsChartProps {
|
||||
hideNumbers?: boolean;
|
||||
}
|
||||
|
||||
export default function GrowthAnalyticsChart({
|
||||
hideNumbers = false,
|
||||
}: GrowthAnalyticsChartProps) {
|
||||
const [data, setData] = useState<GrowthAnalytics | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [period, setPeriod] = useState("30");
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const response = await getGrowthAnalyticsWithStore(period);
|
||||
setData(response);
|
||||
} catch (err) {
|
||||
console.error("Error fetching growth data:", err);
|
||||
setError("Failed to load growth data");
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load growth analytics data.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [period, toast]);
|
||||
|
||||
const maskValue = (value: string): string => {
|
||||
if (!hideNumbers) return value;
|
||||
if (value.includes("£")) return "£***";
|
||||
if (value.match(/^\d/) || value.match(/^-?\d/)) return "***";
|
||||
return value;
|
||||
};
|
||||
|
||||
const formatGrowthRate = (rate: number): string => {
|
||||
const prefix = rate > 0 ? "+" : "";
|
||||
return `${prefix}${rate.toFixed(1)}%`;
|
||||
};
|
||||
|
||||
const getGrowthIcon = (rate: number) => {
|
||||
if (rate > 0) return <ArrowUpRight className="h-4 w-4 text-green-500" />;
|
||||
if (rate < 0) return <ArrowDownRight className="h-4 w-4 text-red-500" />;
|
||||
return <Minus className="h-4 w-4 text-muted-foreground" />;
|
||||
};
|
||||
|
||||
const getGrowthColor = (rate: number): string => {
|
||||
if (rate > 0) return "text-green-600";
|
||||
if (rate < 0) return "text-red-600";
|
||||
return "text-muted-foreground";
|
||||
};
|
||||
|
||||
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
const item = payload[0].payload;
|
||||
return (
|
||||
<div className="bg-background p-3 border border-border rounded-lg shadow-lg">
|
||||
<p className="text-sm font-medium text-foreground mb-2">{item.date}</p>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm text-blue-600">
|
||||
Revenue:{" "}
|
||||
<span className="font-semibold">
|
||||
{hideNumbers ? "£***" : formatGBP(item.revenue)}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-sm text-green-600">
|
||||
Orders:{" "}
|
||||
<span className="font-semibold">
|
||||
{hideNumbers ? "***" : item.orders}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-sm text-purple-600">
|
||||
Customers:{" "}
|
||||
<span className="font-semibold">
|
||||
{hideNumbers ? "***" : item.uniqueCustomers}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-sm text-orange-600">
|
||||
Avg Order:{" "}
|
||||
<span className="font-semibold">
|
||||
{hideNumbers ? "£***" : formatGBP(item.avgOrderValue)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<ChartSkeleton
|
||||
title="Growth Analytics"
|
||||
description="Track your store's growth over time"
|
||||
icon={TrendingUp}
|
||||
showStats={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !data) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-5 w-5" />
|
||||
Growth Analytics
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-center py-8">
|
||||
<TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
{error || "No growth data available"}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const { summary, customerInsights, timeSeries, topGrowingProducts } = data;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Period Selector */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-5 w-5" />
|
||||
Growth Analytics
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Compare performance against the previous period
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Select value={period} onValueChange={setPeriod}>
|
||||
<SelectTrigger className="w-40">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="7">Last 7 days</SelectItem>
|
||||
<SelectItem value="30">Last 30 days</SelectItem>
|
||||
<SelectItem value="90">Last 90 days</SelectItem>
|
||||
<SelectItem value="365">Last 365 days</SelectItem>
|
||||
<SelectItem value="all">All time</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* Growth Rate Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{/* Revenue Growth */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<DollarSign className="h-5 w-5 text-blue-500" />
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
Revenue
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{getGrowthIcon(summary.growthRates.revenue)}
|
||||
<span
|
||||
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.revenue)}`}
|
||||
>
|
||||
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.revenue)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="text-2xl font-bold">
|
||||
{maskValue(formatGBP(summary.currentPeriod.revenue))}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
vs {maskValue(formatGBP(summary.previousPeriod.revenue))} previous
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Orders Growth */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShoppingCart className="h-5 w-5 text-green-500" />
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
Orders
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{getGrowthIcon(summary.growthRates.orders)}
|
||||
<span
|
||||
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.orders)}`}
|
||||
>
|
||||
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.orders)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="text-2xl font-bold">
|
||||
{maskValue(summary.currentPeriod.orders.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
vs {maskValue(summary.previousPeriod.orders.toString())} previous
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* AOV Growth */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="h-5 w-5 text-purple-500" />
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
Avg Order
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{getGrowthIcon(summary.growthRates.avgOrderValue)}
|
||||
<span
|
||||
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.avgOrderValue)}`}
|
||||
>
|
||||
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.avgOrderValue)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="text-2xl font-bold">
|
||||
{maskValue(formatGBP(summary.currentPeriod.avgOrderValue))}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
vs {maskValue(formatGBP(summary.previousPeriod.avgOrderValue))} previous
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Customers Growth */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5 text-orange-500" />
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
Customers
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{getGrowthIcon(summary.growthRates.customers)}
|
||||
<span
|
||||
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.customers)}`}
|
||||
>
|
||||
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.customers)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="text-2xl font-bold">
|
||||
{maskValue(summary.currentPeriod.customers.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
vs {maskValue(summary.previousPeriod.customers.toString())} previous
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Revenue Trend Chart */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Revenue & Orders Over Time</CardTitle>
|
||||
<CardDescription>
|
||||
{data.period.granularity === "daily"
|
||||
? "Daily"
|
||||
: data.period.granularity === "weekly"
|
||||
? "Weekly"
|
||||
: "Monthly"}{" "}
|
||||
breakdown from {data.period.start} to {data.period.end}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{timeSeries.length === 0 ? (
|
||||
<div className="text-center py-8">
|
||||
<TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
No data available for this period
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-72">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart
|
||||
data={timeSeries}
|
||||
margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#2563eb" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="#2563eb" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tick={{ fontSize: 11 }}
|
||||
angle={-45}
|
||||
textAnchor="end"
|
||||
height={60}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="left"
|
||||
tick={{ fontSize: 11 }}
|
||||
tickFormatter={(value) =>
|
||||
hideNumbers ? "***" : `£${(value / 1000).toFixed(0)}k`
|
||||
}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="right"
|
||||
orientation="right"
|
||||
tick={{ fontSize: 11 }}
|
||||
tickFormatter={(value) => (hideNumbers ? "***" : value)}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Area
|
||||
yAxisId="left"
|
||||
type="monotone"
|
||||
dataKey="revenue"
|
||||
stroke="#2563eb"
|
||||
strokeWidth={2}
|
||||
fill="url(#colorRevenue)"
|
||||
/>
|
||||
<Line
|
||||
yAxisId="right"
|
||||
type="monotone"
|
||||
dataKey="orders"
|
||||
stroke="#22c55e"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Customer Insights */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5" />
|
||||
Customer Insights
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
New vs returning customers and engagement metrics
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{maskValue(customerInsights.newCustomers.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">New Customers</div>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{maskValue(customerInsights.returningCustomers.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Returning</div>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-purple-600">
|
||||
{maskValue(customerInsights.totalCustomers.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Total</div>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-orange-600">
|
||||
{hideNumbers ? "***%" : `${customerInsights.newCustomerRate}%`}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">New Rate</div>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-pink-600">
|
||||
{maskValue(customerInsights.avgOrdersPerCustomer.toString())}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Avg Orders</div>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-muted/50 rounded-lg">
|
||||
<div className="text-2xl font-bold text-teal-600">
|
||||
{maskValue(formatGBP(customerInsights.avgSpentPerCustomer))}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Avg Spent</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Top Growing Products */}
|
||||
{topGrowingProducts.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Package className="h-5 w-5" />
|
||||
Top Growing Products
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Products with the highest revenue growth compared to previous period
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{topGrowingProducts.slice(0, 5).map((product, index) => (
|
||||
<div
|
||||
key={product.productId}
|
||||
className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary/10 text-primary text-sm font-bold">
|
||||
{index + 1}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium">{product.productName}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{maskValue(formatGBP(product.currentPeriodRevenue))} revenue
|
||||
{" · "}
|
||||
{maskValue(product.currentPeriodQuantity.toString())} sold
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={product.revenueGrowth >= 0 ? "default" : "destructive"}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
{product.revenueGrowth >= 0 ? (
|
||||
<TrendingUp className="h-3 w-3" />
|
||||
) : (
|
||||
<TrendingDown className="h-3 w-3" />
|
||||
)}
|
||||
{hideNumbers ? "***" : formatGrowthRate(product.revenueGrowth)}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { clientFetch } from '../api-client';
|
||||
import { clientFetch } from "../api-client";
|
||||
|
||||
// Analytics Types
|
||||
export interface AnalyticsOverview {
|
||||
@@ -22,7 +22,7 @@ export interface AnalyticsOverview {
|
||||
customers: {
|
||||
unique: number;
|
||||
};
|
||||
userType?: 'vendor' | 'staff';
|
||||
userType?: "vendor" | "staff";
|
||||
}
|
||||
|
||||
export interface RevenueData {
|
||||
@@ -86,14 +86,73 @@ export interface OrderAnalytics {
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface GrowthAnalytics {
|
||||
period: {
|
||||
start: string;
|
||||
end: string;
|
||||
days: number;
|
||||
granularity: "daily" | "weekly" | "monthly";
|
||||
};
|
||||
summary: {
|
||||
currentPeriod: {
|
||||
revenue: number;
|
||||
orders: number;
|
||||
avgOrderValue: number;
|
||||
customers: number;
|
||||
};
|
||||
previousPeriod: {
|
||||
revenue: number;
|
||||
orders: number;
|
||||
avgOrderValue: number;
|
||||
customers: number;
|
||||
};
|
||||
growthRates: {
|
||||
revenue: number;
|
||||
orders: number;
|
||||
avgOrderValue: number;
|
||||
customers: number;
|
||||
};
|
||||
};
|
||||
customerInsights: {
|
||||
newCustomers: number;
|
||||
returningCustomers: number;
|
||||
totalCustomers: number;
|
||||
newCustomerRate: number;
|
||||
avgOrdersPerCustomer: number;
|
||||
avgSpentPerCustomer: number;
|
||||
};
|
||||
timeSeries: Array<{
|
||||
date: string;
|
||||
revenue: number;
|
||||
orders: number;
|
||||
avgOrderValue: number;
|
||||
uniqueCustomers: number;
|
||||
cumulativeRevenue: number;
|
||||
cumulativeOrders: number;
|
||||
}>;
|
||||
topGrowingProducts: Array<{
|
||||
productId: string;
|
||||
productName: string;
|
||||
currentPeriodRevenue: number;
|
||||
previousPeriodRevenue: number;
|
||||
revenueGrowth: number;
|
||||
currentPeriodQuantity: number;
|
||||
previousPeriodQuantity: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
// Analytics Service Functions
|
||||
|
||||
/**
|
||||
* Get analytics overview data
|
||||
* @param storeId Optional storeId for staff users
|
||||
*/
|
||||
export const getAnalyticsOverview = async (storeId?: string): Promise<AnalyticsOverview> => {
|
||||
const url = storeId ? `/analytics/overview?storeId=${storeId}` : '/analytics/overview';
|
||||
export const getAnalyticsOverview = async (
|
||||
storeId?: string,
|
||||
): Promise<AnalyticsOverview> => {
|
||||
const url = storeId
|
||||
? `/analytics/overview?storeId=${storeId}`
|
||||
: "/analytics/overview";
|
||||
return clientFetch<AnalyticsOverview>(url);
|
||||
};
|
||||
|
||||
@@ -102,9 +161,12 @@ export const getAnalyticsOverview = async (storeId?: string): Promise<AnalyticsO
|
||||
* @param period Time period in days (7, 30, 90)
|
||||
* @param storeId Optional storeId for staff users
|
||||
*/
|
||||
export const getRevenueTrends = async (period: string = '30', storeId?: string): Promise<RevenueData[]> => {
|
||||
export const getRevenueTrends = async (
|
||||
period: string = "30",
|
||||
storeId?: string,
|
||||
): Promise<RevenueData[]> => {
|
||||
const params = new URLSearchParams({ period });
|
||||
if (storeId) params.append('storeId', storeId);
|
||||
if (storeId) params.append("storeId", storeId);
|
||||
|
||||
const url = `/analytics/revenue-trends?${params.toString()}`;
|
||||
return clientFetch<RevenueData[]>(url);
|
||||
@@ -114,8 +176,12 @@ export const getRevenueTrends = async (period: string = '30', storeId?: string):
|
||||
* Get product performance data
|
||||
* @param storeId Optional storeId for staff users
|
||||
*/
|
||||
export const getProductPerformance = async (storeId?: string): Promise<ProductPerformance[]> => {
|
||||
const url = storeId ? `/analytics/product-performance?storeId=${storeId}` : '/analytics/product-performance';
|
||||
export const getProductPerformance = async (
|
||||
storeId?: string,
|
||||
): Promise<ProductPerformance[]> => {
|
||||
const url = storeId
|
||||
? `/analytics/product-performance?storeId=${storeId}`
|
||||
: "/analytics/product-performance";
|
||||
return clientFetch<ProductPerformance[]>(url);
|
||||
};
|
||||
|
||||
@@ -125,12 +191,16 @@ export const getProductPerformance = async (storeId?: string): Promise<ProductPe
|
||||
* @param page Page number (default: 1)
|
||||
* @param limit Number of customers per page (default: 10)
|
||||
*/
|
||||
export const getCustomerInsights = async (storeId?: string, page: number = 1, limit: number = 10): Promise<CustomerInsights> => {
|
||||
export const getCustomerInsights = async (
|
||||
storeId?: string,
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
): Promise<CustomerInsights> => {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString()
|
||||
limit: limit.toString(),
|
||||
});
|
||||
if (storeId) params.append('storeId', storeId);
|
||||
if (storeId) params.append("storeId", storeId);
|
||||
|
||||
const url = `/analytics/customer-insights?${params.toString()}`;
|
||||
return clientFetch<CustomerInsights>(url);
|
||||
@@ -141,23 +211,45 @@ export const getCustomerInsights = async (storeId?: string, page: number = 1, li
|
||||
* @param period Time period in days (7, 30, 90)
|
||||
* @param storeId Optional storeId for staff users
|
||||
*/
|
||||
export const getOrderAnalytics = async (period: string = '30', storeId?: string): Promise<OrderAnalytics> => {
|
||||
export const getOrderAnalytics = async (
|
||||
period: string = "30",
|
||||
storeId?: string,
|
||||
): Promise<OrderAnalytics> => {
|
||||
const params = new URLSearchParams({ period });
|
||||
if (storeId) params.append('storeId', storeId);
|
||||
if (storeId) params.append("storeId", storeId);
|
||||
|
||||
const url = `/analytics/order-analytics?${params.toString()}`;
|
||||
return clientFetch<OrderAnalytics>(url);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get growth analytics data
|
||||
* @param period Time period: "7", "30", "90", "365", or "all" (default: "30")
|
||||
* @param granularity Data granularity: "daily", "weekly", "monthly" (auto-selected if not specified)
|
||||
* @param storeId Optional storeId for staff users
|
||||
*/
|
||||
export const getGrowthAnalytics = async (
|
||||
period: string = "30",
|
||||
granularity?: string,
|
||||
storeId?: string,
|
||||
): Promise<GrowthAnalytics> => {
|
||||
const params = new URLSearchParams({ period });
|
||||
if (granularity) params.append("granularity", granularity);
|
||||
if (storeId) params.append("storeId", storeId);
|
||||
|
||||
const url = `/analytics/growth?${params.toString()}`;
|
||||
return clientFetch<GrowthAnalytics>(url);
|
||||
};
|
||||
|
||||
// Helper function to determine if user is staff and get storeId
|
||||
export const getStoreIdForUser = (): string | undefined => {
|
||||
if (typeof window === 'undefined') return undefined;
|
||||
if (typeof window === "undefined") return undefined;
|
||||
|
||||
// Check if user is staff (you might need to adjust this based on your auth system)
|
||||
const userType = localStorage.getItem('userType');
|
||||
const storeId = localStorage.getItem('storeId');
|
||||
const userType = localStorage.getItem("userType");
|
||||
const storeId = localStorage.getItem("storeId");
|
||||
|
||||
if (userType === 'staff' && storeId) {
|
||||
if (userType === "staff" && storeId) {
|
||||
return storeId;
|
||||
}
|
||||
|
||||
@@ -165,35 +257,53 @@ export const getStoreIdForUser = (): string | undefined => {
|
||||
};
|
||||
|
||||
// Enhanced analytics functions that automatically handle storeId for staff users
|
||||
export const getAnalyticsOverviewWithStore = async (): Promise<AnalyticsOverview> => {
|
||||
export const getAnalyticsOverviewWithStore =
|
||||
async (): Promise<AnalyticsOverview> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getAnalyticsOverview(storeId);
|
||||
};
|
||||
};
|
||||
|
||||
export const getRevenueTrendsWithStore = async (period: string = '30'): Promise<RevenueData[]> => {
|
||||
export const getRevenueTrendsWithStore = async (
|
||||
period: string = "30",
|
||||
): Promise<RevenueData[]> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getRevenueTrends(period, storeId);
|
||||
};
|
||||
|
||||
export const getProductPerformanceWithStore = async (): Promise<ProductPerformance[]> => {
|
||||
export const getProductPerformanceWithStore = async (): Promise<
|
||||
ProductPerformance[]
|
||||
> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getProductPerformance(storeId);
|
||||
};
|
||||
|
||||
export const getCustomerInsightsWithStore = async (page: number = 1, limit: number = 10): Promise<CustomerInsights> => {
|
||||
export const getCustomerInsightsWithStore = async (
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
): Promise<CustomerInsights> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getCustomerInsights(storeId, page, limit);
|
||||
};
|
||||
|
||||
export const getOrderAnalyticsWithStore = async (period: string = '30'): Promise<OrderAnalytics> => {
|
||||
export const getOrderAnalyticsWithStore = async (
|
||||
period: string = "30",
|
||||
): Promise<OrderAnalytics> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getOrderAnalytics(period, storeId);
|
||||
};
|
||||
|
||||
export const getGrowthAnalyticsWithStore = async (
|
||||
period: string = "30",
|
||||
granularity?: string,
|
||||
): Promise<GrowthAnalytics> => {
|
||||
const storeId = getStoreIdForUser();
|
||||
return getGrowthAnalytics(period, granularity, storeId);
|
||||
};
|
||||
|
||||
export function formatGBP(value: number) {
|
||||
return value.toLocaleString('en-GB', {
|
||||
style: 'currency',
|
||||
currency: 'GBP',
|
||||
return value.toLocaleString("en-GB", {
|
||||
style: "currency",
|
||||
currency: "GBP",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user