Update GrowthAnalyticsChart.tsx

This commit is contained in:
g
2026-01-07 12:52:20 +00:00
parent ce1d2d3fe8
commit 3e27a4b1f2

View File

@@ -8,7 +8,6 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
@@ -16,6 +15,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import {
TrendingUp,
@@ -24,9 +24,7 @@ import {
ShoppingCart,
DollarSign,
Package,
ArrowUpRight,
ArrowDownRight,
Minus,
RefreshCw,
} from "lucide-react";
import {
getGrowthAnalyticsWithStore,
@@ -34,144 +32,149 @@ import {
} from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
import {
LineChart,
ComposedChart,
Bar,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
AreaChart,
Area,
BarChart,
Bar,
PieChart,
Pie,
Cell,
} from "recharts";
import { ChartSkeleton } from "./SkeletonLoaders";
interface GrowthAnalyticsChartProps {
hideNumbers?: boolean;
}
const SEGMENT_COLORS = {
new: "#3b82f6",
returning: "#10b981",
loyal: "#f59e0b",
vip: "#8b5cf6",
};
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 [loading, setLoading] = useState(true);
const [period, setPeriod] = useState("30");
const [refreshing, setRefreshing] = useState(false);
const { toast } = useToast();
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
setError(null);
setLoading(true);
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);
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchData();
}, [period, toast]);
}, [period]);
const maskValue = (value: string): string => {
if (!hideNumbers) return value;
if (value.includes("£")) return "£***";
if (value.match(/^\d/) || value.match(/^-?\d/)) return "***";
return value;
const handleRefresh = () => {
setRefreshing(true);
fetchData();
};
const formatGrowthRate = (rate: number): string => {
const prefix = rate > 0 ? "+" : "";
return `${prefix}${rate.toFixed(1)}%`;
const formatCurrency = (value: number) => {
if (hideNumbers) return "£***";
return new Intl.NumberFormat("en-GB", {
style: "currency",
currency: "GBP",
maximumFractionDigits: 0,
}).format(value);
};
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 formatNumber = (value: number) => {
if (hideNumbers) return "***";
return value.toLocaleString();
};
const getGrowthColor = (rate: number): string => {
if (rate > 0) return "text-green-600";
if (rate < 0) return "text-red-600";
return "text-muted-foreground";
const TrendIndicator = ({
value,
suffix = "%",
}: {
value: number;
suffix?: string;
}) => {
if (hideNumbers) return <span className="text-muted-foreground">***</span>;
const isPositive = value > 0;
const isNeutral = value === 0;
return (
<div
className={`flex items-center text-sm font-medium ${
isNeutral
? "text-muted-foreground"
: isPositive
? "text-green-600"
: "text-red-600"
}`}
>
{isPositive ? (
<TrendingUp className="h-4 w-4 mr-1" />
) : isNeutral ? null : (
<TrendingDown className="h-4 w-4 mr-1" />
)}
{isPositive ? "+" : ""}
{value.toFixed(1)}
{suffix}
</div>
);
};
const CustomTooltip = ({ active, payload, label }: any) => {
if (active && payload && payload.length) {
const CustomTooltip = ({ active, payload }: any) => {
if (active && 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">
<div className="bg-background border border-border p-3 rounded-lg shadow-lg">
<p className="font-medium mb-2">{item.date}</p>
<p className="text-sm text-blue-600">
Revenue:{" "}
<span className="font-semibold">
{hideNumbers ? "£***" : formatGBP(item.revenue)}
</span>
Orders: {hideNumbers ? "***" : item.orders.toLocaleString()}
</p>
<p className="text-sm text-green-600">
Orders:{" "}
<span className="font-semibold">
{hideNumbers ? "***" : item.orders}
</span>
Revenue: {hideNumbers ? "£***" : formatGBP(item.revenue)}
</p>
<p className="text-sm text-purple-600">
Customers:{" "}
<span className="font-semibold">
{hideNumbers ? "***" : item.uniqueCustomers}
</span>
Customers: {hideNumbers ? "***" : item.uniqueCustomers}
</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) {
if (loading && !data) {
return (
<ChartSkeleton
title="Growth Analytics"
description="Track your store's growth over time"
icon={TrendingUp}
showStats={true}
/>
<div className="flex justify-center my-8">
<div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
</div>
);
}
if (error || !data) {
if (!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>
<CardContent className="pt-6">
<div className="text-center text-muted-foreground">
No growth data available
</div>
</CardContent>
</Card>
@@ -180,343 +183,315 @@ export default function GrowthAnalyticsChart({
const { summary, customerInsights, timeSeries, topGrowingProducts } = data;
// Prepare pie chart data
const segmentData = [
{
name: "New",
value: customerInsights.newCustomers,
color: SEGMENT_COLORS.new,
},
{
name: "Returning",
value: customerInsights.returningCustomers,
color: SEGMENT_COLORS.returning,
},
];
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">
{/* Header */}
<div className="flex justify-between items-center">
<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>
<h3 className="text-lg font-semibold">Store Growth</h3>
<p className="text-sm text-muted-foreground">
{data.period.start} to {data.period.end} ({data.period.granularity})
</p>
</div>
<div className="flex items-center gap-2">
<Select value={period} onValueChange={setPeriod}>
<SelectTrigger className="w-40">
<SelectTrigger className="w-[140px]">
<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="365">Last year</SelectItem>
<SelectItem value="all">All time</SelectItem>
</SelectContent>
</Select>
<Button
variant="outline"
size="icon"
onClick={handleRefresh}
disabled={refreshing}
>
<RefreshCw
className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
/>
</Button>
</div>
</div>
{/* Summary Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Orders */}
<Card>
<CardHeader className="pb-2">
<div className="flex justify-between items-start">
<CardTitle className="text-sm font-medium">Orders</CardTitle>
<ShoppingCart className="h-4 w-4 text-muted-foreground" />
</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">
<CardContent>
<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
{formatNumber(summary.currentPeriod.orders)}
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-muted-foreground">
vs {formatNumber(summary.previousPeriod.orders)} prev
</span>
<TrendIndicator value={summary.growthRates.orders} />
</div>
</CardContent>
</Card>
{/* Orders Growth */}
{/* Revenue */}
<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
<CardHeader className="pb-2">
<div className="flex justify-between items-start">
<CardTitle className="text-sm font-medium">Revenue</CardTitle>
<DollarSign className="h-4 w-4 text-muted-foreground" />
</div>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">
{formatCurrency(summary.currentPeriod.revenue)}
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-muted-foreground">
vs {formatCurrency(summary.previousPeriod.revenue)} prev
</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>
<TrendIndicator value={summary.growthRates.revenue} />
</div>
</CardContent>
</Card>
{/* AOV Growth */}
{/* Avg Order Value */}
<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>
<CardHeader className="pb-2">
<div className="flex justify-between items-start">
<CardTitle className="text-sm font-medium">Avg Order</CardTitle>
<Package className="h-4 w-4 text-muted-foreground" />
</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">
</CardHeader>
<CardContent>
<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
{formatCurrency(summary.currentPeriod.avgOrderValue)}
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-muted-foreground">
vs {formatCurrency(summary.previousPeriod.avgOrderValue)} prev
</span>
<TrendIndicator value={summary.growthRates.avgOrderValue} />
</div>
</CardContent>
</Card>
{/* Customers Growth */}
{/* Customers */}
<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>
<CardHeader className="pb-2">
<div className="flex justify-between items-start">
<CardTitle className="text-sm font-medium">Customers</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</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">
</CardHeader>
<CardContent>
<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
{formatNumber(summary.currentPeriod.customers)}
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-muted-foreground">
vs {formatNumber(summary.previousPeriod.customers)} prev
</span>
<TrendIndicator value={summary.growthRates.customers} />
</div>
</CardContent>
</Card>
</div>
{/* Revenue Trend Chart */}
{/* Orders & Revenue Chart */}
<Card>
<CardHeader>
<CardTitle>Revenue & Orders Over Time</CardTitle>
<CardTitle>Orders & Revenue Trend</CardTitle>
<CardDescription>
{data.period.granularity === "daily"
? "Daily"
: data.period.granularity === "weekly"
? "Weekly"
: "Monthly"}{" "}
breakdown from {data.period.start} to {data.period.end}
Performance over the selected time period
</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>
{loading || refreshing ? (
<div className="flex items-center justify-center h-80">
<div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
</div>
) : (
<div className="h-72">
) : timeSeries.length > 0 ? (
<div className="h-80">
<ResponsiveContainer width="100%" height="100%">
<AreaChart
<ComposedChart
data={timeSeries}
margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<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 }}
tick={{ fontSize: 12 }}
angle={-45}
textAnchor="end"
height={60}
/>
<YAxis
yAxisId="left"
tick={{ fontSize: 11 }}
tickFormatter={(value) =>
hideNumbers ? "***" : `£${(value / 1000).toFixed(0)}k`
}
tick={{ fontSize: 12 }}
tickFormatter={(v) => (hideNumbers ? "***" : v)}
/>
<YAxis
yAxisId="right"
orientation="right"
tick={{ fontSize: 11 }}
tickFormatter={(value) => (hideNumbers ? "***" : value)}
tick={{ fontSize: 12 }}
tickFormatter={(v) =>
hideNumbers ? "***" : `£${(v / 1000).toFixed(0)}k`
}
/>
<Tooltip content={<CustomTooltip />} />
<Area
<Bar
yAxisId="left"
type="monotone"
dataKey="revenue"
stroke="#2563eb"
strokeWidth={2}
fill="url(#colorRevenue)"
dataKey="orders"
fill="#3b82f6"
radius={[4, 4, 0, 0]}
name="Orders"
/>
<Line
yAxisId="right"
type="monotone"
dataKey="orders"
stroke="#22c55e"
strokeWidth={2}
dot={false}
dataKey="revenue"
stroke="#10b981"
strokeWidth={3}
dot={{ fill: "#10b981", r: 4 }}
name="Revenue"
/>
</AreaChart>
</ComposedChart>
</ResponsiveContainer>
</div>
) : (
<div className="flex items-center justify-center h-80 text-muted-foreground">
No data available for the selected period
</div>
)}
</CardContent>
</Card>
{/* Customer Insights */}
{/* Customer Breakdown & Top Products */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Customer Segments */}
<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>
<CardTitle>Customer Breakdown</CardTitle>
<CardDescription>New vs returning customers</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="grid grid-cols-3 gap-4 mb-4">
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-2xl font-bold text-blue-600">
{maskValue(customerInsights.returningCustomers.toString())}
{formatNumber(customerInsights.newCustomers)}
</div>
<div className="text-xs text-muted-foreground">New</div>
</div>
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-2xl font-bold text-green-600">
{formatNumber(customerInsights.returningCustomers)}
</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 className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-2xl font-bold">
{formatNumber(customerInsights.totalCustomers)}
</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 className="grid grid-cols-2 gap-4">
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-lg font-bold">
{hideNumbers
? "***"
: customerInsights.avgOrdersPerCustomer.toFixed(1)}
</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 className="text-xs text-muted-foreground">
Avg Orders/Customer
</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 className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-lg font-bold">
{formatCurrency(customerInsights.avgSpentPerCustomer)}
</div>
<div className="text-xs text-muted-foreground">
Avg Spent/Customer
</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>
<CardTitle>Top Growing Products</CardTitle>
<CardDescription>
Products with the highest revenue growth compared to previous period
Highest revenue growth vs previous period
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{topGrowingProducts.length > 0 ? (
<div className="space-y-2">
{topGrowingProducts.slice(0, 5).map((product, index) => (
<div
key={product.productId}
className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
className="flex items-center justify-between p-2 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">
<div className="flex items-center gap-2">
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary/10 text-primary text-xs font-semibold">
{index + 1}
</div>
<div>
<div className="font-medium">{product.productName}</div>
<div className="text-sm font-medium truncate max-w-[150px]">
{product.productName}
</div>
<div className="text-xs text-muted-foreground">
{maskValue(formatGBP(product.currentPeriodRevenue))} revenue
{" · "}
{maskValue(product.currentPeriodQuantity.toString())} sold
{formatCurrency(product.currentPeriodRevenue)}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge
variant={product.revenueGrowth >= 0 ? "default" : "destructive"}
className="flex items-center gap-1"
<div
className={`text-sm font-semibold ${
product.revenueGrowth >= 0
? "text-green-600"
: "text-red-600"
}`}
>
{product.revenueGrowth >= 0 ? (
<TrendingUp className="h-3 w-3" />
) : (
<TrendingDown className="h-3 w-3" />
)}
{hideNumbers ? "***" : formatGrowthRate(product.revenueGrowth)}
</Badge>
{hideNumbers
? "***"
: `${product.revenueGrowth >= 0 ? "+" : ""}${product.revenueGrowth.toFixed(0)}%`}
</div>
</div>
))}
</div>
) : (
<div className="text-center text-muted-foreground py-8">
No product growth data available
</div>
)}
</CardContent>
</Card>
)}
</div>
</div>
);
}