feat: full CRUD on all pages — clients (add+navigate), client detail (payments tab+pay), invoices (detail+pay+void), payments (detail view), remittances (submit flow), tickets (detail+comments+create), leads (add+status update)

This commit is contained in:
Forge
2026-03-25 21:40:30 +08:00
parent 05ed524e47
commit 8ae1e14aee
7 changed files with 1301 additions and 870 deletions

View File

@@ -1,162 +1,166 @@
"use client";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Wifi, FileText, Ticket, RefreshCw } from "lucide-react";
import { ArrowLeft, Wifi, FileText, Ticket, CreditCard, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { Input } from "@/components/ui/Input";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { formatDate, formatCurrency } from "@/lib/utils";
import api from "@/lib/api";
import type { Client, Subscription, Invoice, Ticket as TicketType, PaginatedResponse, LegacyPaginatedResponse } from "@/types";
import { toast } from "sonner";
import type { Client, Subscription, Invoice, Ticket as TicketType, Payment, PaginatedResponse, LegacyPaginatedResponse } from "@/types";
type Tab = "profile" | "subscriptions" | "invoices" | "tickets";
type Tab = "profile" | "subscriptions" | "invoices" | "payments" | "tickets";
const statusColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
active: "success",
ACTIVE: "success",
suspended: "warning",
SUSPENDED: "warning",
cancelled: "danger",
CANCELLED: "danger",
disconnected: "danger",
pending: "muted",
PENDING: "muted",
ACTIVE: "success", active: "success",
SUSPENDED: "warning", suspended: "warning",
CANCELLED: "danger", cancelled: "danger",
DISCONNECTED: "danger",
PENDING: "muted", pending: "muted",
};
const invColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
PAID: "success", paid: "success",
PARTIAL: "warning", partial: "warning",
OVERDUE: "danger", overdue: "danger",
SENT: "muted", DRAFT: "muted", VOID: "muted",
};
const channelColors: Record<string, string> = {
CASH: "bg-green-100 text-green-700",
GCASH: "bg-blue-100 text-blue-700",
MAYA: "bg-purple-100 text-purple-700",
BANK_TRANSFER: "bg-yellow-100 text-yellow-700",
CHECK: "bg-gray-100 text-gray-700",
};
export default function ClientDetailPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const qc = useQueryClient();
const [activeTab, setActiveTab] = useState<Tab>("profile");
const [payInvoice, setPayInvoice] = useState<Invoice | null>(null);
const [payForm, setPayForm] = useState({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });
const { data: client, isLoading, refetch: refetchClient } = useQuery<Client>({
queryKey: ["client", id],
queryFn: async () => {
const res = await api.get<Client>(`/api/v1/clients/${id}`);
return res.data;
},
queryFn: async () => { const r = await api.get<Client>(`/api/v1/clients/${id}`); return r.data; },
});
const { data: subscriptions, isError: subsError } = useQuery<Subscription[]>({
queryKey: ["client-subscriptions", id],
queryFn: async () => {
const res = await api.get<Subscription[]>(`/api/v1/clients/${id}/subscriptions`);
return Array.isArray(res.data) ? res.data : [];
},
queryFn: async () => { const r = await api.get<Subscription[]>(`/api/v1/clients/${id}/subscriptions`); return r.data; },
enabled: activeTab === "subscriptions",
retry: false,
});
const { data: invoicesData } = useQuery<LegacyPaginatedResponse<Invoice>>({
const { data: invoicesData, refetch: refetchInvoices } = useQuery<LegacyPaginatedResponse<Invoice>>({
queryKey: ["client-invoices", id],
queryFn: async () => {
const res = await api.get<LegacyPaginatedResponse<Invoice>>(`/api/v1/invoices?clientId=${id}&page=1&limit=20`);
return res.data;
},
queryFn: async () => { const r = await api.get<LegacyPaginatedResponse<Invoice>>(`/api/v1/invoices?clientId=${id}&page=1&limit=30`); return r.data; },
enabled: activeTab === "invoices",
});
const { data: paymentsData } = useQuery<LegacyPaginatedResponse<Payment>>({
queryKey: ["client-payments", id],
queryFn: async () => {
const r = await api.get<LegacyPaginatedResponse<Payment>>(`/api/v1/payments?clientId=${id}&page=1&limit=30`);
return r.data;
},
enabled: activeTab === "payments",
});
const { data: ticketsData } = useQuery<PaginatedResponse<TicketType>>({
queryKey: ["client-tickets", id],
queryFn: async () => {
const res = await api.get<PaginatedResponse<TicketType>>(`/api/v1/tickets?clientId=${id}&page=1&limit=20`);
return res.data;
},
queryFn: async () => { const r = await api.get<PaginatedResponse<TicketType>>(`/api/v1/tickets?clientId=${id}&page=1&limit=20`); return r.data; },
enabled: activeTab === "tickets",
});
const tabs: { key: Tab; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
{ key: "profile", label: "Profile", icon: ArrowLeft },
{ key: "subscriptions", label: "Subscriptions", icon: Wifi },
{ key: "invoices", label: "Invoices", icon: FileText },
{ key: "tickets", label: "Tickets", icon: Ticket },
const recordPayment = useMutation({
mutationFn: async () => {
await api.post("/api/v1/payments", {
clientId: id, invoiceId: payInvoice?.id,
amount: Number(payForm.amount), channel: payForm.channel,
referenceNumber: payForm.referenceNumber || undefined,
notes: payForm.notes || undefined,
paymentDate: new Date().toISOString(),
});
},
onSuccess: () => {
toast.success("Payment recorded!");
setPayInvoice(null);
setPayForm({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });
qc.invalidateQueries({ queryKey: ["client-invoices", id] });
qc.invalidateQueries({ queryKey: ["client-payments", id] });
refetchInvoices();
},
onError: (e: any) => toast.error(e.response?.data?.message ?? "Payment failed"),
});
const tabs = [
{ key: "profile" as Tab, label: "Profile" },
{ key: "subscriptions" as Tab, label: "Subscriptions" },
{ key: "invoices" as Tab, label: "Invoices" },
{ key: "payments" as Tab, label: "Payments" },
{ key: "tickets" as Tab, label: "Tickets" },
];
if (isLoading) {
return (
<div className="space-y-4">
<div className="h-8 w-48 animate-pulse bg-gray-200 rounded" />
<Card>
<CardContent className="py-10">
<div className="h-32 animate-pulse bg-gray-100 rounded-lg" />
</CardContent>
</Card>
</div>
);
}
if (isLoading) return (
<div className="space-y-4">
<div className="h-8 w-48 animate-pulse bg-gray-200 rounded" />
<Card><CardContent className="py-10"><div className="h-32 animate-pulse bg-gray-100 rounded-lg" /></CardContent></Card>
</div>
);
if (!client) {
return (
<div className="text-center py-20 text-gray-400">
<p>Client not found</p>
<Button variant="secondary" className="mt-4" onClick={() => router.push("/clients")}>
Back to Clients
</Button>
</div>
);
}
if (!client) return (
<div className="text-center py-20 text-gray-400">
<p>Client not found</p>
<Button variant="secondary" className="mt-4" onClick={() => router.push("/clients")}>Back to Clients</Button>
</div>
);
const sub = client.subscriptions?.[0];
const clientStatus = sub?.status ?? (client.isActive ? "ACTIVE" : "INACTIVE");
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => router.push("/clients")}>
<ArrowLeft className="h-4 w-4" />
<ArrowLeft className="h-4 w-4 mr-1" /> Back
</Button>
<div>
<h1 className="text-2xl font-bold text-gray-900">
{client.firstName} {client.lastName}
</h1>
<p className="text-sm text-gray-500">
{client.accountNumber} {client.area?.name ?? ""}
</p>
</div>
<div className="ml-auto flex items-center gap-2">
<Badge variant={client.isActive ? "success" : "muted"}>
{client.isActive ? "Active" : "Inactive"}
</Badge>
<Button size="sm" variant="outline" onClick={() => refetchClient()}>
<RefreshCw className="h-4 w-4" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold text-gray-900">{client.firstName} {client.lastName}</h1>
<p className="text-sm text-gray-500">{client.accountNumber} · {client.area?.name ?? "No area"}</p>
</div>
<Badge variant={statusColor[clientStatus] ?? "muted"}>{clientStatus}</Badge>
<Button size="sm" variant="outline" onClick={() => refetchClient()}><RefreshCw className="h-4 w-4" /></Button>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200">
{[
{ key: "profile" as Tab, label: "Profile" },
{ key: "subscriptions" as Tab, label: "Subscriptions" },
{ key: "invoices" as Tab, label: "Invoices" },
{ key: "tickets" as Tab, label: "Tickets" },
].map((tab) => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === tab.key
? "border-blue-600 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
{tab.label}
</button>
<div className="flex border-b border-gray-200 overflow-x-auto">
{tabs.map(tab => (
<button key={tab.key} onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 whitespace-nowrap transition-colors ${
activeTab === tab.key ? "border-blue-600 text-blue-600" : "border-transparent text-gray-500 hover:text-gray-700"
}`}>{tab.label}</button>
))}
</div>
{/* Profile Tab */}
{/* Profile */}
{activeTab === "profile" && (
<Card>
<CardHeader>
<CardTitle>Client Profile</CardTitle>
</CardHeader>
<CardHeader><CardTitle>Client Profile</CardTitle></CardHeader>
<CardContent>
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[
{ label: "Account Number", value: client.accountNumber },
{ label: "Full Name", value: `${client.firstName} ${client.lastName}` },
{ label: "Email", value: client.email },
{ label: "Email", value: client.email || "—" },
{ label: "Phone", value: client.phone },
{ label: "Address", value: client.address || "—" },
{ label: "Area", value: client.area?.name || "—" },
@@ -173,126 +177,141 @@ export default function ClientDetailPage() {
</Card>
)}
{/* Subscriptions Tab */}
{/* Subscriptions */}
{activeTab === "subscriptions" && (
<Card>
<CardHeader><CardTitle>Subscriptions</CardTitle></CardHeader>
<CardContent className="p-0">
<Table>
<TableHead>
<TableRow>
<Th>Plan</Th>
<Th>Status</Th>
<Th>Start Date</Th>
<Th>Monthly Rate</Th>
</TableRow>
</TableHead>
<TableHead><TableRow><Th>Plan</Th><Th>Type</Th><Th>Status</Th><Th>Start Date</Th><Th>Monthly Rate</Th></TableRow></TableHead>
<TableBody>
{subsError ? (
<tr><td colSpan={4} className="py-8 text-center text-gray-400 text-sm">No data yet</td></tr>
) : !subscriptions || subscriptions.length === 0 ? (
<EmptyState message="No subscriptions yet" />
) : (
subscriptions.map((sub) => (
<TableRow key={sub.id} className="hover:bg-gray-50 transition-colors">
<Td className="font-medium">{sub.plan?.name ?? sub.planId}</Td>
<Td>
<Badge variant={statusColor[sub.status] ?? "muted"}>
{sub.status}
</Badge>
</Td>
{!subscriptions || subscriptions.length === 0 ? <EmptyState message="No subscriptions" /> :
subscriptions.map(sub => (
<TableRow key={sub.id}>
<Td className="font-medium">{sub.plan?.name ?? "—"}</Td>
<Td><Badge variant="muted">{sub.type ?? sub.plan?.type ?? "—"}</Badge></Td>
<Td><Badge variant={statusColor[sub.status] ?? "muted"}>{sub.status}</Badge></Td>
<Td>{formatDate(sub.startDate)}</Td>
<Td>{formatCurrency(sub.plan?.monthlyPrice ?? sub.monthlyRate ?? sub.mrc ?? 0)}</Td>
</TableRow>
))
)}
}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* Invoices Tab */}
{/* Invoices */}
{activeTab === "invoices" && (
<Card>
<CardHeader><CardTitle>Invoices</CardTitle></CardHeader>
<CardContent className="p-0">
<Table>
<TableHead>
<TableRow>
<Th>Invoice #</Th>
<Th>Amount</Th>
<Th>Due Date</Th>
<Th>Status</Th>
</TableRow>
</TableHead>
<TableHead><TableRow><Th>Invoice #</Th><Th>Total</Th><Th>Balance</Th><Th>Due Date</Th><Th>Status</Th><Th></Th></TableRow></TableHead>
<TableBody>
{!invoicesData?.data || invoicesData.data.length === 0 ? (
<EmptyState message="No invoices yet" />
) : (
invoicesData.data.map((inv) => (
{!invoicesData?.data || invoicesData.data.length === 0 ? <EmptyState message="No invoices" /> :
invoicesData.data.map((inv: any) => (
<TableRow key={inv.id}>
<Td className="font-mono text-xs">{inv.invoiceNumber ?? inv.id.slice(0, 8)}</Td>
<Td>{formatCurrency(inv.amount ?? inv.totalAmount ?? 0)}</Td>
<Td>{formatDate(inv.dueDate)}</Td>
<Td>{formatCurrency(Number(inv.total ?? inv.amount ?? 0))}</Td>
<Td className={Number(inv.balance) > 0 ? "text-red-600 font-medium" : "text-gray-500"}>
{formatCurrency(Number(inv.balance ?? 0))}
</Td>
<Td>{inv.dueDate ? formatDate(inv.dueDate) : "—"}</Td>
<Td><Badge variant={invColor[inv.status] ?? "muted"}>{inv.status}</Badge></Td>
<Td>
<Badge
variant={
inv.status === "paid" || inv.status === "PAID" ? "success" :
inv.status === "overdue" || inv.status === "OVERDUE" ? "danger" : "warning"
}
>
{inv.status}
</Badge>
{["SENT", "PARTIAL", "OVERDUE"].includes(inv.status) && (
<Button size="sm" onClick={() => {
setPayInvoice(inv);
setPayForm(f => ({ ...f, amount: String(Number(inv.balance ?? inv.total ?? 0)) }));
}}>Pay</Button>
)}
</Td>
</TableRow>
))
)}
}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* Tickets Tab */}
{activeTab === "tickets" && (
{/* Payments */}
{activeTab === "payments" && (
<Card>
<CardHeader><CardTitle>Tickets</CardTitle></CardHeader>
<CardHeader><CardTitle>Payment History</CardTitle></CardHeader>
<CardContent className="p-0">
<Table>
<TableHead>
<TableRow>
<Th>Subject</Th>
<Th>Type</Th>
<Th>Priority</Th>
<Th>Status</Th>
<Th>Created</Th>
</TableRow>
</TableHead>
<TableHead><TableRow><Th>Date</Th><Th>Amount</Th><Th>Channel</Th><Th>Reference</Th><Th>Notes</Th></TableRow></TableHead>
<TableBody>
{!ticketsData?.data || ticketsData.data.length === 0 ? (
<EmptyState message="No tickets yet" />
) : (
ticketsData.data.map((ticket) => (
<TableRow key={ticket.id}>
<Td className="font-medium">{ticket.subject}</Td>
<Td><Badge variant="muted">{ticket.type}</Badge></Td>
<Td>
<Badge variant={
ticket.priority === "urgent" ? "danger" :
ticket.priority === "high" ? "warning" : "muted"
}>{ticket.priority}</Badge>
</Td>
<Td><Badge variant="default">{ticket.status}</Badge></Td>
<Td className="text-xs text-gray-400">{formatDate(ticket.createdAt)}</Td>
{!paymentsData?.data || paymentsData.data.length === 0 ? <EmptyState message="No payments yet" /> :
paymentsData.data.map((p: any) => (
<TableRow key={p.id}>
<Td className="text-sm">{p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</Td>
<Td className="font-medium text-green-700">{formatCurrency(Number(p.amount))}</Td>
<Td><span className={`px-2 py-0.5 rounded-full text-xs font-medium ${channelColors[p.channel] ?? "bg-gray-100 text-gray-600"}`}>{p.channel}</span></Td>
<Td className="text-xs text-gray-500">{p.referenceNumber ?? p.orNumber ?? "—"}</Td>
<Td className="text-xs text-gray-500">{p.notes ?? "—"}</Td>
</TableRow>
))
)}
}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* Tickets */}
{activeTab === "tickets" && (
<Card>
<CardHeader><CardTitle>Tickets</CardTitle></CardHeader>
<CardContent className="p-0">
<Table>
<TableHead><TableRow><Th>Subject</Th><Th>Type</Th><Th>Priority</Th><Th>Status</Th><Th>Created</Th></TableRow></TableHead>
<TableBody>
{!ticketsData?.data || ticketsData.data.length === 0 ? <EmptyState message="No tickets" /> :
ticketsData.data.map(t => (
<TableRow key={t.id}>
<Td className="font-medium">{t.subject}</Td>
<Td><Badge variant="muted">{t.type}</Badge></Td>
<Td><Badge variant={t.priority === "HIGH" ? "warning" : "muted"}>{t.priority}</Badge></Td>
<Td><Badge variant={t.status === "RESOLVED" ? "success" : t.status === "OPEN" ? "warning" : "muted"}>{t.status}</Badge></Td>
<Td className="text-xs text-gray-400">{formatDate(t.createdAt)}</Td>
</TableRow>
))
}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* Pay Invoice Modal */}
<Modal isOpen={!!payInvoice} onClose={() => setPayInvoice(null)} title={`Record Payment — ${payInvoice?.invoiceNumber ?? ""}`}>
{payInvoice && (
<div className="space-y-4">
<div className="bg-gray-50 rounded-lg p-3 text-sm space-y-1">
<div className="flex justify-between"><span className="text-gray-500">Invoice Total</span><span className="font-medium">{formatCurrency(Number((payInvoice as any).total ?? payInvoice.amount))}</span></div>
<div className="flex justify-between"><span className="text-gray-500">Amount Paid</span><span>{formatCurrency(Number((payInvoice as any).amountPaid ?? 0))}</span></div>
<div className="flex justify-between font-medium text-red-600"><span>Balance Due</span><span>{formatCurrency(Number((payInvoice as any).balance ?? payInvoice.amount))}</span></div>
</div>
<Input label="Amount" type="number" value={payForm.amount} onChange={e => setPayForm(f => ({ ...f, amount: e.target.value }))} />
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Payment Method</label>
<select className="border rounded-lg px-3 py-2 text-sm" value={payForm.channel} onChange={e => setPayForm(f => ({ ...f, channel: e.target.value }))}>
{["CASH","GCASH","MAYA","BANK_TRANSFER","CHECK"].map(c => <option key={c} value={c}>{c}</option>)}
</select>
</div>
<Input label="Reference # (optional)" value={payForm.referenceNumber} onChange={e => setPayForm(f => ({ ...f, referenceNumber: e.target.value }))} />
<Input label="Notes (optional)" value={payForm.notes} onChange={e => setPayForm(f => ({ ...f, notes: e.target.value }))} />
<div className="flex justify-end gap-2 pt-1">
<Button variant="outline" onClick={() => setPayInvoice(null)}>Cancel</Button>
<Button onClick={() => recordPayment.mutate()} isLoading={recordPayment.isPending} disabled={!payForm.amount}>Record Payment</Button>
</div>
</div>
)}
</Modal>
</div>
);
}

View File

@@ -1,192 +1,213 @@
'use client';
"use client";
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Search, UserPlus, ChevronRight } from 'lucide-react';
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { UserPlus, Search, ChevronRight, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Modal } from "@/components/ui/Modal";
import { Badge } from "@/components/ui/Badge";
import api from "@/lib/api";
import { toast } from "sonner";
interface Area { id: string; name: string; }
interface Plan { id: string; name: string; monthlyPrice: number; }
interface Client {
id: string;
accountNumber: string;
firstName: string;
lastName: string;
phone: string;
isActive: boolean;
area: { name: string } | null;
subscriptions: Array<{
status: string;
type: string;
monthlyPrice: string;
plan?: { name: string };
}>;
id: string; accountNumber: string; firstName: string; lastName: string;
phone: string; email: string; address?: string; isActive: boolean;
area: { id: string; name: string } | null;
subscriptions: Array<{ status: string; type: string; monthlyPrice: string; plan?: { name: string }; }>;
}
interface ClientsResponse { data: Client[]; total: number; page: number; limit: number; }
interface ClientsResponse {
data: Client[];
total: number;
page: number;
limit: number;
}
const statusColors: Record<string, string> = {
ACTIVE: 'bg-green-100 text-green-700',
PENDING: 'bg-yellow-100 text-yellow-700',
SUSPENDED: 'bg-red-100 text-red-700',
DISCONNECTED: 'bg-gray-100 text-gray-700',
CANCELLED: 'bg-gray-100 text-gray-500',
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted"> = {
ACTIVE: "success", PENDING: "warning", SUSPENDED: "danger", DISCONNECTED: "muted", CANCELLED: "muted",
};
export default function ClientsPage() {
const [search, setSearch] = useState('');
const router = useRouter();
const qc = useQueryClient();
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [showAdd, setShowAdd] = useState(false);
const [form, setForm] = useState({
firstName: "", lastName: "", email: "", phone: "", address: "",
areaId: "", planId: "", billingType: "POSTPAID",
});
const { data, isLoading } = useQuery<ClientsResponse>({
queryKey: ['clients', search, page],
const { data, isLoading, refetch } = useQuery<ClientsResponse>({
queryKey: ["clients", search, page],
queryFn: async () => {
const params = new URLSearchParams({ page: String(page), limit: '20' });
if (search) params.set('search', search);
const res = await api.get(`/api/v1/clients?${params}`);
const params = new URLSearchParams({ page: String(page), limit: "20" });
if (search) params.set("search", search);
const res = await api.get<ClientsResponse>(`/api/v1/clients?${params}`);
return res.data;
},
staleTime: 30_000,
});
const { data: areas = [] } = useQuery<Area[]>({
queryKey: ["areas"],
queryFn: async () => { const r = await api.get<Area[]>("/api/v1/areas"); return r.data; },
});
const { data: plans = [] } = useQuery<Plan[]>({
queryKey: ["plans"],
queryFn: async () => { const r = await api.get<Plan[]>("/api/v1/plans"); return Array.isArray(r.data) ? r.data : (r.data as any).data ?? []; },
});
const createClient = useMutation({
mutationFn: async () => {
const res = await api.post("/api/v1/clients/onboard", {
firstName: form.firstName, lastName: form.lastName,
email: form.email, phone: form.phone, address: form.address,
areaId: form.areaId || undefined, planId: form.planId,
billingType: form.billingType,
});
return res.data;
},
onSuccess: (data: any) => {
toast.success("Client created successfully!");
qc.invalidateQueries({ queryKey: ["clients"] });
setShowAdd(false);
setForm({ firstName: "", lastName: "", email: "", phone: "", address: "", areaId: "", planId: "", billingType: "POSTPAID" });
if (data?.client?.id) router.push(`/clients/${data.client.id}`);
},
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create client"),
});
const clients = data?.data ?? [];
const total = data?.total ?? 0;
return (
<div>
<div className="flex items-center justify-between mb-6">
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-800">Clients</h1>
<p className="text-slate-500 text-sm mt-1">{total} total clients</p>
<h1 className="text-2xl font-bold text-gray-900">Clients</h1>
<p className="text-sm text-gray-500 mt-1">{total} total clients</p>
</div>
<div className="flex gap-2">
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
<Button onClick={() => setShowAdd(true)} size="sm"><UserPlus size={14} className="mr-1" />Add Client</Button>
</div>
<button
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
style={{ backgroundColor: '#0891B2' }}
>
<UserPlus size={16} />
Add Client
</button>
</div>
{/* Search */}
<div className="relative mb-4">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<Input
placeholder="Search by name or account number..."
className="pl-9"
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
{/* Table */}
<Card className="border shadow-sm">
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-slate-50">
<th className="text-left px-4 py-3 font-medium text-slate-500">Account #</th>
<th className="text-left px-4 py-3 font-medium text-slate-500">Name</th>
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Area</th>
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Plan</th>
<th className="text-left px-4 py-3 font-medium text-slate-500">Status</th>
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Monthly</th>
<th className="px-4 py-3"></th>
</tr>
</thead>
<tbody>
{isLoading
? Array.from({ length: 8 }).map((_, i) => (
<tr key={i} className="border-b">
<td className="px-4 py-3"><Skeleton className="h-4 w-24" /></td>
<td className="px-4 py-3"><Skeleton className="h-4 w-32" /></td>
<td className="px-4 py-3 hidden md:table-cell"><Skeleton className="h-4 w-20" /></td>
<td className="px-4 py-3 hidden lg:table-cell"><Skeleton className="h-4 w-24" /></td>
<td className="px-4 py-3"><Skeleton className="h-5 w-16 rounded-full" /></td>
<td className="px-4 py-3 hidden xl:table-cell"><Skeleton className="h-4 w-16" /></td>
<td className="px-4 py-3"><Skeleton className="h-4 w-4" /></td>
</tr>
))
: clients.map((client) => {
const sub = client.subscriptions?.[0];
const status = sub?.status ?? (client.isActive ? 'ACTIVE' : 'INACTIVE');
return (
<tr
key={client.id}
className="border-b hover:bg-slate-50 cursor-pointer transition-colors"
>
<td className="px-4 py-3 font-mono text-xs text-slate-600">
{client.accountNumber}
</td>
<td className="px-4 py-3 font-medium text-slate-800">
{client.firstName} {client.lastName}
<div className="text-xs text-slate-400">{client.phone}</div>
</td>
<td className="px-4 py-3 text-slate-600 hidden md:table-cell">
{client.area?.name ?? '—'}
</td>
<td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
{sub?.plan?.name ?? (sub ? `${sub.type}` : '—')}
</td>
<td className="px-4 py-3">
<span
className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[status] ?? 'bg-gray-100 text-gray-500'}`}
>
{status}
</span>
</td>
<td className="px-4 py-3 text-slate-600 hidden xl:table-cell">
{sub ? `${Number(sub.monthlyPrice).toLocaleString()}` : '—'}
</td>
<td className="px-4 py-3 text-slate-400">
<ChevronRight size={16} />
</td>
</tr>
);
})}
</tbody>
</table>
<Card>
<CardHeader>
<div className="relative">
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<input
className="w-full pl-9 pr-4 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Search by name or account number..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
{/* Pagination */}
{total > 20 && (
<div className="flex items-center justify-between px-4 py-3 border-t">
<p className="text-sm text-slate-500">
Showing {(page - 1) * 20 + 1}{Math.min(page * 20, total)} of {total}
</p>
<div className="flex gap-2">
<button
disabled={page === 1}
onClick={() => setPage(p => p - 1)}
className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
>
Prev
</button>
<button
disabled={page * 20 >= total}
onClick={() => setPage(p => p + 1)}
className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
>
Next
</button>
</div>
</div>
)}
</CardHeader>
<CardContent className="p-0">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-gray-50">
<th className="text-left px-4 py-3 font-medium text-gray-500">Account #</th>
<th className="text-left px-4 py-3 font-medium text-gray-500">Name</th>
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden md:table-cell">Area</th>
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden lg:table-cell">Plan</th>
<th className="text-left px-4 py-3 font-medium text-gray-500">Status</th>
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden xl:table-cell">Monthly</th>
<th className="px-4 py-3"></th>
</tr>
</thead>
<tbody>
{isLoading ? (
Array.from({ length: 8 }).map((_, i) => (
<tr key={i} className="border-b"><td colSpan={7} className="px-4 py-3"><div className="h-4 bg-gray-100 rounded animate-pulse" /></td></tr>
))
) : clients.map((client) => {
const sub = client.subscriptions?.[0];
const status = sub?.status ?? (client.isActive ? "ACTIVE" : "INACTIVE");
return (
<tr key={client.id} onClick={() => router.push(`/clients/${client.id}`)}
className="border-b hover:bg-blue-50 cursor-pointer transition-colors">
<td className="px-4 py-3 font-mono text-xs text-gray-600">{client.accountNumber}</td>
<td className="px-4 py-3 font-medium text-gray-800">
{client.firstName} {client.lastName}
<div className="text-xs text-gray-400">{client.phone}</div>
</td>
<td className="px-4 py-3 text-gray-600 hidden md:table-cell">{client.area?.name ?? "—"}</td>
<td className="px-4 py-3 text-gray-600 hidden lg:table-cell">{sub?.plan?.name ?? (sub ? sub.type : "—")}</td>
<td className="px-4 py-3">
<Badge variant={statusVariant[status] ?? "muted"}>{status}</Badge>
</td>
<td className="px-4 py-3 text-gray-600 hidden xl:table-cell">
{sub ? `${Number(sub.monthlyPrice).toLocaleString()}` : "—"}
</td>
<td className="px-4 py-3 text-gray-400"><ChevronRight size={16} /></td>
</tr>
);
})}
</tbody>
</table>
{!isLoading && clients.length === 0 && (
<div className="text-center py-12 text-slate-400">
No clients found{search ? ` for "${search}"` : ''}
<div className="text-center py-12 text-gray-400">No clients found{search ? ` for "${search}"` : ""}</div>
)}
{total > 20 && (
<div className="flex items-center justify-between px-4 py-3 border-t text-sm text-gray-500">
<span>Showing {(page - 1) * 20 + 1}{Math.min(page * 20, total)} of {total}</span>
<div className="flex gap-2">
<button disabled={page === 1} onClick={() => setPage(p => p - 1)} className="px-3 py-1 border rounded-md disabled:opacity-40">Prev</button>
<button disabled={page * 20 >= total} onClick={() => setPage(p => p + 1)} className="px-3 py-1 border rounded-md disabled:opacity-40">Next</button>
</div>
</div>
)}
</CardContent>
</Card>
{/* Add Client Modal */}
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add New Client" className="max-w-xl">
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<Input label="First Name" value={form.firstName} onChange={e => setForm(f => ({ ...f, firstName: e.target.value }))} />
<Input label="Last Name" value={form.lastName} onChange={e => setForm(f => ({ ...f, lastName: e.target.value }))} />
</div>
<Input label="Email" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
<Input label="Phone" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
<Input label="Address" value={form.address} onChange={e => setForm(f => ({ ...f, address: e.target.value }))} />
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Area</label>
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
value={form.areaId} onChange={e => setForm(f => ({ ...f, areaId: e.target.value }))}>
<option value=""> Select area </option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Billing Type</label>
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
value={form.billingType} onChange={e => setForm(f => ({ ...f, billingType: e.target.value }))}>
<option value="POSTPAID">Postpaid</option>
<option value="PREPAID">Prepaid</option>
</select>
</div>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Plan <span className="text-red-500">*</span></label>
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
value={form.planId} onChange={e => setForm(f => ({ ...f, planId: e.target.value }))}>
<option value=""> Select plan </option>
{plans.map(p => <option key={p.id} value={p.id}>{p.name} {Number(p.monthlyPrice).toLocaleString()}/mo</option>)}
</select>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={() => setShowAdd(false)}>Cancel</Button>
<Button onClick={() => createClient.mutate()} isLoading={createClient.isPending}
disabled={!form.firstName || !form.lastName || !form.phone || !form.planId}>
Create Client
</Button>
</div>
</div>
</Modal>
</div>
);
}