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

View File

@@ -132,11 +132,17 @@ export default function OrderDetailsPage() {
const results = await Promise.all(responses.map((res) => res)); const results = await Promise.all(responses.map((res) => res));
results.forEach((product, index) => { results.forEach((product, index) => {
productNamesMap[productIds[index]] = product.name || "Unknown Product"; productNamesMap[productIds[index]] = product.name || "Unknown Product (Deleted)";
}); });
} catch (err) { } catch (err) {
console.error("Failed to fetch product names:", 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; return productNamesMap;
}; };
@@ -324,6 +330,20 @@ export default function OrderDetailsPage() {
const productNamesMap = await fetchProductNames(productIds, authToken); const productNamesMap = await fetchProductNames(productIds, authToken);
setProductNames(productNamesMap); 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") { if (data.status === "paid") {
setIsPaid(true); setIsPaid(true);
} }
@@ -603,7 +623,7 @@ export default function OrderDetailsPage() {
{order?.products.map((product) => ( {order?.products.map((product) => (
<TableRow key={product._id}> <TableRow key={product._id}>
<TableCell> <TableCell>
{productNames[product.productId] || "Loading..."} {productNames[product.productId] || "Unknown Product (Deleted)"}
</TableCell> </TableCell>
<TableCell>{product.quantity}</TableCell> <TableCell>{product.quantity}</TableCell>
<TableCell>£{product.pricePerUnit.toFixed(2)}</TableCell> <TableCell>£{product.pricePerUnit.toFixed(2)}</TableCell>

File diff suppressed because it is too large Load Diff