This commit is contained in:
NotII
2025-03-19 14:06:58 +01:00
parent 6bdcb15552
commit 57e196cc6a
3 changed files with 499 additions and 902 deletions

View File

@@ -1,172 +1,161 @@
"use client";
import React, { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
AlertCircle, Users, MessageSquare, BarChart as BarChartIcon, Trash2, Bot, Database,
DollarSign, CreditCard, Landmark, Shield, Tag
} from "lucide-react";
import AdminAnalytics from "@/components/admin/AdminAnalytics";
import React, { useEffect, useState } from "react";
// Example chart library:
// import { LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid } from "recharts";
interface DailyDataPoint {
date: string;
count: number;
}
interface AnalyticsData {
success?: boolean;
orders?: {
total: number;
today: number;
week: number;
dailyOrders: DailyDataPoint[];
};
revenue?: {
total: number;
today: number;
week: number;
dailyRevenue: DailyDataPoint[];
};
vendors?: {
total: number;
newToday: number;
newThisWeek: number;
dailyVendors: DailyDataPoint[];
};
engagement?: {
totalChats: number;
activeChatsToday: number;
dailyChats: DailyDataPoint[];
};
products?: {
total: number;
};
message?: string;
}
export default function AdminDashboardPage() {
const [activeTab, setActiveTab] = useState("overview");
const [isAdmin, setIsAdmin] = useState(false);
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Check if the current user is an admin
const checkAdminStatus = async () => {
const fetchAnalytics = async () => {
try {
// Get auth token from cookies
const token = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (!token) {
setIsAdmin(false);
setLoading(false);
return;
}
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/me`, {
method: "GET",
setLoading(true);
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/admin/analytics`, {
headers: {
Authorization: `Bearer ${token}`,
},
'Authorization': `Bearer ${process.env.NEXT_PUBLIC_JWT_SECRET}`
}
});
const data = await response.json();
// Check if vendor has admin privileges
setIsAdmin(data.vendor?.isAdmin === true);
setAnalytics(data);
} catch (error) {
console.error("Error checking admin status:", error);
setIsAdmin(false);
console.error("Error fetching analytics:", error);
} finally {
setLoading(false);
}
};
checkAdminStatus();
useEffect(() => {
fetchAnalytics();
}, []);
if (loading) {
return <div className="p-4">Loading Admin Dashboard...</div>;
}
if (!analytics?.success) {
return (
<div className="flex justify-center items-center h-screen">
<div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
<div className="p-4">
<h2>Error Fetching Analytics</h2>
<p>{analytics?.message || "Unknown error occurred."}</p>
</div>
);
}
if (!isAdmin) {
return (
<div className="container mx-auto p-6">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Access Denied</AlertTitle>
<AlertDescription>
You do not have permission to access the admin dashboard.
</AlertDescription>
</Alert>
</div>
);
}
// Deconstruct the analytics data
const {
orders,
revenue,
vendors,
engagement,
products,
} = analytics;
return (
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-6">Admin Dashboard</h1>
<div className="p-4">
<h1 className="text-2xl font-bold mb-4">Admin Dashboard</h1>
<Tabs defaultValue="overview" value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid grid-cols-5 w-full mb-6">
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="vendors">Vendors</TabsTrigger>
<TabsTrigger value="bot">Bot Management</TabsTrigger>
<TabsTrigger value="sessions">Sessions</TabsTrigger>
<TabsTrigger value="analytics">Analytics</TabsTrigger>
</TabsList>
<TabsContent value="overview">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("vendors")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Vendor Management</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
View and manage vendors across the platform.
</CardDescription>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("bot")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Bot Management</CardTitle>
<Bot className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
Configure and manage the Telegram bot settings.
</CardDescription>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("sessions")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Session Management</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
Manage active sessions and clear inactive ones.
</CardDescription>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("analytics")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Analytics</CardTitle>
<BarChartIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
View platform statistics and performance metrics.
</CardDescription>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("analytics")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Promotions</CardTitle>
<Tag className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
Track promotion usage and performance metrics.
</CardDescription>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("analytics")}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-md font-medium">Payments & Escrow</CardTitle>
<Landmark className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<CardDescription>
Monitor escrow status and financial operations.
</CardDescription>
</CardContent>
</Card>
{/* Quick stats row */}
<div className="grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-white rounded shadow p-4">
<h2 className="font-bold text-lg mb-2">Total Orders</h2>
<p className="text-xl">{orders?.total || 0}</p>
<p className="text-sm text-gray-600">
Today: {orders?.today || 0} | This Week: {orders?.week || 0}
</p>
</div>
<div className="bg-white rounded shadow p-4">
<h2 className="font-bold text-lg mb-2">Revenue</h2>
<p className="text-xl">£{revenue?.total?.toFixed(2) || 0}</p>
<p className="text-sm text-gray-600">
Today: £{revenue?.today?.toFixed(2) || 0} | This Week: £{revenue?.week?.toFixed(2) || 0}
</p>
</div>
<div className="bg-white rounded shadow p-4">
<h2 className="font-bold text-lg mb-2">Vendors</h2>
<p className="text-xl">{vendors?.total || 0}</p>
<p className="text-sm text-gray-600">
New Today: {vendors?.newToday || 0} | This Week: {vendors?.newThisWeek || 0}
</p>
</div>
<div className="bg-white rounded shadow p-4">
<h2 className="font-bold text-lg mb-2">Chats</h2>
<p className="text-xl">{engagement?.totalChats || 0}</p>
<p className="text-sm text-gray-600">
Active Today: {engagement?.activeChatsToday || 0}
</p>
</div>
<div className="bg-white rounded shadow p-4">
<h2 className="font-bold text-lg mb-2">Products</h2>
<p className="text-xl">{products?.total || 0}</p>
</div>
</div>
{/* Example chart section */}
<div className="mt-8 bg-white p-4 rounded shadow">
<h2 className="text-lg font-bold mb-4">Orders This Week</h2>
{/*
Uncomment and customize if using a chart library like Recharts:
<LineChart
width={800}
height={300}
data={orders?.dailyOrders || []}
margin={{ top: 5, right: 20, left: 10, bottom: 5 }}
>
<CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Line type="monotone" dataKey="count" stroke="#8884d8" />
</LineChart>
*/}
<pre className="text-sm bg-gray-100 p-2 rounded mt-2">
{JSON.stringify(orders?.dailyOrders, null, 2)}
</pre>
</div>
</TabsContent>
<TabsContent value="analytics">
<AdminAnalytics />
</TabsContent>
</Tabs>
</div>
);
}

View File

@@ -132,11 +132,17 @@ export default function OrderDetailsPage() {
const results = await Promise.all(responses.map((res) => res));
results.forEach((product, index) => {
productNamesMap[productIds[index]] = product.name || "Unknown Product";
productNamesMap[productIds[index]] = product.name || "Unknown Product (Deleted)";
});
} catch (err) {
console.error("Failed to fetch product names:", err);
// Initialize product names that failed to load
productIds.forEach(id => {
if (!productNamesMap[id]) {
productNamesMap[id] = "Unknown Product (Deleted)";
}
});
}
return productNamesMap;
};
@@ -324,6 +330,20 @@ export default function OrderDetailsPage() {
const productNamesMap = await fetchProductNames(productIds, authToken);
setProductNames(productNamesMap);
// Add a short timeout to ensure any products still showing as loading
// are marked as deleted/unknown
setTimeout(() => {
setProductNames(prev => {
const newMap = {...prev};
productIds.forEach(id => {
if (!newMap[id] || newMap[id] === "Loading...") {
newMap[id] = "Unknown Product (Deleted)";
}
});
return newMap;
});
}, 3000); // 3 second timeout
if (data.status === "paid") {
setIsPaid(true);
}
@@ -603,7 +623,7 @@ export default function OrderDetailsPage() {
{order?.products.map((product) => (
<TableRow key={product._id}>
<TableCell>
{productNames[product.productId] || "Loading..."}
{productNames[product.productId] || "Unknown Product (Deleted)"}
</TableCell>
<TableCell>{product.quantity}</TableCell>
<TableCell>£{product.pricePerUnit.toFixed(2)}</TableCell>

File diff suppressed because it is too large Load Diff