holy fkn airball

This commit is contained in:
NotII
2025-06-29 04:13:50 +01:00
parent e9b943a00a
commit 236a676ac5
11 changed files with 638 additions and 164 deletions

View File

@@ -17,34 +17,14 @@ import {
Activity,
RefreshCw
} from "lucide-react";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import RevenueChart from "./RevenueChart";
import ProductPerformanceChart from "./ProductPerformanceChart";
import CustomerInsightsChart from "./CustomerInsightsChart";
import OrderAnalyticsChart from "./OrderAnalyticsChart";
import MetricsCard from "./MetricsCard";
interface AnalyticsOverview {
orders: {
total: number;
completed: number;
pending: number;
completionRate: string;
};
revenue: {
total: number;
monthly: number;
weekly: number;
averageOrderValue: number;
};
products: {
total: number;
};
customers: {
unique: number;
};
}
import { getAnalyticsOverviewWithStore, type AnalyticsOverview } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
interface AnalyticsDashboardProps {
initialData: AnalyticsOverview;
@@ -59,7 +39,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
const refreshData = async () => {
try {
setIsLoading(true);
const newData = await clientFetch<AnalyticsOverview>("/analytics/overview");
const newData = await getAnalyticsOverviewWithStore();
setData(newData);
toast({
title: "Data refreshed",
@@ -79,18 +59,18 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
const metrics = [
{
title: "Total Revenue",
value: `$${data.revenue.total.toLocaleString()}`,
value: formatGBP(data.revenue.total),
description: "All-time revenue",
icon: DollarSign,
trend: data.revenue.monthly > 0 ? "up" : "neutral",
trendValue: `$${data.revenue.monthly.toLocaleString()} this month`
trend: data.revenue.monthly > 0 ? "up" as const : "neutral" as const,
trendValue: `${formatGBP(data.revenue.monthly)} this month`
},
{
title: "Total Orders",
value: data.orders.total.toLocaleString(),
description: "All-time orders",
icon: ShoppingCart,
trend: data.orders.completed > 0 ? "up" : "neutral",
trend: data.orders.completed > 0 ? "up" as const : "neutral" as const,
trendValue: `${data.orders.completed} completed`
},
{
@@ -98,7 +78,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
value: data.customers.unique.toLocaleString(),
description: "Total customers",
icon: Users,
trend: "neutral",
trend: "neutral" as const,
trendValue: "Lifetime customers"
},
{
@@ -106,32 +86,13 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
value: data.products.total.toLocaleString(),
description: "Active products",
icon: Package,
trend: "neutral",
trend: "neutral" as const,
trendValue: "In your store"
}
];
return (
<div className="space-y-6">
{/* Header with refresh button */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-semibold">Performance Overview</h2>
<p className="text-muted-foreground">
Key metrics and insights about your store performance
</p>
</div>
<Button
onClick={refreshData}
disabled={isLoading}
variant="outline"
className="flex items-center gap-2"
>
<RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
Refresh Data
</Button>
</div>
{/* Key Metrics Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{metrics.map((metric) => (

View File

@@ -3,29 +3,11 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { Users, Crown, UserPlus, UserCheck, Star } from "lucide-react";
interface CustomerInsights {
totalCustomers: number;
segments: {
new: number;
returning: number;
loyal: number;
vip: number;
};
topCustomers: Array<{
_id: string;
orderCount: number;
totalSpent: number;
averageOrderValue: number;
firstOrder: string;
lastOrder: string;
}>;
averageOrdersPerCustomer: string;
}
import { getCustomerInsightsWithStore, type CustomerInsights } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
export default function CustomerInsightsChart() {
const [data, setData] = useState<CustomerInsights | null>(null);
@@ -38,7 +20,7 @@ export default function CustomerInsightsChart() {
try {
setIsLoading(true);
setError(null);
const response = await clientFetch<CustomerInsights>('/analytics/customer-insights');
const response = await getCustomerInsightsWithStore();
setData(response);
} catch (err) {
console.error('Error fetching customer insights:', err);
@@ -251,10 +233,10 @@ export default function CustomerInsightsChart() {
</div>
<div className="text-right">
<div className="font-bold text-green-600">
${customer.totalSpent.toFixed(2)}
{formatGBP(customer.totalSpent)}
</div>
<div className="text-sm text-muted-foreground">
${customer.averageOrderValue.toFixed(2)} avg
{formatGBP(customer.averageOrderValue)} avg
</div>
</div>
</div>

View File

@@ -3,27 +3,11 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { BarChart3, Clock, CheckCircle, XCircle, AlertCircle } from "lucide-react";
interface OrderAnalytics {
statusDistribution: Array<{
_id: string;
count: number;
}>;
dailyOrders: Array<{
_id: {
year: number;
month: number;
day: number;
};
orders: number;
revenue: number;
}>;
averageProcessingDays: number;
}
import { getOrderAnalyticsWithStore, type OrderAnalytics } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
interface OrderAnalyticsChartProps {
timeRange: string;
@@ -40,7 +24,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
try {
setIsLoading(true);
setError(null);
const response = await clientFetch<OrderAnalytics>(`/analytics/order-analytics?period=${timeRange}`);
const response = await getOrderAnalyticsWithStore(timeRange);
setData(response);
} catch (err) {
console.error('Error fetching order analytics:', err);
@@ -235,7 +219,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
</div>
<div className="text-center">
<div className="text-2xl font-bold text-purple-600">
${totalRevenue.toFixed(2)}
{formatGBP(totalRevenue)}
</div>
<div className="text-sm text-muted-foreground">Total Revenue</div>
</div>
@@ -247,7 +231,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
const maxOrders = Math.max(...data.dailyOrders.map(d => d.orders));
const height = maxOrders > 0 ? (item.orders / maxOrders) * 100 : 0;
const date = new Date(item._id.year, item._id.month - 1, item._id.day);
const dateLabel = date.toLocaleDateString('en-US', {
const dateLabel = date.toLocaleDateString('en-GB', {
month: 'short',
day: 'numeric'
});
@@ -257,7 +241,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
<div
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
style={{ height: `${height}%` }}
title={`${dateLabel}: ${item.orders} orders, $${item.revenue.toFixed(2)} revenue`}
title={`${dateLabel}: ${item.orders} orders, ${formatGBP(item.revenue)} revenue`}
/>
<div className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
{dateLabel}

View File

@@ -4,23 +4,11 @@ import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { Package, TrendingUp } from "lucide-react";
interface ProductPerformance {
productId: string;
name: string;
image: string;
unitType: string;
currentStock: number;
stockStatus: string;
totalSold: number;
totalRevenue: number;
orderCount: number;
averagePrice: number;
}
import { Package } from "lucide-react";
import { getProductPerformanceWithStore, type ProductPerformance } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
export default function ProductPerformanceChart() {
const [data, setData] = useState<ProductPerformance[]>([]);
@@ -33,7 +21,7 @@ export default function ProductPerformanceChart() {
try {
setIsLoading(true);
setError(null);
const response = await clientFetch<ProductPerformance[]>('/analytics/product-performance');
const response = await getProductPerformanceWithStore();
setData(response);
} catch (err) {
console.error('Error fetching product performance:', err);
@@ -214,13 +202,13 @@ export default function ProductPerformanceChart() {
{product.totalSold.toFixed(2)}
</TableCell>
<TableCell className="text-right font-medium text-green-600">
${product.totalRevenue.toFixed(2)}
{formatGBP(product.totalRevenue)}
</TableCell>
<TableCell className="text-right">
{product.orderCount}
</TableCell>
<TableCell className="text-right">
${product.averagePrice.toFixed(2)}
{formatGBP(product.averagePrice)}
</TableCell>
</TableRow>
))}

View File

@@ -2,20 +2,11 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { TrendingUp, DollarSign } from "lucide-react";
interface RevenueData {
_id: {
year: number;
month: number;
day: number;
};
revenue: number;
orders: number;
}
import { getRevenueTrendsWithStore, type RevenueData } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
interface RevenueChartProps {
timeRange: string;
@@ -32,7 +23,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
try {
setIsLoading(true);
setError(null);
const response = await clientFetch<RevenueData[]>(`/analytics/revenue-trends?period=${timeRange}`);
const response = await getRevenueTrendsWithStore(timeRange);
setData(response);
} catch (err) {
console.error('Error fetching revenue data:', err);
@@ -56,7 +47,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
const formatDate = (item: RevenueData) => {
const date = new Date(item._id.year, item._id.month - 1, item._id.day);
return date.toLocaleDateString('en-US', {
return date.toLocaleDateString('en-GB', {
month: 'short',
day: 'numeric'
});
@@ -153,7 +144,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
<div
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
style={{ height: `${height}%` }}
title={`${formatDate(item)}: $${item.revenue.toFixed(2)}`}
title={`${formatDate(item)}: ${formatGBP(item.revenue)}`}
/>
<div className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
{formatDate(item)}
@@ -167,7 +158,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
<div className="grid grid-cols-3 gap-4 pt-4 border-t">
<div className="text-center">
<div className="text-2xl font-bold text-green-600">
${totalRevenue.toFixed(2)}
{formatGBP(totalRevenue)}
</div>
<div className="text-sm text-muted-foreground">Total Revenue</div>
</div>
@@ -179,7 +170,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
</div>
<div className="text-center">
<div className="text-2xl font-bold text-purple-600">
${averageRevenue.toFixed(2)}
{formatGBP(averageRevenue)}
</div>
<div className="text-sm text-muted-foreground">Avg Daily Revenue</div>
</div>

View File

@@ -0,0 +1,114 @@
"use client"
import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Store, Search } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
export default function StoreSelector() {
const [storeId, setStoreId] = useState('');
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const searchParams = useSearchParams();
const { toast } = useToast();
// Initialize with current storeId from URL
useEffect(() => {
const currentStoreId = searchParams.get('storeId');
if (currentStoreId) {
setStoreId(currentStoreId);
}
}, [searchParams]);
const handleStoreSelect = async () => {
if (!storeId.trim()) {
toast({
title: "Error",
description: "Please enter a store ID",
variant: "destructive",
});
return;
}
setIsLoading(true);
try {
// Navigate to analytics with the selected storeId
router.push(`/dashboard/analytics?storeId=${encodeURIComponent(storeId.trim())}`);
toast({
title: "Store Selected",
description: `Analytics will now show data for store: ${storeId}`,
});
} catch (error) {
toast({
title: "Error",
description: "Failed to switch store",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
handleStoreSelect();
}
};
return (
<Card className="w-full max-w-md mx-auto">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Store className="h-5 w-5" />
Select Store
</CardTitle>
<CardDescription>
Enter the store ID to view analytics for that store
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="storeId">Store ID</Label>
<div className="flex gap-2">
<Input
id="storeId"
type="text"
placeholder="Enter store ID..."
value={storeId}
onChange={(e) => setStoreId(e.target.value)}
onKeyPress={handleKeyPress}
className="flex-1"
/>
<Button
onClick={handleStoreSelect}
disabled={isLoading || !storeId.trim()}
size="icon"
>
<Search className="h-4 w-4" />
</Button>
</div>
</div>
<Button
onClick={handleStoreSelect}
disabled={isLoading || !storeId.trim()}
className="w-full"
>
{isLoading ? "Loading..." : "View Analytics"}
</Button>
{searchParams.get('storeId') && (
<div className="text-sm text-muted-foreground text-center">
Currently viewing: {searchParams.get('storeId')}
</div>
)}
</CardContent>
</Card>
);
}