holy fkn airball
This commit is contained in:
@@ -1,40 +1,149 @@
|
|||||||
import AnalyticsDashboard from "@/components/analytics/AnalyticsDashboard";
|
import { Suspense } from 'react';
|
||||||
|
import { cookies } from 'next/headers';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import Dashboard from "@/components/dashboard/dashboard";
|
||||||
|
import AnalyticsDashboard from '@/components/analytics/AnalyticsDashboard';
|
||||||
|
import StoreSelector from '@/components/analytics/StoreSelector';
|
||||||
|
import { getAnalyticsOverviewServer } from '@/lib/server-api';
|
||||||
import { fetchServer } from '@/lib/api';
|
import { fetchServer } from '@/lib/api';
|
||||||
|
import { performance } from 'perf_hooks';
|
||||||
|
import { Info, GitCommit, User, Zap, BarChart3 } from 'lucide-react';
|
||||||
|
import packageJson from '../../../package.json';
|
||||||
|
import { getGitInfo } from '@/lib/utils/git';
|
||||||
|
|
||||||
interface AnalyticsOverview {
|
// Vendor type for consistency
|
||||||
orders: {
|
interface Vendor {
|
||||||
total: number;
|
_id: string;
|
||||||
completed: number;
|
username: string;
|
||||||
pending: number;
|
storeId: string;
|
||||||
completionRate: string;
|
pgpKey: string;
|
||||||
};
|
__v: number;
|
||||||
revenue: {
|
|
||||||
total: number;
|
|
||||||
monthly: number;
|
|
||||||
weekly: number;
|
|
||||||
averageOrderValue: number;
|
|
||||||
};
|
|
||||||
products: {
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
customers: {
|
|
||||||
unique: number;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function AnalyticsPage() {
|
interface User {
|
||||||
const analyticsData = await fetchServer<AnalyticsOverview>("/analytics/overview");
|
vendor: Vendor;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function AnalyticsPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: { storeId?: string };
|
||||||
|
}) {
|
||||||
|
const startTime = performance.now();
|
||||||
|
|
||||||
|
// Check for storeId in query parameters (for staff users)
|
||||||
|
const storeId = searchParams.storeId;
|
||||||
|
|
||||||
|
// Check for storeId in cookies (alternative method for staff users)
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const cookieStoreId = cookieStore.get('storeId')?.value;
|
||||||
|
|
||||||
|
// Use query parameter first, then cookie, then undefined (for vendors)
|
||||||
|
const finalStoreId = storeId || cookieStoreId;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch user data and analytics data in parallel
|
||||||
|
const [userResponse, initialData] = await Promise.all([
|
||||||
|
fetchServer<User>("/auth/me"),
|
||||||
|
getAnalyticsOverviewServer(finalStoreId)
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Get git info using the utility
|
||||||
|
const gitInfo = getGitInfo();
|
||||||
|
|
||||||
|
const endTime = performance.now();
|
||||||
|
const generationTime = (endTime - startTime).toFixed(2);
|
||||||
|
const panelVersion = packageJson.version;
|
||||||
|
const commitHash = gitInfo.hash;
|
||||||
|
|
||||||
|
const vendor = userResponse.vendor;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<Dashboard>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
{/* Analytics Content */}
|
||||||
<h1 className="text-3xl font-bold text-foreground">Analytics Dashboard</h1>
|
<Suspense fallback={
|
||||||
<p className="text-muted-foreground mt-2">
|
<div className="flex items-center justify-center h-64">
|
||||||
Comprehensive insights into your store performance, sales trends, and customer behavior.
|
<div className="text-center">
|
||||||
</p>
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
|
||||||
|
<p className="text-muted-foreground">Loading analytics...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}>
|
||||||
|
<AnalyticsDashboard initialData={initialData} />
|
||||||
|
</Suspense>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<AnalyticsDashboard initialData={analyticsData} />
|
{/* Footer with version info */}
|
||||||
|
<div className="fixed bottom-2 right-2 text-xs text-muted-foreground bg-background/80 backdrop-blur-sm px-2 py-1 rounded border border-border/50 z-50 flex items-center space-x-2">
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Info size={12} className="text-muted-foreground/80" />
|
||||||
|
<span>v{panelVersion}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<User size={12} className="text-muted-foreground/80" />
|
||||||
|
<span>{vendor.username}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<GitCommit size={12} className="text-muted-foreground/80" />
|
||||||
|
<span>{commitHash}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Zap size={12} className="text-amber-500" />
|
||||||
|
<span>Generated in {generationTime}ms</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span className="px-1.5 py-0.5 text-xs rounded-sm bg-emerald-500/20 text-emerald-300">
|
||||||
|
{process.env.NODE_ENV || 'development'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Dashboard>
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching analytics data:', error);
|
||||||
|
|
||||||
|
// If it's a 401/403 error, redirect to login
|
||||||
|
if (error instanceof Error && error.message.includes('401')) {
|
||||||
|
redirect('/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it's a 400 error (missing storeId for staff), show store selector
|
||||||
|
if (error instanceof Error && error.message.includes('400')) {
|
||||||
|
return (
|
||||||
|
<Dashboard>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="text-center mb-8">
|
||||||
|
<h1 className="text-3xl font-bold text-foreground mb-4">Analytics Dashboard</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Please select a store to view analytics data.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<StoreSelector />
|
||||||
|
</div>
|
||||||
|
</Dashboard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For other errors, show a fallback
|
||||||
|
return (
|
||||||
|
<Dashboard>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<h1 className="text-3xl font-bold text-foreground mb-4">Analytics Dashboard</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Unable to load analytics data. Please try refreshing the page.
|
||||||
|
</p>
|
||||||
|
{finalStoreId && (
|
||||||
|
<p className="text-sm text-muted-foreground mt-2">
|
||||||
|
Accessing store: {finalStoreId}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Dashboard>
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -17,34 +17,14 @@ import {
|
|||||||
Activity,
|
Activity,
|
||||||
RefreshCw
|
RefreshCw
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { clientFetch } from "@/lib/api";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import RevenueChart from "./RevenueChart";
|
import RevenueChart from "./RevenueChart";
|
||||||
import ProductPerformanceChart from "./ProductPerformanceChart";
|
import ProductPerformanceChart from "./ProductPerformanceChart";
|
||||||
import CustomerInsightsChart from "./CustomerInsightsChart";
|
import CustomerInsightsChart from "./CustomerInsightsChart";
|
||||||
import OrderAnalyticsChart from "./OrderAnalyticsChart";
|
import OrderAnalyticsChart from "./OrderAnalyticsChart";
|
||||||
import MetricsCard from "./MetricsCard";
|
import MetricsCard from "./MetricsCard";
|
||||||
|
import { getAnalyticsOverviewWithStore, type AnalyticsOverview } from "@/lib/services/analytics-service";
|
||||||
interface AnalyticsOverview {
|
import { formatGBP } from "@/utils/format";
|
||||||
orders: {
|
|
||||||
total: number;
|
|
||||||
completed: number;
|
|
||||||
pending: number;
|
|
||||||
completionRate: string;
|
|
||||||
};
|
|
||||||
revenue: {
|
|
||||||
total: number;
|
|
||||||
monthly: number;
|
|
||||||
weekly: number;
|
|
||||||
averageOrderValue: number;
|
|
||||||
};
|
|
||||||
products: {
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
customers: {
|
|
||||||
unique: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AnalyticsDashboardProps {
|
interface AnalyticsDashboardProps {
|
||||||
initialData: AnalyticsOverview;
|
initialData: AnalyticsOverview;
|
||||||
@@ -59,7 +39,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
|||||||
const refreshData = async () => {
|
const refreshData = async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const newData = await clientFetch<AnalyticsOverview>("/analytics/overview");
|
const newData = await getAnalyticsOverviewWithStore();
|
||||||
setData(newData);
|
setData(newData);
|
||||||
toast({
|
toast({
|
||||||
title: "Data refreshed",
|
title: "Data refreshed",
|
||||||
@@ -79,18 +59,18 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
|||||||
const metrics = [
|
const metrics = [
|
||||||
{
|
{
|
||||||
title: "Total Revenue",
|
title: "Total Revenue",
|
||||||
value: `$${data.revenue.total.toLocaleString()}`,
|
value: formatGBP(data.revenue.total),
|
||||||
description: "All-time revenue",
|
description: "All-time revenue",
|
||||||
icon: DollarSign,
|
icon: DollarSign,
|
||||||
trend: data.revenue.monthly > 0 ? "up" : "neutral",
|
trend: data.revenue.monthly > 0 ? "up" as const : "neutral" as const,
|
||||||
trendValue: `$${data.revenue.monthly.toLocaleString()} this month`
|
trendValue: `${formatGBP(data.revenue.monthly)} this month`
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Total Orders",
|
title: "Total Orders",
|
||||||
value: data.orders.total.toLocaleString(),
|
value: data.orders.total.toLocaleString(),
|
||||||
description: "All-time orders",
|
description: "All-time orders",
|
||||||
icon: ShoppingCart,
|
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`
|
trendValue: `${data.orders.completed} completed`
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -98,7 +78,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
|||||||
value: data.customers.unique.toLocaleString(),
|
value: data.customers.unique.toLocaleString(),
|
||||||
description: "Total customers",
|
description: "Total customers",
|
||||||
icon: Users,
|
icon: Users,
|
||||||
trend: "neutral",
|
trend: "neutral" as const,
|
||||||
trendValue: "Lifetime customers"
|
trendValue: "Lifetime customers"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -106,32 +86,13 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
|
|||||||
value: data.products.total.toLocaleString(),
|
value: data.products.total.toLocaleString(),
|
||||||
description: "Active products",
|
description: "Active products",
|
||||||
icon: Package,
|
icon: Package,
|
||||||
trend: "neutral",
|
trend: "neutral" as const,
|
||||||
trendValue: "In your store"
|
trendValue: "In your store"
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<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 */}
|
{/* Key Metrics Cards */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
{metrics.map((metric) => (
|
{metrics.map((metric) => (
|
||||||
|
|||||||
@@ -3,29 +3,11 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { clientFetch } from "@/lib/api";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Users, Crown, UserPlus, UserCheck, Star } from "lucide-react";
|
import { Users, Crown, UserPlus, UserCheck, Star } from "lucide-react";
|
||||||
|
import { getCustomerInsightsWithStore, type CustomerInsights } from "@/lib/services/analytics-service";
|
||||||
interface CustomerInsights {
|
import { formatGBP } from "@/utils/format";
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function CustomerInsightsChart() {
|
export default function CustomerInsightsChart() {
|
||||||
const [data, setData] = useState<CustomerInsights | null>(null);
|
const [data, setData] = useState<CustomerInsights | null>(null);
|
||||||
@@ -38,7 +20,7 @@ export default function CustomerInsightsChart() {
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const response = await clientFetch<CustomerInsights>('/analytics/customer-insights');
|
const response = await getCustomerInsightsWithStore();
|
||||||
setData(response);
|
setData(response);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching customer insights:', err);
|
console.error('Error fetching customer insights:', err);
|
||||||
@@ -251,10 +233,10 @@ export default function CustomerInsightsChart() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<div className="font-bold text-green-600">
|
<div className="font-bold text-green-600">
|
||||||
${customer.totalSpent.toFixed(2)}
|
{formatGBP(customer.totalSpent)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-sm text-muted-foreground">
|
||||||
${customer.averageOrderValue.toFixed(2)} avg
|
{formatGBP(customer.averageOrderValue)} avg
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,27 +3,11 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { clientFetch } from "@/lib/api";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { BarChart3, Clock, CheckCircle, XCircle, AlertCircle } from "lucide-react";
|
import { BarChart3, Clock, CheckCircle, XCircle, AlertCircle } from "lucide-react";
|
||||||
|
import { getOrderAnalyticsWithStore, type OrderAnalytics } from "@/lib/services/analytics-service";
|
||||||
interface OrderAnalytics {
|
import { formatGBP } from "@/utils/format";
|
||||||
statusDistribution: Array<{
|
|
||||||
_id: string;
|
|
||||||
count: number;
|
|
||||||
}>;
|
|
||||||
dailyOrders: Array<{
|
|
||||||
_id: {
|
|
||||||
year: number;
|
|
||||||
month: number;
|
|
||||||
day: number;
|
|
||||||
};
|
|
||||||
orders: number;
|
|
||||||
revenue: number;
|
|
||||||
}>;
|
|
||||||
averageProcessingDays: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OrderAnalyticsChartProps {
|
interface OrderAnalyticsChartProps {
|
||||||
timeRange: string;
|
timeRange: string;
|
||||||
@@ -40,7 +24,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const response = await clientFetch<OrderAnalytics>(`/analytics/order-analytics?period=${timeRange}`);
|
const response = await getOrderAnalyticsWithStore(timeRange);
|
||||||
setData(response);
|
setData(response);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching order analytics:', err);
|
console.error('Error fetching order analytics:', err);
|
||||||
@@ -235,7 +219,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
|
|||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold text-purple-600">
|
<div className="text-2xl font-bold text-purple-600">
|
||||||
${totalRevenue.toFixed(2)}
|
{formatGBP(totalRevenue)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">Total Revenue</div>
|
<div className="text-sm text-muted-foreground">Total Revenue</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -247,7 +231,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
|
|||||||
const maxOrders = Math.max(...data.dailyOrders.map(d => d.orders));
|
const maxOrders = Math.max(...data.dailyOrders.map(d => d.orders));
|
||||||
const height = maxOrders > 0 ? (item.orders / maxOrders) * 100 : 0;
|
const height = maxOrders > 0 ? (item.orders / maxOrders) * 100 : 0;
|
||||||
const date = new Date(item._id.year, item._id.month - 1, item._id.day);
|
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',
|
month: 'short',
|
||||||
day: 'numeric'
|
day: 'numeric'
|
||||||
});
|
});
|
||||||
@@ -257,7 +241,7 @@ export default function OrderAnalyticsChart({ timeRange }: OrderAnalyticsChartPr
|
|||||||
<div
|
<div
|
||||||
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
|
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
|
||||||
style={{ height: `${height}%` }}
|
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">
|
<div className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
|
||||||
{dateLabel}
|
{dateLabel}
|
||||||
|
|||||||
@@ -4,23 +4,11 @@ import { useState, useEffect } from 'react';
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { clientFetch } from "@/lib/api";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Package, TrendingUp } from "lucide-react";
|
import { Package } from "lucide-react";
|
||||||
|
import { getProductPerformanceWithStore, type ProductPerformance } from "@/lib/services/analytics-service";
|
||||||
interface ProductPerformance {
|
import { formatGBP } from "@/utils/format";
|
||||||
productId: string;
|
|
||||||
name: string;
|
|
||||||
image: string;
|
|
||||||
unitType: string;
|
|
||||||
currentStock: number;
|
|
||||||
stockStatus: string;
|
|
||||||
totalSold: number;
|
|
||||||
totalRevenue: number;
|
|
||||||
orderCount: number;
|
|
||||||
averagePrice: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ProductPerformanceChart() {
|
export default function ProductPerformanceChart() {
|
||||||
const [data, setData] = useState<ProductPerformance[]>([]);
|
const [data, setData] = useState<ProductPerformance[]>([]);
|
||||||
@@ -33,7 +21,7 @@ export default function ProductPerformanceChart() {
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const response = await clientFetch<ProductPerformance[]>('/analytics/product-performance');
|
const response = await getProductPerformanceWithStore();
|
||||||
setData(response);
|
setData(response);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching product performance:', err);
|
console.error('Error fetching product performance:', err);
|
||||||
@@ -214,13 +202,13 @@ export default function ProductPerformanceChart() {
|
|||||||
{product.totalSold.toFixed(2)}
|
{product.totalSold.toFixed(2)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="text-right font-medium text-green-600">
|
<TableCell className="text-right font-medium text-green-600">
|
||||||
${product.totalRevenue.toFixed(2)}
|
{formatGBP(product.totalRevenue)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="text-right">
|
<TableCell className="text-right">
|
||||||
{product.orderCount}
|
{product.orderCount}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="text-right">
|
<TableCell className="text-right">
|
||||||
${product.averagePrice.toFixed(2)}
|
{formatGBP(product.averagePrice)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -2,20 +2,11 @@
|
|||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { clientFetch } from "@/lib/api";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { TrendingUp, DollarSign } from "lucide-react";
|
import { TrendingUp, DollarSign } from "lucide-react";
|
||||||
|
import { getRevenueTrendsWithStore, type RevenueData } from "@/lib/services/analytics-service";
|
||||||
interface RevenueData {
|
import { formatGBP } from "@/utils/format";
|
||||||
_id: {
|
|
||||||
year: number;
|
|
||||||
month: number;
|
|
||||||
day: number;
|
|
||||||
};
|
|
||||||
revenue: number;
|
|
||||||
orders: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RevenueChartProps {
|
interface RevenueChartProps {
|
||||||
timeRange: string;
|
timeRange: string;
|
||||||
@@ -32,7 +23,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const response = await clientFetch<RevenueData[]>(`/analytics/revenue-trends?period=${timeRange}`);
|
const response = await getRevenueTrendsWithStore(timeRange);
|
||||||
setData(response);
|
setData(response);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching revenue data:', err);
|
console.error('Error fetching revenue data:', err);
|
||||||
@@ -56,7 +47,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
|
|||||||
|
|
||||||
const formatDate = (item: RevenueData) => {
|
const formatDate = (item: RevenueData) => {
|
||||||
const date = new Date(item._id.year, item._id.month - 1, item._id.day);
|
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',
|
month: 'short',
|
||||||
day: 'numeric'
|
day: 'numeric'
|
||||||
});
|
});
|
||||||
@@ -153,7 +144,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
|
|||||||
<div
|
<div
|
||||||
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
|
className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
|
||||||
style={{ height: `${height}%` }}
|
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">
|
<div className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
|
||||||
{formatDate(item)}
|
{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="grid grid-cols-3 gap-4 pt-4 border-t">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold text-green-600">
|
<div className="text-2xl font-bold text-green-600">
|
||||||
${totalRevenue.toFixed(2)}
|
{formatGBP(totalRevenue)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">Total Revenue</div>
|
<div className="text-sm text-muted-foreground">Total Revenue</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -179,7 +170,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold text-purple-600">
|
<div className="text-2xl font-bold text-purple-600">
|
||||||
${averageRevenue.toFixed(2)}
|
{formatGBP(averageRevenue)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">Avg Daily Revenue</div>
|
<div className="text-sm text-muted-foreground">Avg Daily Revenue</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
114
components/analytics/StoreSelector.tsx
Normal file
114
components/analytics/StoreSelector.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
34
lib/api.ts
34
lib/api.ts
@@ -45,6 +45,28 @@ export {
|
|||||||
type ShippingOptionsResponse,
|
type ShippingOptionsResponse,
|
||||||
} from './services/shipping-service';
|
} from './services/shipping-service';
|
||||||
|
|
||||||
|
// Re-export analytics services
|
||||||
|
export {
|
||||||
|
getAnalyticsOverview,
|
||||||
|
getRevenueTrends,
|
||||||
|
getProductPerformance,
|
||||||
|
getCustomerInsights,
|
||||||
|
getOrderAnalytics,
|
||||||
|
getAnalyticsOverviewWithStore,
|
||||||
|
getRevenueTrendsWithStore,
|
||||||
|
getProductPerformanceWithStore,
|
||||||
|
getCustomerInsightsWithStore,
|
||||||
|
getOrderAnalyticsWithStore,
|
||||||
|
getStoreIdForUser,
|
||||||
|
|
||||||
|
// Types
|
||||||
|
type AnalyticsOverview,
|
||||||
|
type RevenueData,
|
||||||
|
type ProductPerformance,
|
||||||
|
type CustomerInsights,
|
||||||
|
type OrderAnalytics,
|
||||||
|
} from './services/analytics-service';
|
||||||
|
|
||||||
// Define the PlatformStats interface to match the expected format
|
// Define the PlatformStats interface to match the expected format
|
||||||
export interface PlatformStats {
|
export interface PlatformStats {
|
||||||
orders: {
|
orders: {
|
||||||
@@ -70,7 +92,17 @@ export {
|
|||||||
fetchServer,
|
fetchServer,
|
||||||
getCustomersServer,
|
getCustomersServer,
|
||||||
getCustomerDetailsServer,
|
getCustomerDetailsServer,
|
||||||
getPlatformStatsServer
|
getPlatformStatsServer,
|
||||||
|
getAnalyticsOverviewServer,
|
||||||
|
getRevenueTrendsServer,
|
||||||
|
getProductPerformanceServer,
|
||||||
|
getCustomerInsightsServer,
|
||||||
|
getOrderAnalyticsServer,
|
||||||
|
type AnalyticsOverview as ServerAnalyticsOverview,
|
||||||
|
type RevenueData as ServerRevenueData,
|
||||||
|
type ProductPerformance as ServerProductPerformance,
|
||||||
|
type CustomerInsights as ServerCustomerInsights,
|
||||||
|
type OrderAnalytics as ServerOrderAnalytics,
|
||||||
} from './server-api';
|
} from './server-api';
|
||||||
|
|
||||||
// Get clientFetch first so we can use it in the compatibility functions
|
// Get clientFetch first so we can use it in the compatibility functions
|
||||||
|
|||||||
@@ -162,3 +162,117 @@ export async function getPlatformStatsServer() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Analytics Types for server-side
|
||||||
|
export 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;
|
||||||
|
};
|
||||||
|
userType?: 'vendor' | 'staff';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RevenueData {
|
||||||
|
_id: {
|
||||||
|
year: number;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
};
|
||||||
|
revenue: number;
|
||||||
|
orders: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductPerformance {
|
||||||
|
productId: string;
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
unitType: string;
|
||||||
|
currentStock: number;
|
||||||
|
stockStatus: string;
|
||||||
|
totalSold: number;
|
||||||
|
totalRevenue: number;
|
||||||
|
orderCount: number;
|
||||||
|
averagePrice: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderAnalytics {
|
||||||
|
statusDistribution: Array<{
|
||||||
|
_id: string;
|
||||||
|
count: number;
|
||||||
|
}>;
|
||||||
|
dailyOrders: Array<{
|
||||||
|
_id: {
|
||||||
|
year: number;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
};
|
||||||
|
orders: number;
|
||||||
|
revenue: number;
|
||||||
|
}>;
|
||||||
|
averageProcessingDays: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server-side analytics functions
|
||||||
|
export const getAnalyticsOverviewServer = async (storeId?: string): Promise<AnalyticsOverview> => {
|
||||||
|
const url = storeId ? `/analytics/overview?storeId=${storeId}` : '/analytics/overview';
|
||||||
|
return fetchServer<AnalyticsOverview>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRevenueTrendsServer = async (period: string = '30', storeId?: string): Promise<RevenueData[]> => {
|
||||||
|
const params = new URLSearchParams({ period });
|
||||||
|
if (storeId) params.append('storeId', storeId);
|
||||||
|
|
||||||
|
const url = `/analytics/revenue-trends?${params.toString()}`;
|
||||||
|
return fetchServer<RevenueData[]>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getProductPerformanceServer = async (storeId?: string): Promise<ProductPerformance[]> => {
|
||||||
|
const url = storeId ? `/analytics/product-performance?storeId=${storeId}` : '/analytics/product-performance';
|
||||||
|
return fetchServer<ProductPerformance[]>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCustomerInsightsServer = async (storeId?: string): Promise<CustomerInsights> => {
|
||||||
|
const url = storeId ? `/analytics/customer-insights?storeId=${storeId}` : '/analytics/customer-insights';
|
||||||
|
return fetchServer<CustomerInsights>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getOrderAnalyticsServer = async (period: string = '30', storeId?: string): Promise<OrderAnalytics> => {
|
||||||
|
const params = new URLSearchParams({ period });
|
||||||
|
if (storeId) params.append('storeId', storeId);
|
||||||
|
|
||||||
|
const url = `/analytics/order-analytics?${params.toString()}`;
|
||||||
|
return fetchServer<OrderAnalytics>(url);
|
||||||
|
};
|
||||||
190
lib/services/analytics-service.ts
Normal file
190
lib/services/analytics-service.ts
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { clientFetch } from '../api-client';
|
||||||
|
|
||||||
|
// Analytics Types
|
||||||
|
export 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;
|
||||||
|
};
|
||||||
|
userType?: 'vendor' | 'staff';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RevenueData {
|
||||||
|
_id: {
|
||||||
|
year: number;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
};
|
||||||
|
revenue: number;
|
||||||
|
orders: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductPerformance {
|
||||||
|
productId: string;
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
unitType: string;
|
||||||
|
currentStock: number;
|
||||||
|
stockStatus: string;
|
||||||
|
totalSold: number;
|
||||||
|
totalRevenue: number;
|
||||||
|
orderCount: number;
|
||||||
|
averagePrice: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderAnalytics {
|
||||||
|
statusDistribution: Array<{
|
||||||
|
_id: string;
|
||||||
|
count: number;
|
||||||
|
}>;
|
||||||
|
dailyOrders: Array<{
|
||||||
|
_id: {
|
||||||
|
year: number;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
};
|
||||||
|
orders: number;
|
||||||
|
revenue: number;
|
||||||
|
}>;
|
||||||
|
averageProcessingDays: 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';
|
||||||
|
return clientFetch<AnalyticsOverview>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get revenue trends data
|
||||||
|
* @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[]> => {
|
||||||
|
const params = new URLSearchParams({ period });
|
||||||
|
if (storeId) params.append('storeId', storeId);
|
||||||
|
|
||||||
|
const url = `/analytics/revenue-trends?${params.toString()}`;
|
||||||
|
return clientFetch<RevenueData[]>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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';
|
||||||
|
return clientFetch<ProductPerformance[]>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get customer insights data
|
||||||
|
* @param storeId Optional storeId for staff users
|
||||||
|
*/
|
||||||
|
export const getCustomerInsights = async (storeId?: string): Promise<CustomerInsights> => {
|
||||||
|
const url = storeId ? `/analytics/customer-insights?storeId=${storeId}` : '/analytics/customer-insights';
|
||||||
|
return clientFetch<CustomerInsights>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get order analytics data
|
||||||
|
* @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> => {
|
||||||
|
const params = new URLSearchParams({ period });
|
||||||
|
if (storeId) params.append('storeId', storeId);
|
||||||
|
|
||||||
|
const url = `/analytics/order-analytics?${params.toString()}`;
|
||||||
|
return clientFetch<OrderAnalytics>(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to determine if user is staff and get storeId
|
||||||
|
export const getStoreIdForUser = (): string | 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');
|
||||||
|
|
||||||
|
if (userType === 'staff' && storeId) {
|
||||||
|
return storeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Enhanced analytics functions that automatically handle storeId for staff users
|
||||||
|
export const getAnalyticsOverviewWithStore = async (): Promise<AnalyticsOverview> => {
|
||||||
|
const storeId = getStoreIdForUser();
|
||||||
|
return getAnalyticsOverview(storeId);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRevenueTrendsWithStore = async (period: string = '30'): Promise<RevenueData[]> => {
|
||||||
|
const storeId = getStoreIdForUser();
|
||||||
|
return getRevenueTrends(period, storeId);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getProductPerformanceWithStore = async (): Promise<ProductPerformance[]> => {
|
||||||
|
const storeId = getStoreIdForUser();
|
||||||
|
return getProductPerformance(storeId);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCustomerInsightsWithStore = async (): Promise<CustomerInsights> => {
|
||||||
|
const storeId = getStoreIdForUser();
|
||||||
|
return getCustomerInsights(storeId);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getOrderAnalyticsWithStore = async (period: string = '30'): Promise<OrderAnalytics> => {
|
||||||
|
const storeId = getStoreIdForUser();
|
||||||
|
return getOrderAnalytics(period, storeId);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function formatGBP(value: number) {
|
||||||
|
return value.toLocaleString('en-GB', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'GBP',
|
||||||
|
minimumFractionDigits: 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -4,3 +4,12 @@ export const formatCurrency = (amount: number): string => {
|
|||||||
currency: 'GBP'
|
currency: 'GBP'
|
||||||
}).format(amount);
|
}).format(amount);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export function formatGBP(value: number) {
|
||||||
|
return value.toLocaleString('en-GB', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'GBP',
|
||||||
|
minimumFractionDigits: 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user