fix: remove Tasks from sidebar, rebuild Reports with KPIs+charts+tables, fix Settings (billing gracePeriod, Users CRUD with create+role+toggle)
This commit is contained in:
@@ -1,193 +1,262 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { api } from '@/lib/api';
|
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line, CartesianGrid } from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { RefreshCw, TrendingUp, Users, AlertTriangle, DollarSign } from "lucide-react";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';
|
import { Button } from "@/components/ui/Button";
|
||||||
|
import { Badge } from "@/components/ui/Badge";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
const peso = (v: number) => '₱' + (v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
|
const COLORS = ["#0891B2", "#059669", "#F59E0B", "#EF4444", "#8B5CF6", "#EC4899"];
|
||||||
|
|
||||||
|
function KpiCard({ title, value, sub, icon: Icon, color }: { title: string; value: string; sub?: string; icon: any; color: string }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-5">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500">{title}</p>
|
||||||
|
<p className="text-2xl font-bold text-gray-900 mt-1">{value}</p>
|
||||||
|
{sub && <p className="text-xs text-gray-400 mt-0.5">{sub}</p>}
|
||||||
|
</div>
|
||||||
|
<div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: color + "20" }}>
|
||||||
|
<Icon size={20} style={{ color }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function ReportsPage() {
|
export default function ReportsPage() {
|
||||||
const [from, setFrom] = useState(() => {
|
const today = new Date();
|
||||||
const d = new Date();
|
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split("T")[0];
|
||||||
d.setDate(1);
|
const [from, setFrom] = useState(firstOfMonth);
|
||||||
return d.toISOString().split('T')[0];
|
const [to, setTo] = useState(today.toISOString().split("T")[0]);
|
||||||
});
|
|
||||||
const [to, setTo] = useState(() => new Date().toISOString().split('T')[0]);
|
|
||||||
|
|
||||||
const { data: collection, isLoading: collLoading } = useQuery({
|
const { data: collection = [], isLoading: collLoading, refetch: refetchAll } = useQuery({
|
||||||
queryKey: ['reports', 'collection', from, to],
|
queryKey: ["reports-collection", from, to],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get(`/api/v1/reports/collection?from=${from}&to=${to}`);
|
const res = await api.get(`/api/v1/reports/collection?from=${from}&to=${to}`);
|
||||||
return res.data as Array<{ collector: string; totalAmount: number; paymentCount: number }>;
|
return res.data as Array<{ collector: string; totalAmount: number; paymentCount: number }>;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: aging, isLoading: agingLoading } = useQuery({
|
const { data: aging = [] } = useQuery({
|
||||||
queryKey: ['reports', 'aging'],
|
queryKey: ["reports-aging"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get('/api/v1/reports/aging');
|
const res = await api.get("/api/v1/reports/aging");
|
||||||
return res.data as Array<{ bucket: string; invoiceCount: number; totalAmount: number }>;
|
return res.data as Array<{ bucket: string; invoiceCount: number; totalAmount: number }>;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: subscribers, isLoading: subLoading } = useQuery({
|
const { data: subscribers = [] } = useQuery({
|
||||||
queryKey: ['reports', 'subscribers'],
|
queryKey: ["reports-subscribers"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get('/api/v1/reports/subscribers');
|
const res = await api.get("/api/v1/reports/subscribers");
|
||||||
return res.data as Array<{ plan: string; count: number; revenue: number }>;
|
return res.data as Array<{ status: string; count: number; area?: string; plan?: string }>;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: revenue, isLoading: revLoading } = useQuery({
|
const { data: revenue = [] } = useQuery({
|
||||||
queryKey: ['reports', 'revenue'],
|
queryKey: ["reports-revenue"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get('/api/v1/reports/revenue');
|
const res = await api.get("/api/v1/reports/revenue");
|
||||||
return res.data as Array<{ month: string; total: number }>;
|
return (res.data as Array<{ month: string; revenue: number; totalInvoiced: number }>)
|
||||||
|
.filter(r => r.revenue > 0 || r.totalInvoiced > 0)
|
||||||
|
.slice(-12);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Derived KPIs
|
||||||
|
const totalCollected = collection.reduce((s, c) => s + Number(c.totalAmount), 0);
|
||||||
|
const totalPayments = collection.reduce((s, c) => s + c.paymentCount, 0);
|
||||||
|
const totalOutstanding = aging.reduce((s, a) => s + Number(a.totalAmount), 0);
|
||||||
|
const overdueCount = aging.reduce((s, a) => s + a.invoiceCount, 0);
|
||||||
|
|
||||||
|
// Subscriber summary (status-only rows, no area key)
|
||||||
|
const subByStatus = subscribers.filter(s => !s.area && !s.plan);
|
||||||
|
const activeCount = subByStatus.find(s => s.status === "ACTIVE")?.count ?? 0;
|
||||||
|
const pendingCount = subByStatus.find(s => s.status === "PENDING")?.count ?? 0;
|
||||||
|
const suspendedCount = subByStatus.find(s => s.status === "SUSPENDED")?.count ?? 0;
|
||||||
|
const totalSubs = subByStatus.reduce((s, x) => s + x.count, 0);
|
||||||
|
|
||||||
|
// Subscriber by area (rows with area key)
|
||||||
|
const subByArea = subscribers.filter(s => !!s.area);
|
||||||
|
|
||||||
|
const agingRisk: Record<string, string> = { "0-30": "text-yellow-600", "31-60": "text-orange-600", "61-90": "text-red-500", "90+": "text-red-700" };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="mb-6">
|
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Reports</h1>
|
<div>
|
||||||
<p className="text-slate-500 text-sm mt-1">Financial and operational analytics</p>
|
<h1 className="text-2xl font-bold text-gray-900">Reports</h1>
|
||||||
|
<p className="text-sm text-gray-500">Financial and operational analytics</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<label className="text-gray-500">From</label>
|
||||||
|
<input type="date" value={from} onChange={e => setFrom(e.target.value)}
|
||||||
|
className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||||
|
<label className="text-gray-500">To</label>
|
||||||
|
<input type="date" value={to} onChange={e => setTo(e.target.value)}
|
||||||
|
className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => refetchAll()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* KPI Summary */}
|
||||||
|
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
|
<KpiCard title="Total Collected" value={formatCurrency(totalCollected)} sub={`${totalPayments} payments`} icon={DollarSign} color="#059669" />
|
||||||
|
<KpiCard title="Active Subscribers" value={String(activeCount)} sub={`${pendingCount} pending · ${suspendedCount} suspended`} icon={Users} color="#0891B2" />
|
||||||
|
<KpiCard title="Outstanding Balance" value={formatCurrency(totalOutstanding)} sub={`${overdueCount} overdue invoices`} icon={AlertTriangle} color="#EF4444" />
|
||||||
|
<KpiCard title="Total Subscribers" value={String(totalSubs)} sub={`across all statuses`} icon={TrendingUp} color="#8B5CF6" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Collection Report */}
|
{/* Collection Report */}
|
||||||
<Card className="border shadow-sm mb-6">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
<CardHeader className="flex flex-row items-center justify-between pb-3">
|
<Card>
|
||||||
<CardTitle className="text-base font-semibold text-slate-700">Collection Report</CardTitle>
|
<CardHeader><CardTitle>Collection by Collector</CardTitle></CardHeader>
|
||||||
<div className="flex gap-2 items-center">
|
|
||||||
<input type="date" value={from} onChange={(e) => setFrom(e.target.value)}
|
|
||||||
className="border rounded-md px-2 py-1 text-sm text-slate-700" />
|
|
||||||
<span className="text-slate-400 text-sm">to</span>
|
|
||||||
<input type="date" value={to} onChange={(e) => setTo(e.target.value)}
|
|
||||||
className="border rounded-md px-2 py-1 text-sm text-slate-700" />
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{collLoading ? (
|
|
||||||
<Skeleton className="h-32 w-full" />
|
|
||||||
) : !collection?.length ? (
|
|
||||||
<p className="text-center text-slate-400 py-6">No collections in this period</p>
|
|
||||||
) : (
|
|
||||||
<table className="w-full text-sm">
|
|
||||||
<thead>
|
|
||||||
<tr className="border-b">
|
|
||||||
<th className="text-left py-2 font-medium text-slate-500">Collector</th>
|
|
||||||
<th className="text-right py-2 font-medium text-slate-500">Payments</th>
|
|
||||||
<th className="text-right py-2 font-medium text-slate-500">Total</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{collection?.map((row, i) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
<td className="py-2 text-slate-700">{row.collector}</td>
|
|
||||||
<td className="py-2 text-right text-slate-600">{row.paymentCount}</td>
|
|
||||||
<td className="py-2 text-right font-semibold text-slate-800">{peso(row.totalAmount)}</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
<tr className="bg-slate-50">
|
|
||||||
<td className="py-2 font-semibold text-slate-700">Total</td>
|
|
||||||
<td className="py-2 text-right font-semibold text-slate-700">
|
|
||||||
{collection?.reduce((s, r) => s + r.paymentCount, 0)}
|
|
||||||
</td>
|
|
||||||
<td className="py-2 text-right font-semibold text-slate-800">
|
|
||||||
{peso(collection?.reduce((s, r) => s + r.totalAmount, 0) ?? 0)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
|
|
||||||
{/* Revenue Trend */}
|
|
||||||
<Card className="border shadow-sm">
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-base font-semibold text-slate-700">Revenue Trend (12 months)</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{revLoading ? <Skeleton className="h-48 w-full" /> : (
|
{collLoading ? <div className="h-40 animate-pulse bg-gray-100 rounded" /> :
|
||||||
<ResponsiveContainer width="100%" height={200}>
|
collection.length === 0 ? <p className="text-sm text-gray-400 py-6 text-center">No collection data for this period</p> : (
|
||||||
<BarChart data={revenue ?? []}>
|
<>
|
||||||
<XAxis dataKey="month" tick={{ fontSize: 11 }} />
|
<div className="space-y-2 mb-4">
|
||||||
<YAxis tick={{ fontSize: 11 }} tickFormatter={(v) => `₱${(v/1000).toFixed(0)}k`} />
|
{collection.map((c, i) => (
|
||||||
<Tooltip formatter={(v: any) => peso(v)} />
|
<div key={i} className="flex items-center justify-between py-2 border-b last:border-0">
|
||||||
<Bar dataKey="total" fill="#0891B2" radius={[4, 4, 0, 0]} />
|
<div>
|
||||||
</BarChart>
|
<p className="text-sm font-medium text-gray-800">{c.collector}</p>
|
||||||
</ResponsiveContainer>
|
<p className="text-xs text-gray-400">{c.paymentCount} payments</p>
|
||||||
)}
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-sm font-bold text-green-700">{formatCurrency(c.totalAmount)}</p>
|
||||||
|
<p className="text-xs text-gray-400">{totalCollected > 0 ? ((c.totalAmount / totalCollected) * 100).toFixed(1) : 0}%</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between pt-1 font-semibold text-sm">
|
||||||
|
<span>Total</span>
|
||||||
|
<span className="text-green-700">{formatCurrency(totalCollected)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ResponsiveContainer width="100%" height={160}>
|
||||||
|
<BarChart data={collection} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
|
||||||
|
<XAxis dataKey="collector" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis tick={{ fontSize: 11 }} tickFormatter={v => `₱${(v/1000).toFixed(0)}k`} />
|
||||||
|
<Tooltip formatter={(v: any) => formatCurrency(Number(v))} />
|
||||||
|
<Bar dataKey="totalAmount" fill="#0891B2" radius={[4,4,0,0]} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Aging */}
|
{/* Aging Report */}
|
||||||
<Card className="border shadow-sm">
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader><CardTitle>Accounts Receivable Aging</CardTitle></CardHeader>
|
||||||
<CardTitle className="text-base font-semibold text-slate-700">Accounts Receivable Aging</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{agingLoading ? <Skeleton className="h-48 w-full" /> : (
|
<div className="space-y-3">
|
||||||
<div className="space-y-3">
|
{aging.map((a) => (
|
||||||
{aging?.map((bucket) => (
|
<div key={a.bucket} className="flex items-center justify-between p-3 rounded-lg bg-gray-50">
|
||||||
<div key={bucket.bucket} className="flex items-center gap-3">
|
<div>
|
||||||
<span className="text-sm text-slate-500 w-16">{bucket.bucket}d</span>
|
<p className={`text-sm font-semibold ${agingRisk[a.bucket] ?? "text-gray-700"}`}>{a.bucket} days overdue</p>
|
||||||
<div className="flex-1 bg-slate-100 rounded-full h-3 overflow-hidden">
|
<p className="text-xs text-gray-400">{a.invoiceCount} invoice{a.invoiceCount !== 1 ? "s" : ""}</p>
|
||||||
<div
|
|
||||||
className="h-3 rounded-full"
|
|
||||||
style={{
|
|
||||||
width: `${Math.min(100, (bucket.totalAmount / (Math.max(...(aging?.map(b => b.totalAmount) ?? [1])) || 1)) * 100)}%`,
|
|
||||||
backgroundColor: bucket.bucket === '90+' ? '#DC2626' : bucket.bucket === '61-90' ? '#D97706' : '#0891B2',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<span className="text-sm font-medium text-slate-700 w-32 text-right">{peso(bucket.totalAmount)}</span>
|
|
||||||
<span className="text-xs text-slate-400 w-16 text-right">{bucket.invoiceCount} inv</span>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
<div className="text-right">
|
||||||
{!aging?.some(b => b.totalAmount > 0) && (
|
<p className={`text-base font-bold ${a.totalAmount > 0 ? agingRisk[a.bucket] ?? "text-gray-800" : "text-gray-400"}`}>
|
||||||
<p className="text-center text-slate-400 py-6">No overdue invoices 🎉</p>
|
{formatCurrency(a.totalAmount)}
|
||||||
)}
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between px-3 py-2 bg-red-50 rounded-lg font-semibold text-sm">
|
||||||
|
<span className="text-red-700">Total Outstanding</span>
|
||||||
|
<span className="text-red-700">{formatCurrency(totalOutstanding)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Revenue Trend */}
|
||||||
|
{revenue.length > 0 && (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Revenue Trend (Monthly)</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ResponsiveContainer width="100%" height={220}>
|
||||||
|
<LineChart data={revenue} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#F1F5F9" />
|
||||||
|
<XAxis dataKey="month" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis tick={{ fontSize: 11 }} tickFormatter={v => `₱${(v/1000).toFixed(0)}k`} />
|
||||||
|
<Tooltip formatter={(v: any) => formatCurrency(Number(v))} />
|
||||||
|
<Legend />
|
||||||
|
<Line type="monotone" dataKey="revenue" stroke="#059669" strokeWidth={2} dot={false} name="Collected" />
|
||||||
|
<Line type="monotone" dataKey="totalInvoiced" stroke="#0891B2" strokeWidth={2} dot={false} name="Invoiced" strokeDasharray="4 2" />
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Subscribers by Status + Area */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Subscribers by Status</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{subByStatus.length === 0 ? <p className="text-sm text-gray-400 py-4 text-center">No subscriber data</p> : (
|
||||||
|
<div className="flex gap-6 items-center">
|
||||||
|
<ResponsiveContainer width="50%" height={160}>
|
||||||
|
<PieChart>
|
||||||
|
<Pie data={subByStatus} dataKey="count" nameKey="status" cx="50%" cy="50%" outerRadius={60} label={false}>
|
||||||
|
{subByStatus.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip />
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{subByStatus.map((s, i) => (
|
||||||
|
<div key={s.status} className="flex items-center gap-2">
|
||||||
|
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[i % COLORS.length] }} />
|
||||||
|
<span className="text-sm text-gray-700">{s.status}</span>
|
||||||
|
<span className="text-sm font-bold text-gray-900 ml-auto">{s.count}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="border-t pt-1 flex justify-between text-sm font-semibold">
|
||||||
|
<span>Total</span><span>{totalSubs}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Subscribers by Plan */}
|
{subByArea.length > 0 && (
|
||||||
<Card className="border shadow-sm">
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader><CardTitle>Active Subscribers by Area</CardTitle></CardHeader>
|
||||||
<CardTitle className="text-base font-semibold text-slate-700">Subscribers by Plan</CardTitle>
|
<CardContent>
|
||||||
</CardHeader>
|
<div className="space-y-2">
|
||||||
<CardContent>
|
{subByArea.map((a) => (
|
||||||
{subLoading ? <Skeleton className="h-32 w-full" /> : (
|
<div key={a.area} className="flex items-center justify-between py-2 border-b last:border-0">
|
||||||
<table className="w-full text-sm">
|
<span className="text-sm font-medium text-gray-800">{a.area}</span>
|
||||||
<thead>
|
<div className="flex items-center gap-2">
|
||||||
<tr className="border-b">
|
<div className="w-20 bg-gray-100 rounded-full h-2 overflow-hidden">
|
||||||
<th className="text-left py-2 font-medium text-slate-500">Plan</th>
|
<div className="h-2 rounded-full bg-blue-500" style={{ width: `${Math.min(100, (a.count / (activeCount || 1)) * 100)}%` }} />
|
||||||
<th className="text-right py-2 font-medium text-slate-500">Subscribers</th>
|
</div>
|
||||||
<th className="text-right py-2 font-medium text-slate-500">Monthly Revenue</th>
|
<span className="text-sm font-bold text-gray-700 w-6 text-right">{a.count}</span>
|
||||||
</tr>
|
</div>
|
||||||
</thead>
|
</div>
|
||||||
<tbody>
|
|
||||||
{(subscribers as any[])?.map((row: any, i: number) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
<td className="py-2 text-slate-700">{row.plan ?? row.name ?? '—'}</td>
|
|
||||||
<td className="py-2 text-right text-slate-600">{row.count ?? row.subscribers ?? 0}</td>
|
|
||||||
<td className="py-2 text-right font-semibold text-slate-800">
|
|
||||||
{peso(row.revenue ?? row.monthlyRevenue ?? 0)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</div>
|
||||||
</table>
|
</CardContent>
|
||||||
)}
|
</Card>
|
||||||
</CardContent>
|
)}
|
||||||
</Card>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
Building2, CreditCard, Map, Wifi, Users, ChevronRight,
|
Building2, CreditCard, Map, Wifi, Users, ChevronRight,
|
||||||
@@ -128,27 +128,35 @@ function TenantSettings() {
|
|||||||
|
|
||||||
// ─── Sub-page: Billing Settings ───────────────────────────────────────────────
|
// ─── Sub-page: Billing Settings ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface FullBillingSettings {
|
||||||
|
billingDay?: number;
|
||||||
|
gracePeriodDays?: number;
|
||||||
|
lateFeeAmount?: string | number;
|
||||||
|
lateFeePercent?: string | number;
|
||||||
|
lateFeeGraceDays?: number;
|
||||||
|
currency?: string;
|
||||||
|
}
|
||||||
|
|
||||||
function BillingSettings() {
|
function BillingSettings() {
|
||||||
const [billingDay, setBillingDay] = useState("1");
|
const [fields, setFields] = useState({ billingDay: "1", gracePeriodDays: "5", lateFeeAmount: "0", lateFeePercent: "0", lateFeeGraceDays: "0", currency: "PHP" });
|
||||||
const [lateFeeAmount, setLateFeeAmount] = useState("0");
|
|
||||||
const [graceDays, setGraceDays] = useState("0");
|
|
||||||
const [loaded, setLoaded] = useState(false);
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
|
||||||
const { isLoading } = useQuery<TenantBillingSettings>({
|
const { isLoading } = useQuery<FullBillingSettings>({
|
||||||
queryKey: ["tenant-billing-settings"],
|
queryKey: ["tenant-billing-settings"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
try {
|
const res = await api.get<FullBillingSettings>("/api/v1/tenants/me/settings");
|
||||||
const res = await api.get<TenantBillingSettings>("/api/v1/tenants/me/settings");
|
return res.data ?? {};
|
||||||
return res.data ?? {};
|
|
||||||
} catch {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
select: (data) => {
|
select: (data) => {
|
||||||
if (!loaded && data) {
|
if (!loaded && data) {
|
||||||
setBillingDay(String(data.billingDay ?? 1));
|
setFields({
|
||||||
setLateFeeAmount(String(data.lateFeeAmount ?? 0));
|
billingDay: String(data.billingDay ?? 1),
|
||||||
setGraceDays(String(data.lateFeeGraceDays ?? 0));
|
gracePeriodDays: String(data.gracePeriodDays ?? 5),
|
||||||
|
lateFeeAmount: String(data.lateFeeAmount ?? 0),
|
||||||
|
lateFeePercent: String(data.lateFeePercent ?? 0),
|
||||||
|
lateFeeGraceDays: String(data.lateFeeGraceDays ?? 0),
|
||||||
|
currency: data.currency ?? "PHP",
|
||||||
|
});
|
||||||
setLoaded(true);
|
setLoaded(true);
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
@@ -158,60 +166,52 @@ function BillingSettings() {
|
|||||||
const saveMutation = useMutation({
|
const saveMutation = useMutation({
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
await api.patch("/api/v1/tenants/me/settings", {
|
await api.patch("/api/v1/tenants/me/settings", {
|
||||||
billingDay: parseInt(billingDay),
|
billingDay: parseInt(fields.billingDay),
|
||||||
lateFeeAmount: parseFloat(lateFeeAmount),
|
gracePeriodDays: parseInt(fields.gracePeriodDays),
|
||||||
lateFeeGraceDays: parseInt(graceDays),
|
lateFeeAmount: parseFloat(fields.lateFeeAmount),
|
||||||
|
lateFeePercent: parseFloat(fields.lateFeePercent),
|
||||||
|
lateFeeGraceDays: parseInt(fields.lateFeeGraceDays),
|
||||||
|
currency: fields.currency,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onSuccess: () => toast.success("Billing settings saved"),
|
onSuccess: () => toast.success("Billing settings saved"),
|
||||||
onError: () => toast.error("Failed to save. Endpoint may not be available yet."),
|
onError: () => toast.error("Failed to save billing settings"),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isLoading) {
|
const set = (key: keyof typeof fields) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
|
||||||
return <div className="h-40 animate-pulse bg-gray-100 rounded-xl" />;
|
setFields(f => ({ ...f, [key]: e.target.value }));
|
||||||
}
|
|
||||||
|
if (isLoading) return <div className="h-40 animate-pulse bg-gray-100 rounded-xl" />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader><CardTitle>Billing Configuration</CardTitle></CardHeader>
|
<CardHeader><CardTitle>Billing Configuration</CardTitle></CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form
|
<form onSubmit={(e) => { e.preventDefault(); saveMutation.mutate(); }} className="space-y-4 max-w-lg">
|
||||||
onSubmit={(e) => { e.preventDefault(); saveMutation.mutate(); }}
|
<Input label="Billing Day (1–28)" type="number" min="1" max="28"
|
||||||
className="space-y-4 max-w-lg"
|
value={fields.billingDay} onChange={set("billingDay")}
|
||||||
>
|
hint="Day of month invoices are generated" />
|
||||||
<Input
|
<Input label="Grace Period Days" type="number" min="0"
|
||||||
label="Billing Day (1–28)"
|
value={fields.gracePeriodDays} onChange={set("gracePeriodDays")}
|
||||||
type="number"
|
hint="Days after billing day before account is flagged overdue" />
|
||||||
min="1"
|
<div className="grid grid-cols-2 gap-3">
|
||||||
max="28"
|
<Input label="Late Fee Amount (₱)" type="number" min="0" step="0.01"
|
||||||
value={billingDay}
|
value={fields.lateFeeAmount} onChange={set("lateFeeAmount")} />
|
||||||
onChange={(e) => setBillingDay(e.target.value)}
|
<Input label="Late Fee % (0 = disabled)" type="number" min="0" max="100" step="0.01"
|
||||||
hint="Day of month invoices are generated"
|
value={fields.lateFeePercent} onChange={set("lateFeePercent")} />
|
||||||
/>
|
</div>
|
||||||
<Input
|
<Input label="Late Fee Grace Days" type="number" min="0"
|
||||||
label="Late Fee Amount (₱)"
|
value={fields.lateFeeGraceDays} onChange={set("lateFeeGraceDays")}
|
||||||
type="number"
|
hint="Days after due date before late fee applies" />
|
||||||
min="0"
|
<div className="flex flex-col gap-1.5">
|
||||||
step="0.01"
|
<label className="text-sm font-medium text-gray-700">Currency</label>
|
||||||
value={lateFeeAmount}
|
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
onChange={(e) => setLateFeeAmount(e.target.value)}
|
value={fields.currency} onChange={set("currency")}>
|
||||||
/>
|
<option value="PHP">PHP — Philippine Peso</option>
|
||||||
<Input
|
<option value="USD">USD — US Dollar</option>
|
||||||
label="Late Fee Grace Days"
|
</select>
|
||||||
type="number"
|
</div>
|
||||||
min="0"
|
<Button type="submit" isLoading={saveMutation.isPending}>Save Billing Settings</Button>
|
||||||
value={graceDays}
|
|
||||||
onChange={(e) => setGraceDays(e.target.value)}
|
|
||||||
hint="Days after due date before late fee applies"
|
|
||||||
/>
|
|
||||||
{saveMutation.isError && (
|
|
||||||
<p className="text-sm text-orange-600 bg-orange-50 rounded-lg px-3 py-2">
|
|
||||||
Save endpoint not available yet — changes not persisted.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<Button type="submit" isLoading={saveMutation.isPending}>
|
|
||||||
Save Billing Settings
|
|
||||||
</Button>
|
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -559,15 +559,19 @@ function PlansSettings() {
|
|||||||
// ─── Sub-page: Users ──────────────────────────────────────────────────────────
|
// ─── Sub-page: Users ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface UserItem {
|
interface UserItem {
|
||||||
id: string;
|
id: string; firstName: string; lastName: string; email: string;
|
||||||
firstName: string;
|
phone?: string; isActive: boolean;
|
||||||
lastName: string;
|
roleAssignments?: { role: string }[];
|
||||||
email: string;
|
|
||||||
isActive: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ROLES = ["ADMIN", "STAFF", "COLLECTOR", "TECHNICIAN"];
|
||||||
|
|
||||||
function UsersSettings() {
|
function UsersSettings() {
|
||||||
const { data, isLoading } = useQuery<UserItem[]>({
|
const qc = useQueryClient();
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const [form, setForm] = useState({ firstName: "", lastName: "", email: "", password: "", phone: "", role: "STAFF" });
|
||||||
|
|
||||||
|
const { data, isLoading, refetch } = useQuery<UserItem[]>({
|
||||||
queryKey: ["users-settings"],
|
queryKey: ["users-settings"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<UserItem[]>("/api/v1/users");
|
const res = await api.get<UserItem[]>("/api/v1/users");
|
||||||
@@ -575,46 +579,101 @@ function UsersSettings() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const createUser = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/users", {
|
||||||
|
firstName: form.firstName, lastName: form.lastName,
|
||||||
|
email: form.email, password: form.password,
|
||||||
|
phone: form.phone || undefined, role: form.role,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("User created!");
|
||||||
|
setShowAdd(false);
|
||||||
|
setForm({ firstName: "", lastName: "", email: "", password: "", phone: "", role: "STAFF" });
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create user"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggleActive = useMutation({
|
||||||
|
mutationFn: async ({ id, isActive }: { id: string; isActive: boolean }) => {
|
||||||
|
await api.patch(`/api/v1/users/${id}`, { isActive: !isActive });
|
||||||
|
},
|
||||||
|
onSuccess: () => { toast.success("User updated"); refetch(); },
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed"),
|
||||||
|
});
|
||||||
|
|
||||||
const users = data ?? [];
|
const users = data ?? [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<div className="space-y-4">
|
||||||
<CardHeader><CardTitle>Users</CardTitle></CardHeader>
|
<Card>
|
||||||
<CardContent className="p-0">
|
<CardHeader>
|
||||||
<Table>
|
<div className="flex items-center justify-between">
|
||||||
<TableHead>
|
<CardTitle>Users ({users.length})</CardTitle>
|
||||||
<TableRow>
|
<Button size="sm" onClick={() => setShowAdd(true)}>+ Add User</Button>
|
||||||
<Th>Name</Th>
|
</div>
|
||||||
<Th>Email</Th>
|
</CardHeader>
|
||||||
<Th>Status</Th>
|
<CardContent className="p-0">
|
||||||
</TableRow>
|
<Table>
|
||||||
</TableHead>
|
<TableHead>
|
||||||
<TableBody>
|
<TableRow><Th>Name</Th><Th>Email</Th><Th>Role</Th><Th>Status</Th><Th>Actions</Th></TableRow>
|
||||||
{isLoading ? (
|
</TableHead>
|
||||||
Array.from({ length: 3 }).map((_, i) => (
|
<TableBody>
|
||||||
<TableRow key={i}>
|
{isLoading ? (
|
||||||
{[1,2,3].map((j) => <Td key={j}><div className="h-4 w-28 animate-pulse bg-gray-100 rounded" /></Td>)}
|
Array.from({ length: 3 }).map((_, i) => (
|
||||||
</TableRow>
|
<TableRow key={i}>{[1,2,3,4,5].map(j => <Td key={j}><div className="h-4 w-20 animate-pulse bg-gray-100 rounded" /></Td>)}</TableRow>
|
||||||
))
|
))
|
||||||
) : users.length === 0 ? (
|
) : users.length === 0 ? (
|
||||||
<EmptyState message="No users found" />
|
<EmptyState message="No users found" />
|
||||||
) : (
|
) : users.map(u => {
|
||||||
users.map((u) => (
|
const role = u.roleAssignments?.[0]?.role ?? "—";
|
||||||
<TableRow key={u.id}>
|
return (
|
||||||
<Td className="font-medium">{u.firstName} {u.lastName}</Td>
|
<TableRow key={u.id}>
|
||||||
<Td className="text-sm text-gray-600">{u.email}</Td>
|
<Td className="font-medium">{u.firstName} {u.lastName}<div className="text-xs text-gray-400">{u.phone ?? ""}</div></Td>
|
||||||
<Td>
|
<Td className="text-sm text-gray-600">{u.email}</Td>
|
||||||
<Badge variant={u.isActive ? "success" : "muted"}>
|
<Td><Badge variant={role === "ADMIN" ? "danger" : role === "STAFF" ? "default" as any : "muted"}>{role}</Badge></Td>
|
||||||
{u.isActive ? "Active" : "Inactive"}
|
<Td><Badge variant={u.isActive ? "success" : "muted"}>{u.isActive ? "Active" : "Inactive"}</Badge></Td>
|
||||||
</Badge>
|
<Td>
|
||||||
</Td>
|
<Button size="sm" variant="ghost" onClick={() => toggleActive.mutate({ id: u.id, isActive: u.isActive })}>
|
||||||
</TableRow>
|
{u.isActive ? "Deactivate" : "Activate"}
|
||||||
))
|
</Button>
|
||||||
)}
|
</Td>
|
||||||
</TableBody>
|
</TableRow>
|
||||||
</Table>
|
);
|
||||||
</CardContent>
|
})}
|
||||||
</Card>
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add New User">
|
||||||
|
<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="Password *" type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} hint="Minimum 8 characters" />
|
||||||
|
<Input label="Phone" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Role *</label>
|
||||||
|
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))}>
|
||||||
|
{ROLES.map(r => <option key={r} value={r}>{r}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setShowAdd(false)}>Cancel</Button>
|
||||||
|
<Button onClick={() => createUser.mutate()} isLoading={createUser.isPending}
|
||||||
|
disabled={!form.firstName || !form.lastName || !form.email || form.password.length < 8}>
|
||||||
|
Create User
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { usePathname } from 'next/navigation';
|
|||||||
import { useAuthStore } from '@/lib/auth-store';
|
import { useAuthStore } from '@/lib/auth-store';
|
||||||
import {
|
import {
|
||||||
LayoutDashboard, Users, UserPlus, FileText, CreditCard, ArrowLeftRight,
|
LayoutDashboard, Users, UserPlus, FileText, CreditCard, ArrowLeftRight,
|
||||||
Ticket, BarChart3, Settings, Wifi, ClipboardList, ScrollText,
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
@@ -17,10 +16,9 @@ const navItems = [
|
|||||||
{ label: 'Payments', href: '/payments', icon: CreditCard, roles: [] },
|
{ label: 'Payments', href: '/payments', icon: CreditCard, roles: [] },
|
||||||
{ label: 'Remittances', href: '/remittances', icon: ArrowLeftRight, roles: [] },
|
{ label: 'Remittances', href: '/remittances', icon: ArrowLeftRight, roles: [] },
|
||||||
{ label: 'Tickets', href: '/tickets', icon: Ticket, roles: [] },
|
{ label: 'Tickets', href: '/tickets', icon: Ticket, roles: [] },
|
||||||
{ label: 'Tasks', href: '/tasks', icon: ClipboardList, roles: ['admin','staff'] },
|
|
||||||
{ label: 'Reports', href: '/reports', icon: BarChart3, roles: ['admin','staff'] },
|
{ label: 'Reports', href: '/reports', icon: BarChart3, roles: ['admin','staff'] },
|
||||||
{ label: 'Audit Log', href: '/audit-log', icon: ScrollText, roles: ['admin'] },
|
{ label: 'Audit Log', href: '/audit-log', icon: ScrollText, roles: ['admin'] },
|
||||||
{ label: 'Settings', href: '/settings/tenant', icon: Settings, roles: ['admin'] },
|
{ label: 'Settings', href: '/settings', icon: Settings, roles: ['admin'] },
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
|
|||||||
Reference in New Issue
Block a user