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:
Forge
2026-03-25 21:45:11 +08:00
parent 8ae1e14aee
commit ac0222fbf9
3 changed files with 380 additions and 254 deletions

View File

@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
Building2, CreditCard, Map, Wifi, Users, ChevronRight,
@@ -128,27 +128,35 @@ function TenantSettings() {
// ─── Sub-page: Billing Settings ───────────────────────────────────────────────
interface FullBillingSettings {
billingDay?: number;
gracePeriodDays?: number;
lateFeeAmount?: string | number;
lateFeePercent?: string | number;
lateFeeGraceDays?: number;
currency?: string;
}
function BillingSettings() {
const [billingDay, setBillingDay] = useState("1");
const [lateFeeAmount, setLateFeeAmount] = useState("0");
const [graceDays, setGraceDays] = useState("0");
const [fields, setFields] = useState({ billingDay: "1", gracePeriodDays: "5", lateFeeAmount: "0", lateFeePercent: "0", lateFeeGraceDays: "0", currency: "PHP" });
const [loaded, setLoaded] = useState(false);
const { isLoading } = useQuery<TenantBillingSettings>({
const { isLoading } = useQuery<FullBillingSettings>({
queryKey: ["tenant-billing-settings"],
queryFn: async () => {
try {
const res = await api.get<TenantBillingSettings>("/api/v1/tenants/me/settings");
return res.data ?? {};
} catch {
return {};
}
const res = await api.get<FullBillingSettings>("/api/v1/tenants/me/settings");
return res.data ?? {};
},
select: (data) => {
if (!loaded && data) {
setBillingDay(String(data.billingDay ?? 1));
setLateFeeAmount(String(data.lateFeeAmount ?? 0));
setGraceDays(String(data.lateFeeGraceDays ?? 0));
setFields({
billingDay: String(data.billingDay ?? 1),
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);
}
return data;
@@ -158,60 +166,52 @@ function BillingSettings() {
const saveMutation = useMutation({
mutationFn: async () => {
await api.patch("/api/v1/tenants/me/settings", {
billingDay: parseInt(billingDay),
lateFeeAmount: parseFloat(lateFeeAmount),
lateFeeGraceDays: parseInt(graceDays),
billingDay: parseInt(fields.billingDay),
gracePeriodDays: parseInt(fields.gracePeriodDays),
lateFeeAmount: parseFloat(fields.lateFeeAmount),
lateFeePercent: parseFloat(fields.lateFeePercent),
lateFeeGraceDays: parseInt(fields.lateFeeGraceDays),
currency: fields.currency,
});
},
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) {
return <div className="h-40 animate-pulse bg-gray-100 rounded-xl" />;
}
const set = (key: keyof typeof fields) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
setFields(f => ({ ...f, [key]: e.target.value }));
if (isLoading) return <div className="h-40 animate-pulse bg-gray-100 rounded-xl" />;
return (
<Card>
<CardHeader><CardTitle>Billing Configuration</CardTitle></CardHeader>
<CardContent>
<form
onSubmit={(e) => { e.preventDefault(); saveMutation.mutate(); }}
className="space-y-4 max-w-lg"
>
<Input
label="Billing Day (128)"
type="number"
min="1"
max="28"
value={billingDay}
onChange={(e) => setBillingDay(e.target.value)}
hint="Day of month invoices are generated"
/>
<Input
label="Late Fee Amount (₱)"
type="number"
min="0"
step="0.01"
value={lateFeeAmount}
onChange={(e) => setLateFeeAmount(e.target.value)}
/>
<Input
label="Late Fee Grace Days"
type="number"
min="0"
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 onSubmit={(e) => { e.preventDefault(); saveMutation.mutate(); }} className="space-y-4 max-w-lg">
<Input label="Billing Day (128)" type="number" min="1" max="28"
value={fields.billingDay} onChange={set("billingDay")}
hint="Day of month invoices are generated" />
<Input label="Grace Period Days" type="number" min="0"
value={fields.gracePeriodDays} onChange={set("gracePeriodDays")}
hint="Days after billing day before account is flagged overdue" />
<div className="grid grid-cols-2 gap-3">
<Input label="Late Fee Amount (₱)" type="number" min="0" step="0.01"
value={fields.lateFeeAmount} onChange={set("lateFeeAmount")} />
<Input label="Late Fee % (0 = disabled)" type="number" min="0" max="100" step="0.01"
value={fields.lateFeePercent} onChange={set("lateFeePercent")} />
</div>
<Input label="Late Fee Grace Days" type="number" min="0"
value={fields.lateFeeGraceDays} onChange={set("lateFeeGraceDays")}
hint="Days after due date before late fee applies" />
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Currency</label>
<select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
value={fields.currency} onChange={set("currency")}>
<option value="PHP">PHP Philippine Peso</option>
<option value="USD">USD US Dollar</option>
</select>
</div>
<Button type="submit" isLoading={saveMutation.isPending}>Save Billing Settings</Button>
</form>
</CardContent>
</Card>
@@ -559,15 +559,19 @@ function PlansSettings() {
// ─── Sub-page: Users ──────────────────────────────────────────────────────────
interface UserItem {
id: string;
firstName: string;
lastName: string;
email: string;
isActive: boolean;
id: string; firstName: string; lastName: string; email: string;
phone?: string; isActive: boolean;
roleAssignments?: { role: string }[];
}
const ROLES = ["ADMIN", "STAFF", "COLLECTOR", "TECHNICIAN"];
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"],
queryFn: async () => {
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 ?? [];
return (
<Card>
<CardHeader><CardTitle>Users</CardTitle></CardHeader>
<CardContent className="p-0">
<Table>
<TableHead>
<TableRow>
<Th>Name</Th>
<Th>Email</Th>
<Th>Status</Th>
</TableRow>
</TableHead>
<TableBody>
{isLoading ? (
Array.from({ length: 3 }).map((_, i) => (
<TableRow key={i}>
{[1,2,3].map((j) => <Td key={j}><div className="h-4 w-28 animate-pulse bg-gray-100 rounded" /></Td>)}
</TableRow>
))
) : users.length === 0 ? (
<EmptyState message="No users found" />
) : (
users.map((u) => (
<TableRow key={u.id}>
<Td className="font-medium">{u.firstName} {u.lastName}</Td>
<Td className="text-sm text-gray-600">{u.email}</Td>
<Td>
<Badge variant={u.isActive ? "success" : "muted"}>
{u.isActive ? "Active" : "Inactive"}
</Badge>
</Td>
</TableRow>
))
)}
</TableBody>
</Table>
</CardContent>
</Card>
<div className="space-y-4">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Users ({users.length})</CardTitle>
<Button size="sm" onClick={() => setShowAdd(true)}>+ Add User</Button>
</div>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHead>
<TableRow><Th>Name</Th><Th>Email</Th><Th>Role</Th><Th>Status</Th><Th>Actions</Th></TableRow>
</TableHead>
<TableBody>
{isLoading ? (
Array.from({ length: 3 }).map((_, i) => (
<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 ? (
<EmptyState message="No users found" />
) : users.map(u => {
const role = u.roleAssignments?.[0]?.role ?? "—";
return (
<TableRow key={u.id}>
<Td className="font-medium">{u.firstName} {u.lastName}<div className="text-xs text-gray-400">{u.phone ?? ""}</div></Td>
<Td className="text-sm text-gray-600">{u.email}</Td>
<Td><Badge variant={role === "ADMIN" ? "danger" : role === "STAFF" ? "default" as any : "muted"}>{role}</Badge></Td>
<Td><Badge variant={u.isActive ? "success" : "muted"}>{u.isActive ? "Active" : "Inactive"}</Badge></Td>
<Td>
<Button size="sm" variant="ghost" onClick={() => toggleActive.mutate({ id: u.id, isActive: u.isActive })}>
{u.isActive ? "Deactivate" : "Activate"}
</Button>
</Td>
</TableRow>
);
})}
</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>
);
}