restore: tasks, users, settings, dashboard — all original pages recovered from old Docker image

This commit is contained in:
Forge
2026-03-25 16:16:51 +08:00
parent 2b385ba866
commit 380a83283b
4 changed files with 1213 additions and 136 deletions

View File

@@ -1,166 +1,334 @@
'use client';
"use client";
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Users, Wifi, DollarSign, AlertTriangle, Ticket, ClipboardList } from 'lucide-react';
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 DashboardSummary {
subscribers: { total: number; active: number; pending: number; suspended: number };
billing: { unpaidInvoices: number; overdueInvoices: number };
support: { openTickets: number; inProgressTickets: number };
tasks: { pending: number };
revenue: { thisMonth: number; lastMonth: number; trend: number };
leads: { total: number; new: number };
interface KpiCardProps {
title: string;
value: string | number;
icon: React.ComponentType<{ className?: string }>;
color: string;
subtitle?: string;
href?: string;
}
function KpiCard({
label,
value,
sub,
icon: Icon,
color,
isLoading,
}: {
label: string;
value: string;
sub?: string;
icon: React.ElementType;
color: string;
isLoading: boolean;
}) {
function KpiCard({ title, value, icon: Icon, color, subtitle, href }: KpiCardProps) {
const router = useRouter();
return (
<Card className="border shadow-sm">
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-slate-500">{label}</CardTitle>
<div
className="w-9 h-9 rounded-lg flex items-center justify-center"
style={{ backgroundColor: color + '1A' }}
>
<Icon size={18} style={{ color }} />
<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>
</CardHeader>
<CardContent>
{isLoading ? (
<Skeleton className="h-8 w-24" />
) : (
<>
<p className="text-2xl font-bold text-slate-800">{value}</p>
{sub && <p className="text-xs text-slate-500 mt-1">{sub}</p>}
</>
<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 { data, isLoading, error } = useQuery<DashboardSummary>({
queryKey: ['dashboard', 'summary'],
const router = useRouter();
const { data: stats, isLoading: statsLoading, refetch: refetchStats } = useQuery<DashboardSummary>({
queryKey: ["dashboard-summary"],
queryFn: async () => {
const res = await api.get('/api/v1/dashboard/summary');
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
return res.data;
},
});
const fmt = (n: number) => n?.toLocaleString() ?? '—';
const peso = (n: number) =>
'₱' + (n ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
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>
<div className="mb-6">
<h1 className="text-2xl font-bold text-slate-800">Dashboard</h1>
<p className="text-slate-500 text-sm mt-1">Overview of your ISP operations</p>
<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>
{error && (
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
Failed to load dashboard data.
{/* 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>
)}
{/* KPI Row 1 */}
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 mb-4">
<KpiCard
label="Active Subscribers"
value={fmt(data?.subscribers?.active ?? 0)}
sub={`${fmt(data?.subscribers?.total ?? 0)} total · ${fmt(data?.subscribers?.pending ?? 0)} pending`}
icon={Wifi}
color="#059669"
isLoading={isLoading}
/>
<KpiCard
label="Revenue This Month"
value={peso(data?.revenue?.thisMonth ?? 0)}
sub={`Last month: ${peso(data?.revenue?.lastMonth ?? 0)}`}
icon={DollarSign}
color="#0891B2"
isLoading={isLoading}
/>
<KpiCard
label="Overdue Invoices"
value={fmt(data?.billing?.overdueInvoices ?? 0)}
sub={`${fmt(data?.billing?.unpaidInvoices ?? 0)} unpaid total`}
icon={AlertTriangle}
color="#DC2626"
isLoading={isLoading}
/>
</div>
{/* KPI Row 2 */}
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 mb-8">
<KpiCard
label="Open Tickets"
value={fmt(data?.support?.openTickets ?? 0)}
sub={`${fmt(data?.support?.inProgressTickets ?? 0)} in progress`}
icon={Ticket}
color="#7C3AED"
isLoading={isLoading}
/>
<KpiCard
label="Pending Tasks"
value={fmt(data?.tasks?.pending ?? 0)}
sub="Manual tasks awaiting action"
icon={ClipboardList}
color="#D97706"
isLoading={isLoading}
/>
<KpiCard
label="Total Clients"
value={fmt(data?.subscribers?.total ?? 0)}
sub={`${fmt(data?.leads?.new ?? 0)} new leads`}
icon={Users}
color="#0F172A"
isLoading={isLoading}
/>
</div>
{/* Quick stats */}
<Card className="border shadow-sm">
<CardHeader>
<CardTitle className="text-base font-semibold text-slate-700">Subscriber Breakdown</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
{/* 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="grid grid-cols-2 sm:grid-cols-4 gap-4">
{[
{ label: 'Active', value: data?.subscribers?.active ?? 0, color: '#059669' },
{ label: 'Pending', value: data?.subscribers?.pending ?? 0, color: '#D97706' },
{ label: 'Suspended', value: data?.subscribers?.suspended ?? 0, color: '#DC2626' },
{ label: 'Total', value: data?.subscribers?.total ?? 0, color: '#0891B2' },
].map((item) => (
<div key={item.label} className="text-center p-3 rounded-lg bg-slate-50">
<p className="text-2xl font-bold" style={{ color: item.color }}>
{item.value}
</p>
<p className="text-xs text-slate-500 mt-1">{item.label}</p>
<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>