fix(dashboard): error state, role-gate revenue/chart to ADMIN, remove tasks card, skeleton loaders; add dashboard.spec.ts
This commit is contained in:
@@ -2,23 +2,17 @@
|
||||
|
||||
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 { Users, Wifi, FileText, DollarSign, Ticket, TrendingUp, Database, RefreshCw, AlertCircle } 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 { useAuthStore } from "@/lib/auth-store";
|
||||
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,
|
||||
LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
|
||||
} from "recharts";
|
||||
|
||||
interface KpiCardProps {
|
||||
@@ -46,44 +40,67 @@ function KpiCard({ title, value, icon: Icon, color, subtitle, href }: KpiCardPro
|
||||
<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>
|
||||
)}
|
||||
{href && <div className="ml-auto text-gray-300 text-xs">→</div>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function KpiSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-4 py-5">
|
||||
<div className="h-12 w-12 rounded-xl skeleton shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="h-3 skeleton rounded w-24" />
|
||||
<div className="h-7 skeleton rounded w-16" />
|
||||
<div className="h-2 skeleton rounded w-20" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-gray-400 gap-3">
|
||||
<AlertCircle className="h-10 w-10 text-red-300" />
|
||||
<p className="text-sm text-gray-500">{message}</p>
|
||||
<Button size="sm" variant="outline" onClick={onRetry}>Retry</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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",
|
||||
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 },
|
||||
{ month: lastMonth, revenue: stats.revenue.lastMonth },
|
||||
{ month: thisMonth, revenue: stats.revenue.thisMonth },
|
||||
];
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const router = useRouter();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isAdmin = user?.roles?.some(r => r.toLowerCase() === "admin" || r.toLowerCase() === "super_admin");
|
||||
|
||||
const { data: stats, isLoading: statsLoading, refetch: refetchStats } = useQuery<DashboardSummary>({
|
||||
const {
|
||||
data: stats,
|
||||
isLoading: statsLoading,
|
||||
isError: statsError,
|
||||
refetch: refetchStats,
|
||||
} = useQuery<DashboardSummary>({
|
||||
queryKey: ["dashboard-summary"],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
|
||||
@@ -91,7 +108,11 @@ export default function DashboardPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const { data: ticketsData, refetch: refetchTickets } = useQuery<PaginatedResponse<TicketType>>({
|
||||
const {
|
||||
data: ticketsData,
|
||||
isLoading: ticketsLoading,
|
||||
refetch: refetchTickets,
|
||||
} = useQuery<PaginatedResponse<TicketType>>({
|
||||
queryKey: ["recent-tickets"],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
|
||||
@@ -106,7 +127,7 @@ export default function DashboardPage() {
|
||||
refetchStats();
|
||||
refetchTickets();
|
||||
},
|
||||
onError: (err: { response?: { data?: { message?: string } } }) => {
|
||||
onError: (err: any) => {
|
||||
toast.error(err?.response?.data?.message || "Seed failed");
|
||||
},
|
||||
});
|
||||
@@ -117,99 +138,60 @@ export default function DashboardPage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||
<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
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<Button size="sm" variant="outline" onClick={() => { refetchStats(); refetchTickets(); }}>
|
||||
<RefreshCw className="h-4 w-4" /> Refresh
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
{isAdmin && (
|
||||
<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
|
||||
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>
|
||||
))}
|
||||
{[1,2,3,4].map(i => <KpiSkeleton key={i} />)}
|
||||
</div>
|
||||
) : statsError ? (
|
||||
<Card><CardContent className="py-2">
|
||||
<ErrorState message="Failed to load dashboard stats." onRetry={refetchStats} />
|
||||
</CardContent></Card>
|
||||
) : (
|
||||
<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
|
||||
<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`} />
|
||||
<KpiCard title="Overdue Invoices" value={stats?.billing.overdueInvoices ?? 0} icon={FileText}
|
||||
color="bg-red-500" subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`} href="/invoices" />
|
||||
{isAdmin && (
|
||||
<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"
|
||||
/>
|
||||
: "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")}
|
||||
>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<Card className="cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => router.push("/tickets")}>
|
||||
<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" />
|
||||
@@ -220,10 +202,8 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card
|
||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => router.push("/tickets?status=IN_PROGRESS")}
|
||||
>
|
||||
<Card className="cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => router.push("/tickets")}>
|
||||
<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" />
|
||||
@@ -234,24 +214,10 @@ export default function DashboardPage() {
|
||||
</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 && (
|
||||
{/* Revenue Chart — admin only */}
|
||||
{isAdmin && !statsLoading && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Revenue Overview</CardTitle>
|
||||
@@ -265,30 +231,14 @@ export default function DashboardPage() {
|
||||
<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"
|
||||
/>
|
||||
<Line type="monotone" dataKey="revenue" stroke="#0891B2"
|
||||
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>
|
||||
@@ -299,34 +249,38 @@ export default function DashboardPage() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Tickets</CardTitle>
|
||||
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>
|
||||
View all →
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>View all →</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{recentTickets.length === 0 ? (
|
||||
{ticketsLoading ? (
|
||||
<div className="divide-y">
|
||||
{[1,2,3].map(i => (
|
||||
<div key={i} className="flex items-center gap-4 px-6 py-3">
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="h-3 skeleton rounded w-48" />
|
||||
<div className="h-2 skeleton rounded w-32" />
|
||||
</div>
|
||||
<div className="h-5 skeleton rounded w-16" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : 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}
|
||||
<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")}
|
||||
>
|
||||
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)}
|
||||
{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={priorityVariant[ticket.priority] ?? "muted"}>{ticket.priority}</Badge>
|
||||
<Badge variant="muted">{ticket.status}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
52
e2e/dashboard.spec.ts
Normal file
52
e2e/dashboard.spec.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { login } from './helpers/auth';
|
||||
|
||||
test.describe('Dashboard', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await login(page);
|
||||
});
|
||||
|
||||
test('dashboard page loads with correct title', async ({ page }) => {
|
||||
await expect(page.locator('h1:has-text("Dashboard")')).toBeVisible();
|
||||
await expect(page.locator('text=Overview of your ISP operations')).toBeVisible();
|
||||
});
|
||||
|
||||
test('KPI cards render after loading', async ({ page }) => {
|
||||
// Wait for skeletons to disappear
|
||||
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||
await expect(page.locator('text=Total Clients')).toBeVisible();
|
||||
await expect(page.locator('text=Active Subscriptions')).toBeVisible();
|
||||
await expect(page.locator('text=Overdue Invoices')).toBeVisible();
|
||||
});
|
||||
|
||||
test('revenue card and chart only visible to admin', async ({ page }) => {
|
||||
// Admin login — revenue card should show
|
||||
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||
await expect(page.locator('text=Monthly Revenue')).toBeVisible();
|
||||
await expect(page.locator('text=Revenue Overview')).toBeVisible();
|
||||
});
|
||||
|
||||
test('recent tickets section renders', async ({ page }) => {
|
||||
await expect(page.locator('text=Recent Tickets')).toBeVisible();
|
||||
await expect(page.locator('text=View all →')).toBeVisible();
|
||||
});
|
||||
|
||||
test('refresh button works without crash', async ({ page }) => {
|
||||
await page.click('button:has-text("Refresh")');
|
||||
// Should not crash — page still has dashboard title
|
||||
await expect(page.locator('h1:has-text("Dashboard")')).toBeVisible();
|
||||
});
|
||||
|
||||
test('New Client button navigates to clients', async ({ page }) => {
|
||||
await page.click('button:has-text("+ New Client")');
|
||||
await expect(page).toHaveURL(/\/clients/);
|
||||
});
|
||||
|
||||
test('KPI card click navigates correctly', async ({ page }) => {
|
||||
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||
// Click Total Clients card
|
||||
const clientsCard = page.locator('text=Total Clients').first();
|
||||
await clientsCard.click();
|
||||
await expect(page).toHaveURL(/\/clients/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user