fix(dashboard): error state, role-gate revenue/chart to ADMIN, remove tasks card, skeleton loaders; add dashboard.spec.ts

This commit is contained in:
Forge
2026-03-26 09:22:04 +08:00
parent 981b415430
commit 562ff9e9b6
2 changed files with 163 additions and 157 deletions

View File

@@ -2,23 +2,17 @@
import { useQuery, useMutation } from "@tanstack/react-query"; import { useQuery, useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation"; 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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button"; import { Button } from "@/components/ui/Button";
import { Badge } from "@/components/ui/Badge"; import { Badge } from "@/components/ui/Badge";
import { formatCurrency, formatDateTime } from "@/lib/utils"; import { formatCurrency, formatDateTime } from "@/lib/utils";
import { useAuthStore } from "@/lib/auth-store";
import { toast } from "sonner"; import { toast } from "sonner";
import api from "@/lib/api"; import api from "@/lib/api";
import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types"; import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types";
import { import {
LineChart, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
} from "recharts"; } from "recharts";
interface KpiCardProps { 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> <p className="text-2xl font-bold text-gray-900">{value}</p>
{subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>} {subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>}
</div> </div>
{href && ( {href && <div className="ml-auto text-gray-300 text-xs"></div>}
<div className="ml-auto text-gray-300 text-xs"></div>
)}
</CardContent> </CardContent>
</Card> </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"> = { const priorityVariant: Record<string, "danger" | "warning" | "default" | "muted"> = {
URGENT: "danger", URGENT: "danger", urgent: "danger",
urgent: "danger", HIGH: "warning", high: "warning",
HIGH: "warning", NORMAL: "default", normal: "default",
high: "warning", MEDIUM: "default", medium: "default",
NORMAL: "default", LOW: "muted", low: "muted",
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) { function buildChartData(stats: DashboardSummary | undefined) {
if (!stats) return []; if (!stats) return [];
// Create a simple 2-month comparison from revenue data
const now = new Date(); const now = new Date();
const thisMonth = now.toLocaleString("default", { month: "short" }); const thisMonth = now.toLocaleString("default", { month: "short" });
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" }); const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" });
return [ return [
{ month: lastMonth, revenue: stats.revenue.lastMonth, clients: stats.subscribers.total }, { month: lastMonth, revenue: stats.revenue.lastMonth },
{ month: thisMonth, revenue: stats.revenue.thisMonth, clients: stats.subscribers.active }, { month: thisMonth, revenue: stats.revenue.thisMonth },
]; ];
} }
export default function DashboardPage() { export default function DashboardPage() {
const router = useRouter(); 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"], queryKey: ["dashboard-summary"],
queryFn: async () => { queryFn: async () => {
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary"); 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"], queryKey: ["recent-tickets"],
queryFn: async () => { queryFn: async () => {
const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5"); const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
@@ -106,7 +127,7 @@ export default function DashboardPage() {
refetchStats(); refetchStats();
refetchTickets(); refetchTickets();
}, },
onError: (err: { response?: { data?: { message?: string } } }) => { onError: (err: any) => {
toast.error(err?.response?.data?.message || "Seed failed"); toast.error(err?.response?.data?.message || "Seed failed");
}, },
}); });
@@ -117,99 +138,60 @@ export default function DashboardPage() {
return ( return (
<div className="space-y-6"> <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> <div>
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1> <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> <p className="text-sm text-gray-500 mt-0.5">Overview of your ISP operations</p>
</div> </div>
<div className="flex gap-2 flex-wrap justify-end"> <div className="flex gap-2 flex-wrap">
<Button <Button size="sm" variant="outline" onClick={() => { refetchStats(); refetchTickets(); }}>
size="sm" <RefreshCw className="h-4 w-4" /> Refresh
variant="outline"
onClick={() => { refetchStats(); refetchTickets(); }}
>
<RefreshCw className="h-4 w-4" />
Refresh
</Button> </Button>
<Button {isAdmin && (
size="sm" <Button size="sm" variant="secondary"
variant="secondary"
onClick={() => seedMutation.mutate()} onClick={() => seedMutation.mutate()}
isLoading={seedMutation.isPending} isLoading={seedMutation.isPending}>
> <Database className="h-4 w-4" /> Seed Demo Data
<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> </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>
</div> </div>
{/* KPI Cards */} {/* KPI Cards */}
{statsLoading ? ( {statsLoading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{[1, 2, 3, 4].map((i) => ( {[1,2,3,4].map(i => <KpiSkeleton key={i} />)}
<Card key={i}>
<CardContent className="py-5">
<div className="h-16 animate-pulse bg-gray-100 rounded-lg" />
</CardContent>
</Card>
))}
</div> </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"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<KpiCard <KpiCard title="Total Clients" value={stats?.subscribers.total ?? 0} icon={Users}
title="Total Clients" color="bg-blue-500" subtitle={`${stats?.subscribers.active ?? 0} active`} href="/clients" />
value={stats?.subscribers.total ?? 0} <KpiCard title="Active Subscriptions" value={stats?.subscribers.active ?? 0} icon={Wifi}
icon={Users} color="bg-green-500" subtitle={`${stats?.subscribers.suspended ?? 0} suspended`} />
color="bg-blue-500" <KpiCard title="Overdue Invoices" value={stats?.billing.overdueInvoices ?? 0} icon={FileText}
subtitle={`${stats?.subscribers.active ?? 0} active`} color="bg-red-500" subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`} href="/invoices" />
href="/clients" {isAdmin && (
/> <KpiCard title="Monthly Revenue" value={formatCurrency(stats?.revenue.thisMonth ?? 0)}
<KpiCard icon={DollarSign} color="bg-purple-500"
title="Active Subscriptions" subtitle={stats?.revenue.growth != null
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` ? `${stats.revenue.growth > 0 ? "+" : ""}${stats.revenue.growth.toFixed(1)}% vs last month`
: "vs last month" : "vs last month"} href="/payments" />
} )}
href="/payments"
/>
</div> </div>
)} )}
{/* Secondary stats */} {/* Secondary stats */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Card <Card className="cursor-pointer hover:shadow-md transition-shadow"
className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => router.push("/tickets")}>
onClick={() => router.push("/tickets?status=OPEN")}
>
<CardContent className="flex items-center gap-3 py-4"> <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"> <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" /> <Ticket className="h-5 w-5 text-amber-600" />
@@ -220,10 +202,8 @@ export default function DashboardPage() {
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
<Card <Card className="cursor-pointer hover:shadow-md transition-shadow"
className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => router.push("/tickets")}>
onClick={() => router.push("/tickets?status=IN_PROGRESS")}
>
<CardContent className="flex items-center gap-3 py-4"> <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"> <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" /> <TrendingUp className="h-5 w-5 text-blue-600" />
@@ -234,24 +214,10 @@ export default function DashboardPage() {
</div> </div>
</CardContent> </CardContent>
</Card> </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> </div>
{/* Revenue Chart */} {/* Revenue Chart — admin only */}
{!statsLoading && ( {isAdmin && !statsLoading && (
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Revenue Overview</CardTitle> <CardTitle>Revenue Overview</CardTitle>
@@ -262,33 +228,17 @@ export default function DashboardPage() {
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}> <LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" /> <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
<XAxis dataKey="month" tick={{ fontSize: 12 }} /> <XAxis dataKey="month" tick={{ fontSize: 12 }} />
<YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `${(v / 1000).toFixed(0)}k`} /> <YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `${(v/1000).toFixed(0)}k`} />
<Tooltip formatter={(v) => formatCurrency(Number(v))} /> <Tooltip formatter={(v) => formatCurrency(Number(v))} />
<Legend /> <Legend />
<Line <Line type="monotone" dataKey="revenue" stroke="#0891B2"
type="monotone" strokeWidth={2} dot={{ r: 4 }} name="Revenue" />
dataKey="revenue"
stroke="#3b82f6"
strokeWidth={2}
dot={{ r: 4 }}
name="Revenue"
/>
</LineChart> </LineChart>
</ResponsiveContainer> </ResponsiveContainer>
) : ( ) : (
<div className="flex flex-col items-center justify-center h-32 text-gray-400"> <div className="flex flex-col items-center justify-center h-32 text-gray-400">
<TrendingUp className="h-8 w-8 mb-2 opacity-40" /> <TrendingUp className="h-8 w-8 mb-2 opacity-40" />
<p className="text-sm">Revenue data will appear once payments are recorded.</p> <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> </div>
)} )}
</CardContent> </CardContent>
@@ -299,34 +249,38 @@ export default function DashboardPage() {
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Recent Tickets</CardTitle> <CardTitle>Recent Tickets</CardTitle>
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}> <Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>View all </Button>
View all
</Button>
</CardHeader> </CardHeader>
<CardContent className="p-0"> <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="py-10 text-center text-gray-400 text-sm">No tickets yet</div>
) : ( ) : (
<div className="divide-y divide-gray-50"> <div className="divide-y divide-gray-50">
{recentTickets.map((ticket) => ( {recentTickets.map((ticket) => (
<div <div key={ticket.id}
key={ticket.id}
className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 cursor-pointer transition-colors" 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> <div>
<p className="text-sm font-medium text-gray-800">{ticket.subject}</p> <p className="text-sm font-medium text-gray-800">{ticket.subject}</p>
<p className="text-xs text-gray-400 mt-0.5"> <p className="text-xs text-gray-400 mt-0.5">
{ticket.client {ticket.client ? `${ticket.client.firstName} ${ticket.client.lastName}` : "No client"}
? `${ticket.client.firstName} ${ticket.client.lastName}` {" • "}{formatDateTime(ticket.createdAt)}
: "No client"}{" "}
{formatDateTime(ticket.createdAt)}
</p> </p>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Badge variant={priorityVariant[ticket.priority] ?? "muted"}> <Badge variant={priorityVariant[ticket.priority] ?? "muted"}>{ticket.priority}</Badge>
{ticket.priority}
</Badge>
<Badge variant="muted">{ticket.status}</Badge> <Badge variant="muted">{ticket.status}</Badge>
</div> </div>
</div> </div>

52
e2e/dashboard.spec.ts Normal file
View 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/);
});
});