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,126 +1,223 @@
'use client';
"use client";
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ChevronRight, CheckCircle } from 'lucide-react';
import { format } from 'date-fns';
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { RefreshCw, ArrowLeftRight, CheckCircle, Plus } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { formatDate, formatCurrency } from "@/lib/utils";
import api from "@/lib/api";
import { toast } from "sonner";
interface Payment {
id: string; clientId: string; amount: string; channel: string;
paymentDate?: string; createdAt: string;
client?: { firstName: string; lastName: string; accountNumber: string };
}
interface Remittance {
id: string;
totalAmount: string;
notes: string | null;
status: string;
createdAt: string;
collectedBy?: { firstName: string; lastName: string };
confirmedBy?: { firstName: string; lastName: string };
payments?: Array<{ id: string; amount: string }>;
id: string; collectorId?: string;
collector?: { firstName: string; lastName: string };
amount: number | string; notes?: string; status: string;
payments?: Payment[]; createdAt: string;
}
const peso = (v: string | number) =>
'₱' + Number(v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
const statusVariant: Record<string, "success" | "warning" | "muted"> = {
CONFIRMED: "success", PENDING: "warning", DISPUTED: "muted",
};
export default function RemittancesPage() {
const qc = useQueryClient();
const [showSubmit, setShowSubmit] = useState(false);
const [notes, setNotes] = useState("");
const [selectedPaymentIds, setSelectedPaymentIds] = useState<string[]>([]);
const [selected, setSelected] = useState<Remittance | null>(null);
const { data, isLoading } = useQuery<{ data: Remittance[]; total: number }>({
queryKey: ['remittances'],
const { data: remittances = [], isLoading, refetch } = useQuery<Remittance[]>({
queryKey: ["remittances"],
queryFn: async () => {
const res = await api.get('/api/v1/remittances?limit=30');
return res.data;
const res = await api.get("/api/v1/remittances?limit=50");
const d = res.data;
return Array.isArray(d) ? d : d.data ?? [];
},
staleTime: 30_000,
});
const { data: unremitted = [] } = useQuery<Payment[]>({
queryKey: ["unremitted-payments"],
queryFn: async () => {
const res = await api.get<Payment[]>("/api/v1/payments/unremitted");
return Array.isArray(res.data) ? res.data : (res.data as any).data ?? [];
},
enabled: showSubmit,
});
const confirm = useMutation({
mutationFn: async (id: string) => {
await api.patch(`/api/v1/remittances/${id}/confirm`);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ['remittances'] }),
mutationFn: async (id: string) => { await api.patch(`/api/v1/remittances/${id}/confirm`); },
onSuccess: () => { toast.success("Remittance confirmed!"); qc.invalidateQueries({ queryKey: ["remittances"] }); },
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to confirm"),
});
const remittances = data?.data ?? [];
const submitRemittance = useMutation({
mutationFn: async () => {
await api.post("/api/v1/remittances", { paymentIds: selectedPaymentIds, notes: notes || undefined });
},
onSuccess: () => {
toast.success("Remittance submitted!");
setShowSubmit(false);
setSelectedPaymentIds([]);
setNotes("");
qc.invalidateQueries({ queryKey: ["remittances"] });
qc.invalidateQueries({ queryKey: ["unremitted-payments"] });
},
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to submit remittance"),
});
const togglePayment = (id: string) => {
setSelectedPaymentIds(prev =>
prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
);
};
const selectedTotal = unremitted
.filter(p => selectedPaymentIds.includes(p.id))
.reduce((sum, p) => sum + Number(p.amount), 0);
return (
<div>
<div className="mb-6">
<h1 className="text-2xl font-bold text-slate-800">Remittances</h1>
<p className="text-slate-500 text-sm mt-1">Cash collections submitted by collectors</p>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Remittances</h1>
<p className="text-sm text-gray-500 mt-1">{remittances.length} remittances</p>
</div>
<div className="flex gap-2">
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
<Button onClick={() => setShowSubmit(true)} size="sm"><Plus size={14} className="mr-1" />Submit Remittance</Button>
</div>
</div>
<Card className="border shadow-sm">
<Card>
<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">Date</th>
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Collector</th>
<th className="text-right px-4 py-3 font-medium text-slate-500">Amount</th>
<th className="text-right px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Payments</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">Confirmed By</th>
<th className="px-4 py-3"></th>
</tr>
</thead>
<tbody>
{isLoading
? Array.from({ length: 6 }).map((_, i) => (
<tr key={i} className="border-b">
{[...Array(7)].map((_, j) => (
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
))}
</tr>
))
: remittances.map((r) => (
<tr key={r.id} className="border-b hover:bg-slate-50 transition-colors">
<td className="px-4 py-3 text-slate-600">
{r.createdAt ? format(new Date(r.createdAt), 'MMM d, yyyy') : '—'}
</td>
<td className="px-4 py-3 text-slate-700 hidden md:table-cell">
{r.collectedBy ? `${r.collectedBy.firstName} ${r.collectedBy.lastName}` : '—'}
</td>
<td className="px-4 py-3 text-right font-semibold text-slate-800">
{peso(r.totalAmount)}
</td>
<td className="px-4 py-3 text-right text-slate-600 hidden lg:table-cell">
{r.payments?.length ?? '—'}
</td>
<td className="px-4 py-3">
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
r.status === 'CONFIRMED'
? 'bg-green-100 text-green-700'
: 'bg-yellow-100 text-yellow-700'
}`}>
{r.status}
</span>
</td>
<td className="px-4 py-3 text-slate-600 hidden xl:table-cell">
{r.confirmedBy ? `${r.confirmedBy.firstName} ${r.confirmedBy.lastName}` : '—'}
</td>
<td className="px-4 py-3">
{r.status !== 'CONFIRMED' && (
<button
onClick={() => confirm.mutate(r.id)}
disabled={confirm.isPending}
className="flex items-center gap-1 text-xs font-medium text-green-700 hover:text-green-800"
>
<CheckCircle size={14} />
Confirm
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{!isLoading && remittances.length === 0 && (
<div className="text-center py-12 text-slate-400">No remittances yet</div>
)}
<Table>
<TableHead>
<TableRow><Th>Date</Th><Th>Collector</Th><Th>Amount</Th><Th>Status</Th><Th>Notes</Th><Th></Th></TableRow>
</TableHead>
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}><Td colSpan={6}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
))
) : remittances.length === 0 ? (
<EmptyState colSpan={6} message="No remittances yet" icon={<ArrowLeftRight size={24} />} />
) : remittances.map(r => (
<TableRow key={r.id} onClick={() => setSelected(r)} className="cursor-pointer hover:bg-blue-50 transition-colors">
<Td>{formatDate(r.createdAt)}</Td>
<Td className="font-medium">{r.collector ? `${r.collector.firstName} ${r.collector.lastName}` : "—"}</Td>
<Td className="font-semibold text-blue-700">{formatCurrency(Number(r.amount))}</Td>
<Td><Badge variant={statusVariant[r.status] ?? "muted"}>{r.status}</Badge></Td>
<Td className="text-gray-500 text-sm">{r.notes ?? "—"}</Td>
<Td>
{r.status === "PENDING" && (
<Button size="sm" variant="secondary" onClick={e => { e.stopPropagation(); confirm.mutate(r.id); }}>
<CheckCircle size={13} className="mr-1" />Confirm
</Button>
)}
</Td>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
{/* Remittance Detail Modal */}
<Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Remittance Details" className="max-w-lg">
{selected && (
<div className="space-y-4">
<div className="bg-gray-50 rounded-lg p-4 space-y-2 text-sm">
<div className="flex justify-between"><span className="text-gray-500">Collector</span>
<span className="font-medium">{selected.collector ? `${selected.collector.firstName} ${selected.collector.lastName}` : "—"}</span></div>
<div className="flex justify-between"><span className="text-gray-500">Total Amount</span>
<span className="text-lg font-bold text-blue-700">{formatCurrency(Number(selected.amount))}</span></div>
<div className="flex justify-between"><span className="text-gray-500">Status</span>
<Badge variant={statusVariant[selected.status] ?? "muted"}>{selected.status}</Badge></div>
<div className="flex justify-between"><span className="text-gray-500">Date</span>
<span>{formatDate(selected.createdAt)}</span></div>
{selected.notes && <div className="flex justify-between"><span className="text-gray-500">Notes</span><span>{selected.notes}</span></div>}
</div>
{selected.payments && selected.payments.length > 0 && (
<div>
<p className="text-sm font-medium text-gray-700 mb-2">Included Payments ({selected.payments.length})</p>
<div className="space-y-1.5 max-h-48 overflow-y-auto">
{selected.payments.map(p => (
<div key={p.id} className="flex justify-between text-sm bg-white border rounded-lg px-3 py-2">
<span className="text-gray-600">{p.client ? `${p.client.firstName} ${p.client.lastName}` : p.clientId.slice(0, 8)}</span>
<span className="font-medium text-green-700">{formatCurrency(Number(p.amount))}</span>
</div>
))}
</div>
</div>
)}
<div className="flex justify-between pt-1">
{selected.status === "PENDING" && (
<Button size="sm" onClick={() => { confirm.mutate(selected.id); setSelected(null); }} isLoading={confirm.isPending}>
<CheckCircle size={14} className="mr-1" />Confirm
</Button>
)}
<Button variant="outline" size="sm" onClick={() => setSelected(null)} className="ml-auto">Close</Button>
</div>
</div>
)}
</Modal>
{/* Submit Remittance Modal */}
<Modal isOpen={showSubmit} onClose={() => setShowSubmit(false)} title="Submit Remittance" className="max-w-xl">
<div className="space-y-4">
<p className="text-sm text-gray-500">Select payments to include in this remittance.</p>
{unremitted.length === 0 ? (
<div className="text-center py-6 text-gray-400">No unremitted payments available.</div>
) : (
<>
<div className="flex justify-between items-center">
<span className="text-sm font-medium text-gray-700">{unremitted.length} unremitted payments</span>
<button onClick={() => setSelectedPaymentIds(unremitted.map(p => p.id))}
className="text-xs text-blue-600 hover:underline">Select All</button>
</div>
<div className="space-y-1.5 max-h-64 overflow-y-auto border rounded-lg p-2">
{unremitted.map(p => (
<label key={p.id} className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${selectedPaymentIds.includes(p.id) ? "bg-blue-50 border border-blue-200" : "hover:bg-gray-50 border border-transparent"}`}>
<div className="flex items-center gap-2">
<input type="checkbox" checked={selectedPaymentIds.includes(p.id)} onChange={() => togglePayment(p.id)} className="rounded" />
<div>
<p className="text-sm font-medium">{p.client ? `${p.client.firstName} ${p.client.lastName}` : "—"}</p>
<p className="text-xs text-gray-400">{p.channel} · {p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</p>
</div>
</div>
<span className="font-semibold text-green-700 text-sm">{formatCurrency(Number(p.amount))}</span>
</label>
))}
</div>
<div className="bg-blue-50 rounded-lg px-4 py-3 flex justify-between text-sm font-semibold text-blue-800">
<span>{selectedPaymentIds.length} payments selected</span>
<span>{formatCurrency(selectedTotal)}</span>
</div>
</>
)}
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Notes (optional)</label>
<textarea className="border rounded-lg px-3 py-2 text-sm resize-none h-20 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={notes} onChange={e => setNotes(e.target.value)} placeholder="Add any notes..." />
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setShowSubmit(false)}>Cancel</Button>
<Button onClick={() => submitRemittance.mutate()} isLoading={submitRemittance.isPending}
disabled={selectedPaymentIds.length === 0}>
Submit {selectedPaymentIds.length > 0 ? `(${formatCurrency(selectedTotal)})` : ""}
</Button>
</div>
</div>
</Modal>
</div>
);
}