341 lines
12 KiB
TypeScript
341 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
|
import { useRouter } from "next/navigation";
|
|
import { Users, Wifi, FileText, DollarSign, Ticket, CheckSquare, TrendingUp, Database, RefreshCw } from "lucide-react";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
|
import { Button } from "@/components/ui/Button";
|
|
import { Badge } from "@/components/ui/Badge";
|
|
import { formatCurrency, formatDateTime } from "@/lib/utils";
|
|
import { toast } from "sonner";
|
|
import api from "@/lib/api";
|
|
import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types";
|
|
import {
|
|
LineChart,
|
|
Line,
|
|
XAxis,
|
|
YAxis,
|
|
CartesianGrid,
|
|
Tooltip,
|
|
ResponsiveContainer,
|
|
Legend,
|
|
} from "recharts";
|
|
|
|
interface KpiCardProps {
|
|
title: string;
|
|
value: string | number;
|
|
icon: React.ComponentType<{ className?: string }>;
|
|
color: string;
|
|
subtitle?: string;
|
|
href?: string;
|
|
}
|
|
|
|
function KpiCard({ title, value, icon: Icon, color, subtitle, href }: KpiCardProps) {
|
|
const router = useRouter();
|
|
return (
|
|
<Card
|
|
className={href ? "cursor-pointer hover:shadow-md transition-shadow" : ""}
|
|
onClick={href ? () => router.push(href) : undefined}
|
|
>
|
|
<CardContent className="flex items-center gap-4 py-5">
|
|
<div className={`flex h-12 w-12 items-center justify-center rounded-xl ${color} shrink-0`}>
|
|
<Icon className="h-6 w-6 text-white" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<p className="text-sm font-medium text-gray-500 truncate">{title}</p>
|
|
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
|
{subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>}
|
|
</div>
|
|
{href && (
|
|
<div className="ml-auto text-gray-300 text-xs">→</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
const priorityVariant: Record<string, "danger" | "warning" | "default" | "muted"> = {
|
|
URGENT: "danger",
|
|
urgent: "danger",
|
|
HIGH: "warning",
|
|
high: "warning",
|
|
NORMAL: "default",
|
|
normal: "default",
|
|
MEDIUM: "default",
|
|
medium: "default",
|
|
LOW: "muted",
|
|
low: "muted",
|
|
};
|
|
|
|
// Build mock time-series data from revenue for the chart
|
|
function buildChartData(stats: DashboardSummary | undefined) {
|
|
if (!stats) return [];
|
|
// Create a simple 2-month comparison from revenue data
|
|
const now = new Date();
|
|
const thisMonth = now.toLocaleString("default", { month: "short" });
|
|
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" });
|
|
return [
|
|
{ month: lastMonth, revenue: stats.revenue.lastMonth, clients: stats.subscribers.total },
|
|
{ month: thisMonth, revenue: stats.revenue.thisMonth, clients: stats.subscribers.active },
|
|
];
|
|
}
|
|
|
|
export default function DashboardPage() {
|
|
const router = useRouter();
|
|
|
|
const { data: stats, isLoading: statsLoading, refetch: refetchStats } = useQuery<DashboardSummary>({
|
|
queryKey: ["dashboard-summary"],
|
|
queryFn: async () => {
|
|
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
|
|
return res.data;
|
|
},
|
|
});
|
|
|
|
const { data: ticketsData, refetch: refetchTickets } = useQuery<PaginatedResponse<TicketType>>({
|
|
queryKey: ["recent-tickets"],
|
|
queryFn: async () => {
|
|
const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
|
|
return res.data;
|
|
},
|
|
});
|
|
|
|
const seedMutation = useMutation({
|
|
mutationFn: () => api.post<{ message: string }>("/api/v1/_seed", {}),
|
|
onSuccess: (res) => {
|
|
toast.success(res.data?.message || "Demo data seeded!");
|
|
refetchStats();
|
|
refetchTickets();
|
|
},
|
|
onError: (err: { response?: { data?: { message?: string } } }) => {
|
|
toast.error(err?.response?.data?.message || "Seed failed");
|
|
},
|
|
});
|
|
|
|
const recentTickets = ticketsData?.data ?? [];
|
|
const chartData = buildChartData(stats);
|
|
const hasChartData = chartData.some((d) => d.revenue > 0);
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
|
|
<p className="text-sm text-gray-500 mt-0.5">Overview of your ISP operations</p>
|
|
</div>
|
|
<div className="flex gap-2 flex-wrap justify-end">
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
onClick={() => { refetchStats(); refetchTickets(); }}
|
|
>
|
|
<RefreshCw className="h-4 w-4" />
|
|
Refresh
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="secondary"
|
|
onClick={() => seedMutation.mutate()}
|
|
isLoading={seedMutation.isPending}
|
|
>
|
|
<Database className="h-4 w-4" />
|
|
Seed Demo Data
|
|
</Button>
|
|
<Button size="sm" onClick={() => router.push("/clients")}>
|
|
+ New Client
|
|
</Button>
|
|
<Button size="sm" variant="secondary" onClick={() => router.push("/payments")}>
|
|
+ Record Payment
|
|
</Button>
|
|
<Button size="sm" variant="secondary" onClick={() => router.push("/tickets")}>
|
|
+ New Ticket
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* KPI Cards */}
|
|
{statsLoading ? (
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
|
{[1, 2, 3, 4].map((i) => (
|
|
<Card key={i}>
|
|
<CardContent className="py-5">
|
|
<div className="h-16 animate-pulse bg-gray-100 rounded-lg" />
|
|
</CardContent>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
|
<KpiCard
|
|
title="Total Clients"
|
|
value={stats?.subscribers.total ?? 0}
|
|
icon={Users}
|
|
color="bg-blue-500"
|
|
subtitle={`${stats?.subscribers.active ?? 0} active`}
|
|
href="/clients"
|
|
/>
|
|
<KpiCard
|
|
title="Active Subscriptions"
|
|
value={stats?.subscribers.active ?? 0}
|
|
icon={Wifi}
|
|
color="bg-green-500"
|
|
subtitle={`${stats?.subscribers.suspended ?? 0} suspended`}
|
|
href="/subscriptions"
|
|
/>
|
|
<KpiCard
|
|
title="Overdue Invoices"
|
|
value={stats?.billing.overdueInvoices ?? 0}
|
|
icon={FileText}
|
|
color="bg-red-500"
|
|
subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`}
|
|
href="/invoices?status=OVERDUE"
|
|
/>
|
|
<KpiCard
|
|
title="Monthly Revenue"
|
|
value={formatCurrency(stats?.revenue.thisMonth ?? 0)}
|
|
icon={DollarSign}
|
|
color="bg-purple-500"
|
|
subtitle={
|
|
stats?.revenue.growth != null
|
|
? `${stats.revenue.growth > 0 ? "+" : ""}${stats.revenue.growth.toFixed(1)}% vs last month`
|
|
: "vs last month"
|
|
}
|
|
href="/payments"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* Secondary stats */}
|
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
|
<Card
|
|
className="cursor-pointer hover:shadow-md transition-shadow"
|
|
onClick={() => router.push("/tickets?status=OPEN")}
|
|
>
|
|
<CardContent className="flex items-center gap-3 py-4">
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-50 shrink-0">
|
|
<Ticket className="h-5 w-5 text-amber-600" />
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-gray-500">Open Tickets</p>
|
|
<p className="text-xl font-bold text-gray-900">{stats?.support.openTickets ?? 0}</p>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
<Card
|
|
className="cursor-pointer hover:shadow-md transition-shadow"
|
|
onClick={() => router.push("/tickets?status=IN_PROGRESS")}
|
|
>
|
|
<CardContent className="flex items-center gap-3 py-4">
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 shrink-0">
|
|
<TrendingUp className="h-5 w-5 text-blue-600" />
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-gray-500">In-Progress Tickets</p>
|
|
<p className="text-xl font-bold text-gray-900">{stats?.support.inProgressTickets ?? 0}</p>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
<Card
|
|
className="cursor-pointer hover:shadow-md transition-shadow"
|
|
onClick={() => router.push("/tasks")}
|
|
>
|
|
<CardContent className="flex items-center gap-3 py-4">
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-50 shrink-0">
|
|
<CheckSquare className="h-5 w-5 text-green-600" />
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-gray-500">Pending Tasks</p>
|
|
<p className="text-xl font-bold text-gray-900">{stats?.tasks.pending ?? 0}</p>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
{/* Revenue Chart */}
|
|
{!statsLoading && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Revenue Overview</CardTitle>
|
|
</CardHeader>
|
|
<CardContent>
|
|
{hasChartData ? (
|
|
<ResponsiveContainer width="100%" height={220}>
|
|
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
|
|
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
|
|
<XAxis dataKey="month" tick={{ fontSize: 12 }} />
|
|
<YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `₱${(v / 1000).toFixed(0)}k`} />
|
|
<Tooltip formatter={(v) => formatCurrency(Number(v))} />
|
|
<Legend />
|
|
<Line
|
|
type="monotone"
|
|
dataKey="revenue"
|
|
stroke="#3b82f6"
|
|
strokeWidth={2}
|
|
dot={{ r: 4 }}
|
|
name="Revenue"
|
|
/>
|
|
</LineChart>
|
|
</ResponsiveContainer>
|
|
) : (
|
|
<div className="flex flex-col items-center justify-center h-32 text-gray-400">
|
|
<TrendingUp className="h-8 w-8 mb-2 opacity-40" />
|
|
<p className="text-sm">Revenue data will appear once payments are recorded.</p>
|
|
<Button
|
|
size="sm"
|
|
variant="secondary"
|
|
className="mt-3"
|
|
onClick={() => seedMutation.mutate()}
|
|
isLoading={seedMutation.isPending}
|
|
>
|
|
<Database className="h-4 w-4" />
|
|
Seed Demo Data
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Recent Tickets */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Recent Tickets</CardTitle>
|
|
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>
|
|
View all →
|
|
</Button>
|
|
</CardHeader>
|
|
<CardContent className="p-0">
|
|
{recentTickets.length === 0 ? (
|
|
<div className="py-10 text-center text-gray-400 text-sm">No tickets yet</div>
|
|
) : (
|
|
<div className="divide-y divide-gray-50">
|
|
{recentTickets.map((ticket) => (
|
|
<div
|
|
key={ticket.id}
|
|
className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 cursor-pointer transition-colors"
|
|
onClick={() => router.push("/tickets")}
|
|
>
|
|
<div>
|
|
<p className="text-sm font-medium text-gray-800">{ticket.subject}</p>
|
|
<p className="text-xs text-gray-400 mt-0.5">
|
|
{ticket.client
|
|
? `${ticket.client.firstName} ${ticket.client.lastName}`
|
|
: "No client"}{" "}
|
|
• {formatDateTime(ticket.createdAt)}
|
|
</p>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Badge variant={priorityVariant[ticket.priority] ?? "muted"}>
|
|
{ticket.priority}
|
|
</Badge>
|
|
<Badge variant="muted">{ticket.status}</Badge>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|