Compare commits
68 Commits
backup/202
...
fix/remove
| Author | SHA1 | Date | |
|---|---|---|---|
| 41a90ad76e | |||
| b880137084 | |||
| fca3194801 | |||
| 22c1df67c1 | |||
| ef6b6a3ad4 | |||
| 8156c1f207 | |||
| 8a31ca0199 | |||
| d58b6bfd0b | |||
| e8b91468a1 | |||
| ac60822134 | |||
| 87e9fac4c1 | |||
| c061e821c9 | |||
| 63cce69634 | |||
| ff73898dac | |||
| 0715e66a65 | |||
| 205f0091dc | |||
| a6e13e611c | |||
| ff90ed9fa0 | |||
|
|
38e47b6140 | ||
| 944a501507 | |||
| 73012d52d3 | |||
| 546c32fc55 | |||
|
|
43379905f9 | ||
| 2b047055a2 | |||
| eaa03c69e0 | |||
| 45325b3e1b | |||
|
|
85f646cbed | ||
| 7db2a3fb5b | |||
| b719d87e1b | |||
| 89585ab645 | |||
| b1e2219391 | |||
| fde2b52d1f | |||
|
|
557a2791d3 | ||
| 3039bb595d | |||
|
|
61a696ef9c | ||
| 21ccb92e70 | |||
|
|
1aff75a8c8 | ||
| 85cb9ca7d7 | |||
|
|
37605b6574 | ||
| 081d45a56e | |||
|
|
7c2ab351a8 | ||
| 1681974ca5 | |||
|
|
7129266dd7 | ||
| ea004f840b | |||
|
|
a77759cc97 | ||
| 5843499815 | |||
|
|
e4f04cf38e | ||
| 986ee3dc6d | |||
|
|
cf369b2da6 | ||
|
|
512b9ef830 | ||
|
|
fa6a525c1f | ||
|
|
b0c68ae562 | ||
|
|
eebdf21505 | ||
|
|
bd006aca15 | ||
|
|
50fd7e39fc | ||
|
|
ce179ac799 | ||
|
|
8b0a1ec3a7 | ||
|
|
f8daee8732 | ||
|
|
ea3a076461 | ||
|
|
4510d0f6a4 | ||
|
|
4e37e0fa16 | ||
|
|
9d107ece2f | ||
|
|
562ff9e9b6 | ||
|
|
981b415430 | ||
|
|
4970c70546 | ||
|
|
e6ccda70d2 | ||
|
|
ac0222fbf9 | ||
|
|
8ae1e14aee |
9
.dockerignore
Normal file
9
.dockerignore
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
.next
|
||||||
|
node_modules
|
||||||
|
.git
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
npm-debug.log*
|
||||||
|
*.log
|
||||||
|
test-results
|
||||||
|
playwright-report
|
||||||
25
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
25
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
## Summary
|
||||||
|
<!-- What does this PR do? One sentence. -->
|
||||||
|
|
||||||
|
## Workitem
|
||||||
|
Workitem: <!-- https://plane-pro.juankibin.space/... -->
|
||||||
|
|
||||||
|
## Type
|
||||||
|
- [ ] Feature
|
||||||
|
- [ ] Bug fix
|
||||||
|
- [ ] Refactor
|
||||||
|
- [ ] Chore
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
-
|
||||||
|
|
||||||
|
## How to test
|
||||||
|
1.
|
||||||
|
|
||||||
|
## Screenshots (if UI change)
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
- [ ] Follows project conventions
|
||||||
|
- [ ] No leftover console.log
|
||||||
|
- [ ] No hardcoded secrets
|
||||||
|
- [ ] E2E spec added/updated (if UI change)
|
||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -34,3 +34,8 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
|
# Playwright
|
||||||
|
playwright-report/
|
||||||
|
test-results/
|
||||||
|
.auth/
|
||||||
|
|||||||
21
Dockerfile
Normal file
21
Dockerfile
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
FROM node:22-alpine AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=development
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY . .
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM node:22-alpine AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
|
||||||
|
COPY --from=builder /app/package*.json ./
|
||||||
|
COPY --from=builder /app/.next ./.next
|
||||||
|
COPY --from=builder /app/node_modules ./node_modules
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
ENV PORT=3000
|
||||||
|
CMD ["node_modules/.bin/next", "start"]
|
||||||
314
app/(app)/accounting/company-accounts/page.tsx
Normal file
314
app/(app)/accounting/company-accounts/page.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { ArrowRight } 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 { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
|
import { Badge } from "@/components/ui/Badge";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { AccountingNav } from "@/components/accounting/AccountingNav";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import type { CompanyAccount, CompanyAccountType, Transfer } from "@/types/index";
|
||||||
|
|
||||||
|
function formatDate(iso: string) {
|
||||||
|
return new Date(iso).toLocaleDateString("en-PH", { year: "numeric", month: "short", day: "numeric" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const TYPE_COLORS: Record<CompanyAccountType, "default" | "success" | "warning"> = {
|
||||||
|
CASH: "success",
|
||||||
|
BANK: "default",
|
||||||
|
EWALLET: "warning",
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACCOUNT_TYPES: CompanyAccountType[] = ["CASH", "BANK", "EWALLET"];
|
||||||
|
|
||||||
|
export default function CompanyAccountsPage() {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const [addForm, setAddForm] = useState({
|
||||||
|
name: "", type: "BANK" as CompanyAccountType,
|
||||||
|
bankName: "", accountNumber: "", initialBalance: "0",
|
||||||
|
});
|
||||||
|
|
||||||
|
const [transferAccount, setTransferAccount] = useState<CompanyAccount | null>(null);
|
||||||
|
const [transferForm, setTransferForm] = useState({ toAccountId: "", amount: "", date: today, note: "" });
|
||||||
|
|
||||||
|
const { data: accounts = [], isLoading, refetch: refetchAccounts } = useQuery<CompanyAccount[]>({
|
||||||
|
queryKey: ["company-accounts"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<CompanyAccount[] | { data: CompanyAccount[] }>("/api/v1/company-accounts");
|
||||||
|
const d = res.data;
|
||||||
|
return Array.isArray(d) ? d : (d as { data: CompanyAccount[] }).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: transfers = [], refetch: refetchTransfers } = useQuery<Transfer[]>({
|
||||||
|
queryKey: ["transfers"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Transfer[] | { data: Transfer[] }>("/api/v1/transfers");
|
||||||
|
const d = res.data;
|
||||||
|
return Array.isArray(d) ? d : (d as { data: Transfer[] }).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const addMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/company-accounts", {
|
||||||
|
name: addForm.name,
|
||||||
|
type: addForm.type,
|
||||||
|
bankName: addForm.bankName || undefined,
|
||||||
|
accountNumber: addForm.accountNumber || undefined,
|
||||||
|
initialBalance: parseFloat(addForm.initialBalance) || 0,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Account added");
|
||||||
|
setShowAdd(false);
|
||||||
|
setAddForm({ name: "", type: "BANK", bankName: "", accountNumber: "", initialBalance: "0" });
|
||||||
|
refetchAccounts();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to add account"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const transferMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
if (!transferAccount) return;
|
||||||
|
await api.post("/api/v1/transfers", {
|
||||||
|
fromAccountId: transferAccount.id,
|
||||||
|
toAccountId: transferForm.toAccountId,
|
||||||
|
amount: parseFloat(transferForm.amount),
|
||||||
|
date: transferForm.date,
|
||||||
|
note: transferForm.note || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Transfer completed");
|
||||||
|
setTransferAccount(null);
|
||||||
|
setTransferForm({ toAccountId: "", amount: "", date: today, note: "" });
|
||||||
|
refetchAccounts();
|
||||||
|
refetchTransfers();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to process transfer"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toAccounts = accounts.filter((a) => a.id !== transferAccount?.id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Accounting</h1>
|
||||||
|
<p className="text-sm text-gray-500">Company cash, bank, and e-wallet accounts</p>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={() => setShowAdd(true)}>+ Add Account</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AccountingNav />
|
||||||
|
|
||||||
|
{/* Account Cards */}
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{Array.from({ length: 3 }).map((_, i) => (
|
||||||
|
<div key={i} className="h-36 animate-pulse bg-gray-100 rounded-xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : accounts.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="py-12 text-center text-sm text-gray-400">
|
||||||
|
No company accounts yet. Add your first account to get started.
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{accounts.map((acct) => (
|
||||||
|
<Card key={acct.id}>
|
||||||
|
<CardContent className="pt-5">
|
||||||
|
<div className="flex items-start justify-between mb-3">
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-gray-900">{acct.name}</p>
|
||||||
|
{acct.bankName && (
|
||||||
|
<p className="text-xs text-gray-400 mt-0.5">{acct.bankName}</p>
|
||||||
|
)}
|
||||||
|
{acct.accountNumber && (
|
||||||
|
<p className="text-xs text-gray-400 font-mono">{acct.accountNumber}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Badge variant={TYPE_COLORS[acct.type]}>{acct.type}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-2xl font-bold text-gray-900">{formatCurrency(Number(acct.balance))}</p>
|
||||||
|
<div className="mt-3">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
setTransferAccount(acct);
|
||||||
|
setTransferForm({ toAccountId: "", amount: "", date: today, note: "" });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ArrowRight className="h-3 w-3 mr-1" /> Transfer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Recent Transfers */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Recent Transfers</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Date</Th>
|
||||||
|
<Th>From</Th>
|
||||||
|
<Th></Th>
|
||||||
|
<Th>To</Th>
|
||||||
|
<Th>Amount</Th>
|
||||||
|
<Th>Note</Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{transfers.length === 0 ? (
|
||||||
|
<EmptyState message="No transfers yet" />
|
||||||
|
) : (
|
||||||
|
transfers.slice(0, 20).map((t) => (
|
||||||
|
<TableRow key={t.id}>
|
||||||
|
<Td className="text-sm">{formatDate(t.date)}</Td>
|
||||||
|
<Td className="font-medium text-sm">{t.fromAccount?.name ?? "—"}</Td>
|
||||||
|
<Td className="text-gray-400"><ArrowRight className="h-4 w-4" /></Td>
|
||||||
|
<Td className="font-medium text-sm">{t.toAccount?.name ?? "—"}</Td>
|
||||||
|
<Td className="font-semibold text-sm">{formatCurrency(Number(t.amount))}</Td>
|
||||||
|
<Td className="text-sm text-gray-500">{t.note ?? "—"}</Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Add Account Modal */}
|
||||||
|
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add Company Account">
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); addMutation.mutate(); }} className="space-y-4">
|
||||||
|
<Input
|
||||||
|
label="Account Name *"
|
||||||
|
value={addForm.name}
|
||||||
|
onChange={(e) => setAddForm((f) => ({ ...f, name: e.target.value }))}
|
||||||
|
placeholder="e.g. BDO Savings"
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Type *</label>
|
||||||
|
<select
|
||||||
|
className="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={addForm.type}
|
||||||
|
onChange={(e) => setAddForm((f) => ({ ...f, type: e.target.value as CompanyAccountType }))}
|
||||||
|
>
|
||||||
|
{ACCOUNT_TYPES.map((t) => (
|
||||||
|
<option key={t} value={t}>{t}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Bank Name"
|
||||||
|
value={addForm.bankName}
|
||||||
|
onChange={(e) => setAddForm((f) => ({ ...f, bankName: e.target.value }))}
|
||||||
|
placeholder="e.g. BDO"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Account Number"
|
||||||
|
value={addForm.accountNumber}
|
||||||
|
onChange={(e) => setAddForm((f) => ({ ...f, accountNumber: e.target.value }))}
|
||||||
|
placeholder="e.g. 0012-3456-7890"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Initial Balance (₱)"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
value={addForm.initialBalance}
|
||||||
|
onChange={(e) => setAddForm((f) => ({ ...f, initialBalance: e.target.value }))}
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setShowAdd(false)}>Cancel</Button>
|
||||||
|
<Button type="submit" size="sm" isLoading={addMutation.isPending} disabled={!addForm.name.trim()}>
|
||||||
|
Add Account
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Transfer Modal */}
|
||||||
|
<Modal
|
||||||
|
isOpen={!!transferAccount}
|
||||||
|
onClose={() => setTransferAccount(null)}
|
||||||
|
title={`Transfer from ${transferAccount?.name ?? ""}`}
|
||||||
|
>
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); transferMutation.mutate(); }} className="space-y-4">
|
||||||
|
<div className="p-3 rounded-lg bg-blue-50 text-sm">
|
||||||
|
<span className="text-blue-700 font-medium">Available balance: </span>
|
||||||
|
<span className="text-blue-900 font-bold">{formatCurrency(Number(transferAccount?.balance ?? 0))}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">To Account *</label>
|
||||||
|
<select
|
||||||
|
className="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={transferForm.toAccountId}
|
||||||
|
onChange={(e) => setTransferForm((f) => ({ ...f, toAccountId: e.target.value }))}
|
||||||
|
>
|
||||||
|
<option value="">Select destination account</option>
|
||||||
|
{toAccounts.map((a) => (
|
||||||
|
<option key={a.id} value={a.id}>{a.name} ({a.type})</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Amount (₱) *"
|
||||||
|
type="number"
|
||||||
|
min="0.01"
|
||||||
|
step="0.01"
|
||||||
|
value={transferForm.amount}
|
||||||
|
onChange={(e) => setTransferForm((f) => ({ ...f, amount: e.target.value }))}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Date *"
|
||||||
|
type="date"
|
||||||
|
value={transferForm.date}
|
||||||
|
onChange={(e) => setTransferForm((f) => ({ ...f, date: e.target.value }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Note"
|
||||||
|
value={transferForm.note}
|
||||||
|
onChange={(e) => setTransferForm((f) => ({ ...f, note: e.target.value }))}
|
||||||
|
placeholder="Optional note"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setTransferAccount(null)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="sm"
|
||||||
|
isLoading={transferMutation.isPending}
|
||||||
|
disabled={!transferForm.toAccountId || !transferForm.amount || !transferForm.date}
|
||||||
|
>
|
||||||
|
Transfer Funds
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
210
app/(app)/accounting/expenses/page.tsx
Normal file
210
app/(app)/accounting/expenses/page.tsx
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { Button } from "@/components/ui/Button";
|
||||||
|
import { Input } from "@/components/ui/Input";
|
||||||
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { AccountingNav } from "@/components/accounting/AccountingNav";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import type { Expense, Account } from "@/types/index";
|
||||||
|
|
||||||
|
function formatDate(iso: string) {
|
||||||
|
return new Date(iso).toLocaleDateString("en-PH", { year: "numeric", month: "short", day: "numeric" });
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ExpensesPage() {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const firstOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split("T")[0];
|
||||||
|
|
||||||
|
const [from, setFrom] = useState(firstOfMonth);
|
||||||
|
const [to, setTo] = useState(today);
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const [form, setForm] = useState({ accountId: "", amount: "", date: today, vendor: "", description: "" });
|
||||||
|
|
||||||
|
const { data: expenses = [], isLoading, refetch } = useQuery<Expense[]>({
|
||||||
|
queryKey: ["expenses", from, to],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Expense[] | { data: Expense[] }>(`/api/v1/expenses?dateFrom=${from}&dateTo=${to}`);
|
||||||
|
const d = res.data;
|
||||||
|
return Array.isArray(d) ? d : (d as { data: Expense[] }).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: accounts = [] } = useQuery<Account[]>({
|
||||||
|
queryKey: ["accounts-expense"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Account[] | { data: Account[] }>("/api/v1/accounts?type=EXPENSE");
|
||||||
|
const d = res.data;
|
||||||
|
return (Array.isArray(d) ? d : (d as { data: Account[] }).data ?? []).filter((a) => a.isActive && a.type === "EXPENSE");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const addMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/expenses", {
|
||||||
|
accountId: form.accountId,
|
||||||
|
amount: parseFloat(form.amount),
|
||||||
|
date: form.date,
|
||||||
|
vendor: form.vendor || undefined,
|
||||||
|
description: form.description || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Expense recorded");
|
||||||
|
setShowAdd(false);
|
||||||
|
setForm({ accountId: "", amount: "", date: today, vendor: "", description: "" });
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to record expense"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalAmount = expenses.reduce((s, e) => s + Number(e.amount), 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Accounting</h1>
|
||||||
|
<p className="text-sm text-gray-500">Track business expenses</p>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={() => setShowAdd(true)}>+ Record Expense</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AccountingNav />
|
||||||
|
|
||||||
|
{/* Date filter */}
|
||||||
|
<div className="flex items-center gap-3 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>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>
|
||||||
|
Expenses ({expenses.length})
|
||||||
|
{expenses.length > 0 && (
|
||||||
|
<span className="ml-3 text-sm font-normal text-gray-500">
|
||||||
|
Total: <span className="font-semibold text-gray-800">{formatCurrency(totalAmount)}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Date</Th>
|
||||||
|
<Th>Vendor</Th>
|
||||||
|
<Th>Account</Th>
|
||||||
|
<Th>Amount</Th>
|
||||||
|
<Th>Description</Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 4 }).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>
|
||||||
|
))
|
||||||
|
) : expenses.length === 0 ? (
|
||||||
|
<EmptyState message="No expenses in this period" />
|
||||||
|
) : (
|
||||||
|
expenses.map((e) => (
|
||||||
|
<TableRow key={e.id}>
|
||||||
|
<Td className="text-sm">{formatDate(e.date)}</Td>
|
||||||
|
<Td className="font-medium">{e.vendor ?? <span className="text-gray-300">—</span>}</Td>
|
||||||
|
<Td className="text-sm text-gray-600">
|
||||||
|
{e.account ? `${e.account.code} — ${e.account.name}` : "—"}
|
||||||
|
</Td>
|
||||||
|
<Td className="font-semibold text-sm">{formatCurrency(Number(e.amount))}</Td>
|
||||||
|
<Td className="text-sm text-gray-500 max-w-xs truncate">
|
||||||
|
{e.description ?? <span className="text-gray-300">—</span>}
|
||||||
|
</Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Record Expense">
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); addMutation.mutate(); }} className="space-y-4">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Expense Account *</label>
|
||||||
|
<select
|
||||||
|
className="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={form.accountId}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, accountId: e.target.value }))}
|
||||||
|
>
|
||||||
|
<option value="">Select account</option>
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<option key={a.id} value={a.id}>{a.code} — {a.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Amount (₱) *"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
value={form.amount}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, amount: e.target.value }))}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Date *"
|
||||||
|
type="date"
|
||||||
|
value={form.date}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Vendor"
|
||||||
|
value={form.vendor}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, vendor: e.target.value }))}
|
||||||
|
placeholder="e.g. PLDT, Globe"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Description"
|
||||||
|
value={form.description}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
|
||||||
|
placeholder="What was this expense for?"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setShowAdd(false)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="sm"
|
||||||
|
isLoading={addMutation.isPending}
|
||||||
|
disabled={!form.accountId || !form.amount || !form.date}
|
||||||
|
>
|
||||||
|
Record Expense
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
356
app/(app)/accounting/journal-entries/page.tsx
Normal file
356
app/(app)/accounting/journal-entries/page.tsx
Normal file
@@ -0,0 +1,356 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Plus, Trash2, Eye } 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 { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { AccountingNav } from "@/components/accounting/AccountingNav";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import type { Account, JournalEntry, JournalEntryLine } from "@/types/index";
|
||||||
|
|
||||||
|
function formatDate(iso: string) {
|
||||||
|
return new Date(iso).toLocaleDateString("en-PH", { year: "numeric", month: "short", day: "numeric" });
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LineFormItem {
|
||||||
|
accountId: string;
|
||||||
|
debit: string;
|
||||||
|
credit: string;
|
||||||
|
memo: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyLine = (): LineFormItem => ({ accountId: "", debit: "", credit: "", memo: "" });
|
||||||
|
|
||||||
|
export default function JournalEntriesPage() {
|
||||||
|
const [showNew, setShowNew] = useState(false);
|
||||||
|
const [viewEntry, setViewEntry] = useState<JournalEntry | null>(null);
|
||||||
|
const [form, setForm] = useState({ date: "", description: "", reference: "" });
|
||||||
|
const [lines, setLines] = useState<LineFormItem[]>([emptyLine(), emptyLine()]);
|
||||||
|
|
||||||
|
const { data: entries = [], isLoading, refetch } = useQuery<JournalEntry[]>({
|
||||||
|
queryKey: ["journal-entries"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<JournalEntry[] | { data: JournalEntry[] }>("/api/v1/journal-entries");
|
||||||
|
const d = res.data;
|
||||||
|
return Array.isArray(d) ? d : (d as { data: JournalEntry[] }).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: accounts = [] } = useQuery<Account[]>({
|
||||||
|
queryKey: ["accounts"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Account[] | { data: Account[] }>("/api/v1/accounts");
|
||||||
|
const d = res.data;
|
||||||
|
return (Array.isArray(d) ? d : (d as { data: Account[] }).data ?? []).filter((a) => a.isActive);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalDebit = lines.reduce((s, l) => s + (parseFloat(l.debit) || 0), 0);
|
||||||
|
const totalCredit = lines.reduce((s, l) => s + (parseFloat(l.credit) || 0), 0);
|
||||||
|
const isBalanced = Math.abs(totalDebit - totalCredit) < 0.01 && totalDebit > 0;
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const payload = {
|
||||||
|
date: form.date,
|
||||||
|
description: form.description,
|
||||||
|
reference: form.reference || undefined,
|
||||||
|
lines: lines
|
||||||
|
.filter((l) => l.accountId)
|
||||||
|
.map((l) => ({
|
||||||
|
accountId: l.accountId,
|
||||||
|
debit: parseFloat(l.debit) || 0,
|
||||||
|
credit: parseFloat(l.credit) || 0,
|
||||||
|
memo: l.memo || undefined,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
await api.post("/api/v1/journal-entries", payload);
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Journal entry created");
|
||||||
|
setShowNew(false);
|
||||||
|
setForm({ date: "", description: "", reference: "" });
|
||||||
|
setLines([emptyLine(), emptyLine()]);
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to create journal entry"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function setLine(i: number, field: keyof LineFormItem, value: string) {
|
||||||
|
setLines((prev) => prev.map((l, idx) => idx === i ? { ...l, [field]: value } : l));
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLine() {
|
||||||
|
setLines((prev) => [...prev, emptyLine()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLine(i: number) {
|
||||||
|
if (lines.length <= 2) return;
|
||||||
|
setLines((prev) => prev.filter((_, idx) => idx !== i));
|
||||||
|
}
|
||||||
|
|
||||||
|
const entryTotalDebit = (e: JournalEntry) =>
|
||||||
|
e.lines?.reduce((s, l) => s + Number(l.debit), 0) ?? e.totalDebit ?? 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Accounting</h1>
|
||||||
|
<p className="text-sm text-gray-500">Journal entries and double-entry bookkeeping</p>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={() => setShowNew(true)}>+ New Entry</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AccountingNav />
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Journal Entries ({entries.length})</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Date</Th>
|
||||||
|
<Th>Reference</Th>
|
||||||
|
<Th>Description</Th>
|
||||||
|
<Th>Source</Th>
|
||||||
|
<Th>Lines</Th>
|
||||||
|
<Th>Total Debit</Th>
|
||||||
|
<Th></Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 4 }).map((_, i) => (
|
||||||
|
<TableRow key={i}>
|
||||||
|
{[1,2,3,4,5,6,7].map((j) => (
|
||||||
|
<Td key={j}><div className="h-4 w-20 animate-pulse bg-gray-100 rounded" /></Td>
|
||||||
|
))}
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
) : entries.length === 0 ? (
|
||||||
|
<EmptyState message="No journal entries yet" />
|
||||||
|
) : (
|
||||||
|
entries.map((e) => (
|
||||||
|
<TableRow key={e.id}>
|
||||||
|
<Td className="text-sm">{formatDate(e.date)}</Td>
|
||||||
|
<Td className="font-mono text-xs text-gray-500">{e.reference ?? "—"}</Td>
|
||||||
|
<Td className="font-medium max-w-xs truncate">{e.description}</Td>
|
||||||
|
<Td className="text-xs text-gray-500">{e.sourceType ?? "MANUAL"}</Td>
|
||||||
|
<Td className="text-sm">{e.lines?.length ?? 0}</Td>
|
||||||
|
<Td className="font-semibold text-sm">{formatCurrency(entryTotalDebit(e))}</Td>
|
||||||
|
<Td>
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setViewEntry(e)}>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* New Entry Modal */}
|
||||||
|
<Modal isOpen={showNew} onClose={() => setShowNew(false)} title="New Journal Entry" className="max-w-3xl">
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); createMutation.mutate(); }} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Date *"
|
||||||
|
type="date"
|
||||||
|
value={form.date}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Reference"
|
||||||
|
value={form.reference}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, reference: e.target.value }))}
|
||||||
|
placeholder="e.g. JE-001"
|
||||||
|
/>
|
||||||
|
<div className="col-span-1" />
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Description *"
|
||||||
|
value={form.description}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
|
||||||
|
placeholder="Describe this journal entry"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Lines */}
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<p className="text-sm font-medium text-gray-700">Line Items</p>
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={addLine}>
|
||||||
|
<Plus className="h-3 w-3 mr-1" /> Add Line
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="border rounded-lg overflow-hidden">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-gray-50 border-b">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500 w-1/3">Account</th>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500 w-24">Debit</th>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500 w-24">Credit</th>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500">Memo</th>
|
||||||
|
<th className="w-8" />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{lines.map((line, i) => (
|
||||||
|
<tr key={i} className="border-b last:border-0">
|
||||||
|
<td className="px-3 py-1.5">
|
||||||
|
<select
|
||||||
|
className="w-full rounded border-0 bg-transparent text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 rounded"
|
||||||
|
value={line.accountId}
|
||||||
|
onChange={(e) => setLine(i, "accountId", e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">Select account</option>
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<option key={a.id} value={a.id}>{a.code} — {a.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-1.5">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
className="w-full rounded border-0 bg-transparent text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 rounded"
|
||||||
|
value={line.debit}
|
||||||
|
onChange={(e) => setLine(i, "debit", e.target.value)}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-1.5">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
className="w-full rounded border-0 bg-transparent text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 rounded"
|
||||||
|
value={line.credit}
|
||||||
|
onChange={(e) => setLine(i, "credit", e.target.value)}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-1.5">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="w-full rounded border-0 bg-transparent text-sm focus:outline-none"
|
||||||
|
value={line.memo}
|
||||||
|
onChange={(e) => setLine(i, "memo", e.target.value)}
|
||||||
|
placeholder="Optional"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-1.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeLine(i)}
|
||||||
|
disabled={lines.length <= 2}
|
||||||
|
className="text-gray-300 hover:text-red-400 disabled:opacity-20"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
<tfoot className="bg-gray-50 border-t">
|
||||||
|
<tr>
|
||||||
|
<td className="px-3 py-2 text-xs font-medium text-gray-500">Totals</td>
|
||||||
|
<td className="px-3 py-2 text-sm font-bold text-gray-800">{formatCurrency(totalDebit)}</td>
|
||||||
|
<td className="px-3 py-2 text-sm font-bold text-gray-800">{formatCurrency(totalCredit)}</td>
|
||||||
|
<td colSpan={2} className="px-3 py-2">
|
||||||
|
{totalDebit > 0 && (
|
||||||
|
<span className={`text-xs font-medium ${isBalanced ? "text-green-600" : "text-red-500"}`}>
|
||||||
|
{isBalanced ? "✓ Balanced" : `Off by ${formatCurrency(Math.abs(totalDebit - totalCredit))}`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setShowNew(false)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="sm"
|
||||||
|
isLoading={createMutation.isPending}
|
||||||
|
disabled={!form.date || !form.description || !isBalanced}
|
||||||
|
>
|
||||||
|
Create Entry
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* View Entry Modal */}
|
||||||
|
{viewEntry && (
|
||||||
|
<Modal isOpen={!!viewEntry} onClose={() => setViewEntry(null)} title="Journal Entry" className="max-w-2xl">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid grid-cols-3 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-500">Date</p>
|
||||||
|
<p className="font-medium">{formatDate(viewEntry.date)}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-500">Reference</p>
|
||||||
|
<p className="font-medium font-mono">{viewEntry.reference ?? "—"}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-500">Source</p>
|
||||||
|
<p className="font-medium">{viewEntry.sourceType ?? "MANUAL"}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-500 text-sm">Description</p>
|
||||||
|
<p className="font-medium">{viewEntry.description}</p>
|
||||||
|
</div>
|
||||||
|
<table className="w-full text-sm border rounded-lg overflow-hidden">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500">Account</th>
|
||||||
|
<th className="text-right px-3 py-2 text-xs font-medium text-gray-500">Debit</th>
|
||||||
|
<th className="text-right px-3 py-2 text-xs font-medium text-gray-500">Credit</th>
|
||||||
|
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500">Memo</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{viewEntry.lines?.map((l, i) => (
|
||||||
|
<tr key={i} className="border-t">
|
||||||
|
<td className="px-3 py-2">{l.account ? `${l.account.code} — ${l.account.name}` : l.accountId}</td>
|
||||||
|
<td className="px-3 py-2 text-right font-mono">{Number(l.debit) > 0 ? formatCurrency(Number(l.debit)) : "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-right font-mono">{Number(l.credit) > 0 ? formatCurrency(Number(l.credit)) : "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-gray-500">{l.memo ?? ""}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
<tfoot className="bg-gray-50 border-t">
|
||||||
|
<tr>
|
||||||
|
<td className="px-3 py-2 text-xs font-medium text-gray-500">Total</td>
|
||||||
|
<td className="px-3 py-2 text-right font-bold text-sm">{formatCurrency(entryTotalDebit(viewEntry))}</td>
|
||||||
|
<td className="px-3 py-2 text-right font-bold text-sm">{formatCurrency(entryTotalDebit(viewEntry))}</td>
|
||||||
|
<td />
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setViewEntry(null)}>Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
231
app/(app)/accounting/page.tsx
Normal file
231
app/(app)/accounting/page.tsx
Normal file
@@ -0,0 +1,231 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { Button } from "@/components/ui/Button";
|
||||||
|
import { Input } from "@/components/ui/Input";
|
||||||
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
|
import { Badge } from "@/components/ui/Badge";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { AccountingNav } from "@/components/accounting/AccountingNav";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import type { Account, AccountType } from "@/types/index";
|
||||||
|
|
||||||
|
const ACCOUNT_TYPES: AccountType[] = ["ASSET", "LIABILITY", "EQUITY", "REVENUE", "EXPENSE"];
|
||||||
|
const TYPE_TABS: { key: AccountType | "ALL"; label: string }[] = [
|
||||||
|
{ key: "ALL", label: "All" },
|
||||||
|
{ key: "ASSET", label: "Assets" },
|
||||||
|
{ key: "LIABILITY", label: "Liabilities" },
|
||||||
|
{ key: "EQUITY", label: "Equity" },
|
||||||
|
{ key: "REVENUE", label: "Revenue" },
|
||||||
|
{ key: "EXPENSE", label: "Expenses" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const TYPE_COLORS: Record<AccountType, "default" | "success" | "warning" | "danger" | "muted"> = {
|
||||||
|
ASSET: "success",
|
||||||
|
LIABILITY: "danger",
|
||||||
|
EQUITY: "warning",
|
||||||
|
REVENUE: "default",
|
||||||
|
EXPENSE: "muted",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function ChartOfAccountsPage() {
|
||||||
|
const [activeType, setActiveType] = useState<AccountType | "ALL">("ALL");
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const [form, setForm] = useState({ code: "", name: "", type: "ASSET" as AccountType });
|
||||||
|
|
||||||
|
const { data, isLoading, refetch } = useQuery<Account[]>({
|
||||||
|
queryKey: ["accounts"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Account[] | { data: Account[] }>("/api/v1/accounts");
|
||||||
|
const d = res.data;
|
||||||
|
return Array.isArray(d) ? d : (d as { data: Account[] }).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const accounts = data ?? [];
|
||||||
|
const hasAccounts = accounts.length > 0;
|
||||||
|
|
||||||
|
const filtered = activeType === "ALL" ? accounts : accounts.filter((a) => a.type === activeType);
|
||||||
|
|
||||||
|
const addMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/accounts", form);
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Account created");
|
||||||
|
setShowAdd(false);
|
||||||
|
setForm({ code: "", name: "", type: "ASSET" });
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to create account"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const seedMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/accounts/seed", {});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Default accounts seeded");
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to seed accounts"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggleMutation = useMutation({
|
||||||
|
mutationFn: async ({ id, isActive }: { id: string; isActive: boolean }) => {
|
||||||
|
await api.patch(`/api/v1/accounts/${id}`, { isActive: !isActive });
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Account updated");
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to update account"),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Accounting</h1>
|
||||||
|
<p className="text-sm text-gray-500">Chart of accounts, journals, and financial reports</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{!hasAccounts && (
|
||||||
|
<Button variant="outline" size="sm" onClick={() => seedMutation.mutate()} isLoading={seedMutation.isPending}>
|
||||||
|
Seed Defaults
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button size="sm" onClick={() => setShowAdd(true)}>+ Add Account</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AccountingNav />
|
||||||
|
|
||||||
|
{/* Type filter tabs */}
|
||||||
|
<div className="flex gap-1 flex-wrap">
|
||||||
|
{TYPE_TABS.map(({ key, label }) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
onClick={() => setActiveType(key)}
|
||||||
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
|
||||||
|
activeType === key
|
||||||
|
? "bg-blue-100 text-blue-700"
|
||||||
|
: "text-gray-500 hover:bg-gray-100 hover:text-gray-700"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
{key !== "ALL" && (
|
||||||
|
<span className="ml-1 text-gray-400">
|
||||||
|
({accounts.filter((a) => a.type === key).length})
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>
|
||||||
|
{activeType === "ALL" ? "All Accounts" : activeType} ({filtered.length})
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Code</Th>
|
||||||
|
<Th>Name</Th>
|
||||||
|
<Th>Type</Th>
|
||||||
|
<Th>Status</Th>
|
||||||
|
<Th>Actions</Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 4 }).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>
|
||||||
|
))
|
||||||
|
) : filtered.length === 0 ? (
|
||||||
|
<EmptyState message={hasAccounts ? "No accounts of this type" : "No accounts yet — seed defaults or add manually"} />
|
||||||
|
) : (
|
||||||
|
filtered.map((a) => (
|
||||||
|
<TableRow key={a.id}>
|
||||||
|
<Td className="font-mono text-sm text-gray-700">{a.code}</Td>
|
||||||
|
<Td className="font-medium">{a.name}</Td>
|
||||||
|
<Td>
|
||||||
|
<Badge variant={TYPE_COLORS[a.type]}>{a.type}</Badge>
|
||||||
|
</Td>
|
||||||
|
<Td>
|
||||||
|
<Badge variant={a.isActive ? "success" : "muted"}>
|
||||||
|
{a.isActive ? "Active" : "Inactive"}
|
||||||
|
</Badge>
|
||||||
|
</Td>
|
||||||
|
<Td>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => toggleMutation.mutate({ id: a.id, isActive: a.isActive })}
|
||||||
|
>
|
||||||
|
{a.isActive ? "Deactivate" : "Activate"}
|
||||||
|
</Button>
|
||||||
|
</Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add Account">
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => { e.preventDefault(); addMutation.mutate(); }}
|
||||||
|
className="space-y-4"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
label="Account Code"
|
||||||
|
value={form.code}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))}
|
||||||
|
placeholder="e.g. 1001"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Account Name"
|
||||||
|
value={form.name}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
||||||
|
placeholder="e.g. Cash on Hand"
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Type</label>
|
||||||
|
<select
|
||||||
|
className="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={form.type}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, type: e.target.value as AccountType }))}
|
||||||
|
>
|
||||||
|
{ACCOUNT_TYPES.map((t) => (
|
||||||
|
<option key={t} value={t}>{t}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setShowAdd(false)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="sm"
|
||||||
|
isLoading={addMutation.isPending}
|
||||||
|
disabled={!form.code.trim() || !form.name.trim()}
|
||||||
|
>
|
||||||
|
Create Account
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
342
app/(app)/accounting/reports/page.tsx
Normal file
342
app/(app)/accounting/reports/page.tsx
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
"use client";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { RefreshCw } from "lucide-react";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { Button } from "@/components/ui/Button";
|
||||||
|
import { AccountingNav } from "@/components/accounting/AccountingNav";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import type {
|
||||||
|
TrialBalanceLine,
|
||||||
|
ProfitLossReport,
|
||||||
|
BalanceSheetReport,
|
||||||
|
CashFlowReport,
|
||||||
|
} from "@/types/index";
|
||||||
|
|
||||||
|
type ReportTab = "trial-balance" | "profit-loss" | "balance-sheet" | "cash-flow";
|
||||||
|
|
||||||
|
const TABS: { key: ReportTab; label: string }[] = [
|
||||||
|
{ key: "trial-balance", label: "Trial Balance" },
|
||||||
|
{ key: "profit-loss", label: "Profit & Loss" },
|
||||||
|
{ key: "balance-sheet", label: "Balance Sheet" },
|
||||||
|
{ key: "cash-flow", label: "Cash Flow" },
|
||||||
|
];
|
||||||
|
|
||||||
|
// ─── Trial Balance ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function TrialBalance({ dateFrom, dateTo }: { dateFrom: string; dateTo: string }) {
|
||||||
|
const { data, isLoading } = useQuery<TrialBalanceLine[]>({
|
||||||
|
queryKey: ["report-trial-balance", dateFrom, dateTo],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/api/v1/reports/trial-balance?dateFrom=${dateFrom}&dateTo=${dateTo}`);
|
||||||
|
const d = res.data;
|
||||||
|
if (Array.isArray(d)) return d;
|
||||||
|
return (d as { data?: TrialBalanceLine[] }).data ?? d as TrialBalanceLine[];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const lines = data ?? [];
|
||||||
|
const totalDebit = lines.reduce((s, l) => s + Number(l.debit), 0);
|
||||||
|
const totalCredit = lines.reduce((s, l) => s + Number(l.credit), 0);
|
||||||
|
|
||||||
|
if (isLoading) return <div className="h-64 animate-pulse bg-gray-100 rounded-xl" />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Trial Balance</CardTitle></CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
{lines.length === 0 ? (
|
||||||
|
<p className="text-sm text-gray-400 py-8 text-center">No data for this period</p>
|
||||||
|
) : (
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-gray-50 border-b">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left px-4 py-2.5 text-xs font-medium text-gray-500">Code</th>
|
||||||
|
<th className="text-left px-4 py-2.5 text-xs font-medium text-gray-500">Account</th>
|
||||||
|
<th className="text-right px-4 py-2.5 text-xs font-medium text-gray-500">Debit</th>
|
||||||
|
<th className="text-right px-4 py-2.5 text-xs font-medium text-gray-500">Credit</th>
|
||||||
|
<th className="text-right px-4 py-2.5 text-xs font-medium text-gray-500">Balance</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{lines.map((l, i) => (
|
||||||
|
<tr key={i} className="border-t hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-2.5 font-mono text-xs text-gray-500">{l.code}</td>
|
||||||
|
<td className="px-4 py-2.5 font-medium">{l.name}</td>
|
||||||
|
<td className="px-4 py-2.5 text-right font-mono text-sm">
|
||||||
|
{Number(l.debit) > 0 ? formatCurrency(Number(l.debit)) : "—"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-right font-mono text-sm">
|
||||||
|
{Number(l.credit) > 0 ? formatCurrency(Number(l.credit)) : "—"}
|
||||||
|
</td>
|
||||||
|
<td className={`px-4 py-2.5 text-right font-mono text-sm font-semibold ${Number(l.balance) < 0 ? "text-red-600" : "text-gray-800"}`}>
|
||||||
|
{formatCurrency(Math.abs(Number(l.balance)))}
|
||||||
|
{Number(l.balance) < 0 && " Cr"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
<tfoot className="border-t bg-gray-50 font-semibold">
|
||||||
|
<tr>
|
||||||
|
<td colSpan={2} className="px-4 py-2.5 text-sm">Totals</td>
|
||||||
|
<td className="px-4 py-2.5 text-right font-mono text-sm">{formatCurrency(totalDebit)}</td>
|
||||||
|
<td className="px-4 py-2.5 text-right font-mono text-sm">{formatCurrency(totalCredit)}</td>
|
||||||
|
<td className="px-4 py-2.5 text-right">
|
||||||
|
{Math.abs(totalDebit - totalCredit) < 0.01 ? (
|
||||||
|
<span className="text-green-600 text-xs">✓ Balanced</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-red-500 text-xs">Off by {formatCurrency(Math.abs(totalDebit - totalCredit))}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── P&L ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ProfitLoss({ dateFrom, dateTo }: { dateFrom: string; dateTo: string }) {
|
||||||
|
const { data, isLoading } = useQuery<ProfitLossReport>({
|
||||||
|
queryKey: ["report-profit-loss", dateFrom, dateTo],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/api/v1/reports/profit-loss?dateFrom=${dateFrom}&dateTo=${dateTo}`);
|
||||||
|
return res.data as ProfitLossReport;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) return <div className="h-64 animate-pulse bg-gray-100 rounded-xl" />;
|
||||||
|
if (!data) return <p className="text-sm text-gray-400 py-8 text-center">No data for this period</p>;
|
||||||
|
|
||||||
|
const netIncome = Number(data.netIncome ?? (Number(data.totalRevenue) - Number(data.totalExpenses)));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Profit & Loss Statement</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Revenue */}
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-2 uppercase tracking-wide">Revenue</h3>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{(data.revenue ?? []).map((r, i) => (
|
||||||
|
<div key={i} className="flex justify-between text-sm py-1 border-b border-gray-50">
|
||||||
|
<span className="text-gray-700">{r.name}</span>
|
||||||
|
<span className="font-mono font-medium">{formatCurrency(Number(r.amount))}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between text-sm font-bold py-1 border-t">
|
||||||
|
<span>Total Revenue</span>
|
||||||
|
<span className="text-green-700">{formatCurrency(Number(data.totalRevenue))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Expenses */}
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-2 uppercase tracking-wide">Expenses</h3>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{(data.expenses ?? []).map((e, i) => (
|
||||||
|
<div key={i} className="flex justify-between text-sm py-1 border-b border-gray-50">
|
||||||
|
<span className="text-gray-700">{e.name}</span>
|
||||||
|
<span className="font-mono font-medium">{formatCurrency(Number(e.amount))}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between text-sm font-bold py-1 border-t">
|
||||||
|
<span>Total Expenses</span>
|
||||||
|
<span className="text-red-600">{formatCurrency(Number(data.totalExpenses))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Net Income */}
|
||||||
|
<div className={`flex justify-between text-base font-bold p-3 rounded-lg ${netIncome >= 0 ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
|
||||||
|
<span>Net Income</span>
|
||||||
|
<span>{formatCurrency(netIncome)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Balance Sheet ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function BalanceSheet({ asOf }: { asOf: string }) {
|
||||||
|
const { data, isLoading } = useQuery<BalanceSheetReport>({
|
||||||
|
queryKey: ["report-balance-sheet", asOf],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/api/v1/reports/balance-sheet?asOf=${asOf}`);
|
||||||
|
return res.data as BalanceSheetReport;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) return <div className="h-64 animate-pulse bg-gray-100 rounded-xl" />;
|
||||||
|
if (!data) return <p className="text-sm text-gray-400 py-8 text-center">No data</p>;
|
||||||
|
|
||||||
|
function Section({ title, items, total, color }: { title: string; items: Array<{ name: string; amount: number }>; total: number; color: string }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-2 uppercase tracking-wide">{title}</h3>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{items.map((item, i) => (
|
||||||
|
<div key={i} className="flex justify-between text-sm py-1 border-b border-gray-50">
|
||||||
|
<span className="text-gray-700">{item.name}</span>
|
||||||
|
<span className="font-mono">{formatCurrency(Number(item.amount))}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className={`flex justify-between text-sm font-bold py-1 border-t ${color}`}>
|
||||||
|
<span>Total {title}</span>
|
||||||
|
<span>{formatCurrency(Number(total))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Balance Sheet</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
<Section title="Assets" items={data.assets ?? []} total={data.totalAssets} color="text-blue-700" />
|
||||||
|
<div className="space-y-6">
|
||||||
|
<Section title="Liabilities" items={data.liabilities ?? []} total={data.totalLiabilities} color="text-red-600" />
|
||||||
|
<Section title="Equity" items={data.equity ?? []} total={data.totalEquity} color="text-purple-700" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 p-3 rounded-lg bg-gray-50 flex justify-between text-sm font-bold">
|
||||||
|
<span>Total Liabilities + Equity</span>
|
||||||
|
<span>{formatCurrency(Number(data.totalLiabilities) + Number(data.totalEquity))}</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Cash Flow ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function CashFlow({ dateFrom, dateTo }: { dateFrom: string; dateTo: string }) {
|
||||||
|
const { data, isLoading } = useQuery<CashFlowReport>({
|
||||||
|
queryKey: ["report-cash-flow", dateFrom, dateTo],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/api/v1/reports/cash-flow?dateFrom=${dateFrom}&dateTo=${dateTo}`);
|
||||||
|
return res.data as CashFlowReport;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) return <div className="h-64 animate-pulse bg-gray-100 rounded-xl" />;
|
||||||
|
if (!data) return <p className="text-sm text-gray-400 py-8 text-center">No data for this period</p>;
|
||||||
|
|
||||||
|
function CashSection({ title, items, net }: { title: string; items: Array<{ name: string; amount: number }>; net: number }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-2 uppercase tracking-wide">{title}</h3>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{items.map((item, i) => (
|
||||||
|
<div key={i} className="flex justify-between text-sm py-1 border-b border-gray-50">
|
||||||
|
<span className="text-gray-700">{item.name}</span>
|
||||||
|
<span className={`font-mono ${Number(item.amount) < 0 ? "text-red-600" : ""}`}>
|
||||||
|
{formatCurrency(Number(item.amount))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between text-sm font-bold py-1 border-t">
|
||||||
|
<span>Net {title}</span>
|
||||||
|
<span className={Number(net) >= 0 ? "text-green-700" : "text-red-600"}>
|
||||||
|
{formatCurrency(Number(net))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Cash Flow Statement</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<CashSection title="Operating Activities" items={data.operating ?? []} net={data.netOperating} />
|
||||||
|
<CashSection title="Investing Activities" items={data.investing ?? []} net={data.netInvesting} />
|
||||||
|
<CashSection title="Financing Activities" items={data.financing ?? []} net={data.netFinancing} />
|
||||||
|
<div className={`flex justify-between text-base font-bold p-3 rounded-lg ${Number(data.netCashFlow) >= 0 ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
|
||||||
|
<span>Net Cash Flow</span>
|
||||||
|
<span>{formatCurrency(Number(data.netCashFlow))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Main Page ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export default function AccountingReportsPage() {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const firstOfYear = `${new Date().getFullYear()}-01-01`;
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<ReportTab>("trial-balance");
|
||||||
|
const [dateFrom, setDateFrom] = useState(firstOfYear);
|
||||||
|
const [dateTo, setDateTo] = useState(today);
|
||||||
|
const [asOf, setAsOf] = useState(today);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between flex-wrap gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Accounting</h1>
|
||||||
|
<p className="text-sm text-gray-500">Financial statements and accounting reports</p>
|
||||||
|
</div>
|
||||||
|
{activeTab !== "balance-sheet" ? (
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<label className="text-gray-500">From</label>
|
||||||
|
<input type="date" value={dateFrom} onChange={(e) => setDateFrom(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={dateTo} onChange={(e) => setDateTo(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>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<label className="text-gray-500">As of</label>
|
||||||
|
<input type="date" value={asOf} onChange={(e) => setAsOf(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>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AccountingNav />
|
||||||
|
|
||||||
|
{/* Report tabs */}
|
||||||
|
<div className="flex gap-1 flex-wrap">
|
||||||
|
{TABS.map(({ key, label }) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
onClick={() => setActiveTab(key)}
|
||||||
|
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
|
||||||
|
activeTab === key
|
||||||
|
? "bg-blue-100 text-blue-700"
|
||||||
|
: "text-gray-500 hover:bg-gray-100 hover:text-gray-700"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{activeTab === "trial-balance" && <TrialBalance dateFrom={dateFrom} dateTo={dateTo} />}
|
||||||
|
{activeTab === "profit-loss" && <ProfitLoss dateFrom={dateFrom} dateTo={dateTo} />}
|
||||||
|
{activeTab === "balance-sheet" && <BalanceSheet asOf={asOf} />}
|
||||||
|
{activeTab === "cash-flow" && <CashFlow dateFrom={dateFrom} dateTo={dateTo} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,166 +1,545 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
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 { useParams, useRouter } from "next/navigation";
|
||||||
import { ArrowLeft, Wifi, FileText, Ticket, RefreshCw } from "lucide-react";
|
import {
|
||||||
|
ArrowLeft, FileText, Ticket, CreditCard, RefreshCw,
|
||||||
|
CheckCircle2, Circle, MapPin, Zap, AlertTriangle,
|
||||||
|
} from "lucide-react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { Badge } from "@/components/ui/Badge";
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { Button } from "@/components/ui/Button";
|
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 { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { formatDate, formatCurrency } from "@/lib/utils";
|
import { formatDate, formatCurrency } from "@/lib/utils";
|
||||||
import api from "@/lib/api";
|
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, LegacyPaginatedResponse } from "@/types";
|
||||||
|
|
||||||
type Tab = "profile" | "subscriptions" | "invoices" | "tickets";
|
type Tab = "profile" | "subscriptions" | "invoices" | "payments" | "tickets";
|
||||||
|
|
||||||
const statusColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
const statusColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
||||||
active: "success",
|
ACTIVE: "success", active: "success",
|
||||||
ACTIVE: "success",
|
SUSPENDED: "warning", suspended: "warning",
|
||||||
suspended: "warning",
|
CANCELLED: "danger", cancelled: "danger",
|
||||||
SUSPENDED: "warning",
|
DISCONNECTED: "danger",
|
||||||
cancelled: "danger",
|
PENDING: "muted", pending: "muted",
|
||||||
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",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Activation Flow Types ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface ActivationState {
|
||||||
|
installationTicketId: string | null; // existing INSTALLATION ticket (OPEN/IN_PROGRESS)
|
||||||
|
installationResolved: boolean;
|
||||||
|
locationPinned: boolean; // client has lat/lng set
|
||||||
|
invoiceCreated: boolean; // at least one invoice exists (prepaid: before activation)
|
||||||
|
activationTicketId: string | null; // the INSTALLATION ticket used for activation step
|
||||||
|
activationResolved: boolean;
|
||||||
|
clientActive: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Activation Flow Card ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ActivationFlowCard({
|
||||||
|
client,
|
||||||
|
subscriptions,
|
||||||
|
tickets,
|
||||||
|
invoices,
|
||||||
|
onRefresh,
|
||||||
|
}: {
|
||||||
|
client: Client;
|
||||||
|
subscriptions: Subscription[];
|
||||||
|
tickets: TicketType[];
|
||||||
|
invoices: Invoice[];
|
||||||
|
onRefresh: () => void;
|
||||||
|
}) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [showPinModal, setShowPinModal] = useState(false);
|
||||||
|
const [pinForm, setPinForm] = useState({ lat: String(client.lat ?? ""), lng: String(client.lng ?? "") });
|
||||||
|
const [showActivationTicketModal, setShowActivationTicketModal] = useState(false);
|
||||||
|
|
||||||
|
const pendingSub = subscriptions.find(s => s.status === "PENDING");
|
||||||
|
const billingType = pendingSub?.type ?? "POSTPAID";
|
||||||
|
|
||||||
|
// Derive state from data
|
||||||
|
const installationTickets = tickets.filter(t => t.type === "INSTALLATION");
|
||||||
|
const openInstallTicket = installationTickets.find(t => t.status === "OPEN" || t.status === "IN_PROGRESS");
|
||||||
|
const resolvedInstallTickets = installationTickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED");
|
||||||
|
|
||||||
|
// Activation ticket = an INSTALLATION ticket created after the first one is resolved
|
||||||
|
// We identify it by: resolved install exists + there's another ticket also INSTALLATION
|
||||||
|
const activationTicket = resolvedInstallTickets.length > 1
|
||||||
|
? resolvedInstallTickets[resolvedInstallTickets.length - 1] // latest resolved = activation
|
||||||
|
: installationTickets.find(t =>
|
||||||
|
(t.status === "OPEN" || t.status === "IN_PROGRESS") &&
|
||||||
|
resolvedInstallTickets.length > 0
|
||||||
|
);
|
||||||
|
|
||||||
|
const state: ActivationState = {
|
||||||
|
installationTicketId: openInstallTicket?.id ?? null,
|
||||||
|
installationResolved: resolvedInstallTickets.length > 0,
|
||||||
|
locationPinned: !!(client.lat && client.lng),
|
||||||
|
invoiceCreated: invoices.length > 0,
|
||||||
|
activationTicketId: activationTicket?.id ?? null,
|
||||||
|
activationResolved: !!(activationTicket && (activationTicket.status === "RESOLVED" || activationTicket.status === "CLOSED")),
|
||||||
|
clientActive: client.isActive && (!pendingSub || pendingSub.status !== "PENDING"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// PREPAID steps: resolve install → pin location → create invoice → create activation ticket → resolve → activate
|
||||||
|
// POSTPAID steps: resolve install → pin location → create activation ticket → resolve → activate → create invoice
|
||||||
|
const isPrepaid = billingType === "PREPAID";
|
||||||
|
|
||||||
|
// Mutations
|
||||||
|
const resolveInstallMutation = useMutation({
|
||||||
|
mutationFn: async (ticketId: string) => {
|
||||||
|
await api.patch(`/api/v1/tickets/${ticketId}`, { status: "RESOLVED" });
|
||||||
|
},
|
||||||
|
onSuccess: () => { toast.success("Installation ticket resolved!"); onRefresh(); qc.invalidateQueries({ queryKey: ["client-tickets", client.id] }); },
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to resolve ticket"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const pinLocationMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const lat = parseFloat(pinForm.lat);
|
||||||
|
const lng = parseFloat(pinForm.lng);
|
||||||
|
if (isNaN(lat) || isNaN(lng)) throw new Error("Invalid coordinates");
|
||||||
|
await api.patch(`/api/v1/clients/${client.id}`, { lat, lng });
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Location pinned!");
|
||||||
|
setShowPinModal(false);
|
||||||
|
onRefresh();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client", client.id] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? e.message ?? "Failed to save location"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateInvoiceMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post(`/api/v1/invoices/generate/${client.id}`, {});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Invoice generated!");
|
||||||
|
onRefresh();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-invoices", client.id] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to generate invoice"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const createActivationTicketMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/tickets", {
|
||||||
|
clientId: client.id,
|
||||||
|
subject: `Activation — ${client.firstName} ${client.lastName} (${client.accountNumber})`,
|
||||||
|
type: "INSTALLATION",
|
||||||
|
priority: "HIGH",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Activation ticket created!");
|
||||||
|
setShowActivationTicketModal(false);
|
||||||
|
onRefresh();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-tickets", client.id] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create ticket"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const resolveActivationMutation = useMutation({
|
||||||
|
mutationFn: async (ticketId: string) => {
|
||||||
|
// 1. Resolve activation ticket
|
||||||
|
await api.patch(`/api/v1/tickets/${ticketId}`, { status: "RESOLVED" });
|
||||||
|
// 2. Set client to active
|
||||||
|
await api.patch(`/api/v1/clients/${client.id}`, { isActive: true });
|
||||||
|
// 3. Activate pending subscription if any
|
||||||
|
if (pendingSub) {
|
||||||
|
await api.patch(`/api/v1/clients/${client.id}/subscriptions/${pendingSub.id}/activate`, {});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Client activated! 🎉");
|
||||||
|
onRefresh();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client", client.id] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-subscriptions", client.id] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-tickets", client.id] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Activation failed"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const generatePostpaidInvoiceMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post(`/api/v1/invoices/generate/${client.id}`, {});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("First month invoice generated!");
|
||||||
|
onRefresh();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-invoices", client.id] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to generate invoice"),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Build steps based on billing type
|
||||||
|
type StepStatus = "done" | "active" | "pending";
|
||||||
|
|
||||||
|
interface Step {
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
status: StepStatus;
|
||||||
|
action?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const steps: Step[] = isPrepaid
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
label: "Resolve Installation",
|
||||||
|
description: "Mark the installation ticket as resolved",
|
||||||
|
status: state.installationResolved ? "done" : "active",
|
||||||
|
action: !state.installationResolved && state.installationTicketId ? (
|
||||||
|
<Button size="sm" onClick={() => resolveInstallMutation.mutate(state.installationTicketId!)}
|
||||||
|
isLoading={resolveInstallMutation.isPending}>
|
||||||
|
Resolve Ticket
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Pin Installation Location",
|
||||||
|
description: "Save the client's GPS coordinates",
|
||||||
|
status: state.locationPinned ? "done" : state.installationResolved ? "active" : "pending",
|
||||||
|
action: !state.locationPinned && state.installationResolved ? (
|
||||||
|
<Button size="sm" onClick={() => setShowPinModal(true)}>
|
||||||
|
<MapPin className="h-3.5 w-3.5 mr-1" /> Pin Location
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Create Invoice",
|
||||||
|
description: "Generate the first month invoice (client pays before activation)",
|
||||||
|
status: state.invoiceCreated ? "done" : (state.installationResolved && state.locationPinned) ? "active" : "pending",
|
||||||
|
action: !state.invoiceCreated && state.installationResolved && state.locationPinned ? (
|
||||||
|
<Button size="sm" onClick={() => generateInvoiceMutation.mutate()}
|
||||||
|
isLoading={generateInvoiceMutation.isPending}>
|
||||||
|
<FileText className="h-3.5 w-3.5 mr-1" /> Generate Invoice
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Create Activation Ticket",
|
||||||
|
description: "Open a ticket to confirm service activation",
|
||||||
|
status: state.activationTicketId ? "done" : (state.invoiceCreated) ? "active" : "pending",
|
||||||
|
action: !state.activationTicketId && state.invoiceCreated ? (
|
||||||
|
<Button size="sm" onClick={() => createActivationTicketMutation.mutate()}
|
||||||
|
isLoading={createActivationTicketMutation.isPending}>
|
||||||
|
<Ticket className="h-3.5 w-3.5 mr-1" /> Create Ticket
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Resolve Activation → Client Active",
|
||||||
|
description: "Resolve the activation ticket — client status will be set to Active automatically",
|
||||||
|
status: state.clientActive ? "done" : (state.activationTicketId && !state.activationResolved) ? "active" : "pending",
|
||||||
|
action: state.activationTicketId && !state.activationResolved && !state.clientActive ? (
|
||||||
|
<Button size="sm" variant="primary" onClick={() => resolveActivationMutation.mutate(state.activationTicketId!)}
|
||||||
|
isLoading={resolveActivationMutation.isPending}>
|
||||||
|
<Zap className="h-3.5 w-3.5 mr-1" /> Resolve & Activate
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
label: "Resolve Installation",
|
||||||
|
description: "Mark the installation ticket as resolved",
|
||||||
|
status: state.installationResolved ? "done" : "active",
|
||||||
|
action: !state.installationResolved && state.installationTicketId ? (
|
||||||
|
<Button size="sm" onClick={() => resolveInstallMutation.mutate(state.installationTicketId!)}
|
||||||
|
isLoading={resolveInstallMutation.isPending}>
|
||||||
|
Resolve Ticket
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Pin Installation Location",
|
||||||
|
description: "Save the client's GPS coordinates",
|
||||||
|
status: state.locationPinned ? "done" : state.installationResolved ? "active" : "pending",
|
||||||
|
action: !state.locationPinned && state.installationResolved ? (
|
||||||
|
<Button size="sm" onClick={() => setShowPinModal(true)}>
|
||||||
|
<MapPin className="h-3.5 w-3.5 mr-1" /> Pin Location
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Create Activation Ticket",
|
||||||
|
description: "Open a ticket to confirm service activation",
|
||||||
|
status: state.activationTicketId ? "done" : (state.installationResolved && state.locationPinned) ? "active" : "pending",
|
||||||
|
action: !state.activationTicketId && state.installationResolved && state.locationPinned ? (
|
||||||
|
<Button size="sm" onClick={() => createActivationTicketMutation.mutate()}
|
||||||
|
isLoading={createActivationTicketMutation.isPending}>
|
||||||
|
<Ticket className="h-3.5 w-3.5 mr-1" /> Create Ticket
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Resolve Activation → Client Active",
|
||||||
|
description: "Resolve the activation ticket — client status will be set to Active automatically",
|
||||||
|
status: state.clientActive ? "done" : (state.activationTicketId && !state.activationResolved) ? "active" : "pending",
|
||||||
|
action: state.activationTicketId && !state.activationResolved && !state.clientActive ? (
|
||||||
|
<Button size="sm" variant="primary" onClick={() => resolveActivationMutation.mutate(state.activationTicketId!)}
|
||||||
|
isLoading={resolveActivationMutation.isPending}>
|
||||||
|
<Zap className="h-3.5 w-3.5 mr-1" /> Resolve & Activate
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Generate First Month Invoice",
|
||||||
|
description: "Create the first invoice after client is active (postpaid)",
|
||||||
|
status: (state.clientActive && state.invoiceCreated) ? "done" : state.clientActive ? "active" : "pending",
|
||||||
|
action: state.clientActive && !state.invoiceCreated ? (
|
||||||
|
<Button size="sm" onClick={() => generatePostpaidInvoiceMutation.mutate()}
|
||||||
|
isLoading={generatePostpaidInvoiceMutation.isPending}>
|
||||||
|
<FileText className="h-3.5 w-3.5 mr-1" /> Generate Invoice
|
||||||
|
</Button>
|
||||||
|
) : undefined,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const allDone = steps.every(s => s.status === "done");
|
||||||
|
if (allDone) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card className="border-amber-200 bg-amber-50">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-amber-600" />
|
||||||
|
<CardTitle className="text-amber-800 text-base">
|
||||||
|
Activation Flow — {isPrepaid ? "Prepaid" : "Postpaid"}
|
||||||
|
</CardTitle>
|
||||||
|
<Badge variant="warning" className="ml-auto">{pendingSub?.plan?.name ?? "Pending"}</Badge>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ol className="space-y-3">
|
||||||
|
{steps.map((step, i) => (
|
||||||
|
<li key={i} className="flex items-start gap-3">
|
||||||
|
<div className="mt-0.5 shrink-0">
|
||||||
|
{step.status === "done" ? (
|
||||||
|
<CheckCircle2 className="h-5 w-5 text-green-500" />
|
||||||
|
) : step.status === "active" ? (
|
||||||
|
<div className="h-5 w-5 rounded-full border-2 border-amber-500 bg-amber-100 flex items-center justify-center">
|
||||||
|
<div className="h-2 w-2 rounded-full bg-amber-500" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Circle className="h-5 w-5 text-gray-300" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className={`text-sm font-medium ${
|
||||||
|
step.status === "done" ? "text-green-700 line-through opacity-60" :
|
||||||
|
step.status === "active" ? "text-gray-900" : "text-gray-400"
|
||||||
|
}`}>{step.label}</p>
|
||||||
|
{step.status !== "done" && (
|
||||||
|
<p className="text-xs text-gray-500 mt-0.5">{step.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{step.action && <div className="shrink-0">{step.action}</div>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Pin Location Modal */}
|
||||||
|
<Modal isOpen={showPinModal} onClose={() => setShowPinModal(false)} title="Pin Installation Location">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-gray-500">Enter the GPS coordinates for this installation site.</p>
|
||||||
|
<Input label="Latitude" type="number" step="any" placeholder="e.g. 16.5325"
|
||||||
|
value={pinForm.lat} onChange={e => setPinForm(f => ({ ...f, lat: e.target.value }))} />
|
||||||
|
<Input label="Longitude" type="number" step="any" placeholder="e.g. 121.7710"
|
||||||
|
value={pinForm.lng} onChange={e => setPinForm(f => ({ ...f, lng: e.target.value }))} />
|
||||||
|
<p className="text-xs text-gray-400">💡 Tip: Get coordinates from Google Maps → right-click the location → copy lat/lng.</p>
|
||||||
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
|
<Button variant="outline" onClick={() => setShowPinModal(false)}>Cancel</Button>
|
||||||
|
<Button onClick={() => pinLocationMutation.mutate()} isLoading={pinLocationMutation.isPending}
|
||||||
|
disabled={!pinForm.lat || !pinForm.lng}>
|
||||||
|
<MapPin className="h-4 w-4 mr-1" /> Save Location
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Main Page ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function ClientDetailPage() {
|
export default function ClientDetailPage() {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const qc = useQueryClient();
|
||||||
const [activeTab, setActiveTab] = useState<Tab>("profile");
|
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>({
|
const { data: client, isLoading, refetch: refetchClient } = useQuery<Client>({
|
||||||
queryKey: ["client", id],
|
queryKey: ["client", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => { const r = await api.get<Client>(`/api/v1/clients/${id}`); return r.data; },
|
||||||
const res = await api.get<Client>(`/api/v1/clients/${id}`);
|
|
||||||
return res.data;
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: subscriptions, isError: subsError } = useQuery<Subscription[]>({
|
const { data: subscriptions = [] } = useQuery<Subscription[]>({
|
||||||
queryKey: ["client-subscriptions", id],
|
queryKey: ["client-subscriptions", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<Subscription[]>(`/api/v1/clients/${id}/subscriptions`);
|
const r = await api.get<{ data: Subscription[] }>(`/api/v1/clients/${id}/subscriptions`);
|
||||||
return Array.isArray(res.data) ? res.data : [];
|
return (r.data as any).data ?? [];
|
||||||
},
|
},
|
||||||
enabled: activeTab === "subscriptions",
|
|
||||||
retry: false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: invoicesData } = useQuery<LegacyPaginatedResponse<Invoice>>({
|
const { data: allTickets = [] } = useQuery<TicketType[]>({
|
||||||
|
queryKey: ["client-tickets-all", id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const r = await api.get<LegacyPaginatedResponse<TicketType>>(`/api/v1/tickets?clientId=${id}&page=1&limit=50`);
|
||||||
|
return (r.data as any).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: invoicesData, refetch: refetchInvoices } = useQuery<LegacyPaginatedResponse<Invoice>>({
|
||||||
queryKey: ["client-invoices", id],
|
queryKey: ["client-invoices", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<LegacyPaginatedResponse<Invoice>>(`/api/v1/invoices?clientId=${id}&page=1&limit=20`);
|
const r = await api.get<LegacyPaginatedResponse<Invoice>>(`/api/v1/invoices?clientId=${id}&page=1&limit=30`);
|
||||||
return res.data;
|
return r.data;
|
||||||
},
|
},
|
||||||
enabled: activeTab === "invoices",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: ticketsData } = useQuery<PaginatedResponse<TicketType>>({
|
const { data: paymentsData } = useQuery<LegacyPaginatedResponse<Payment>>({
|
||||||
queryKey: ["client-tickets", id],
|
queryKey: ["client-payments", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<PaginatedResponse<TicketType>>(`/api/v1/tickets?clientId=${id}&page=1&limit=20`);
|
const r = await api.get<LegacyPaginatedResponse<Payment>>(`/api/v1/payments?clientId=${id}&page=1&limit=30`);
|
||||||
return res.data;
|
return r.data;
|
||||||
},
|
},
|
||||||
enabled: activeTab === "tickets",
|
enabled: activeTab === "payments",
|
||||||
});
|
});
|
||||||
|
|
||||||
const tabs: { key: Tab; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
|
const recordPayment = useMutation({
|
||||||
{ key: "profile", label: "Profile", icon: ArrowLeft },
|
mutationFn: async () => {
|
||||||
{ key: "subscriptions", label: "Subscriptions", icon: Wifi },
|
await api.post("/api/v1/payments", {
|
||||||
{ key: "invoices", label: "Invoices", icon: FileText },
|
clientId: id, invoiceId: payInvoice?.id,
|
||||||
{ key: "tickets", label: "Tickets", icon: Ticket },
|
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) {
|
if (isLoading) return (
|
||||||
return (
|
<div className="space-y-4">
|
||||||
<div className="space-y-4">
|
<div className="h-8 w-48 animate-pulse bg-gray-200 rounded" />
|
||||||
<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>
|
||||||
<Card>
|
</div>
|
||||||
<CardContent className="py-10">
|
);
|
||||||
<div className="h-32 animate-pulse bg-gray-100 rounded-lg" />
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!client) {
|
if (!client) return (
|
||||||
return (
|
<div className="text-center py-20 text-gray-400">
|
||||||
<div className="text-center py-20 text-gray-400">
|
<p>Client not found</p>
|
||||||
<p>Client not found</p>
|
<Button variant="secondary" className="mt-4" onClick={() => router.push("/clients")}>Back to Clients</Button>
|
||||||
<Button variant="secondary" className="mt-4" onClick={() => router.push("/clients")}>
|
</div>
|
||||||
Back to Clients
|
);
|
||||||
</Button>
|
|
||||||
</div>
|
const sub = client.subscriptions?.[0];
|
||||||
);
|
const clientStatus = sub?.status ?? (client.isActive ? "ACTIVE" : "INACTIVE");
|
||||||
}
|
const hasPendingSub = subscriptions.some(s => s.status === "PENDING");
|
||||||
|
const needsActivation = !client.isActive || hasPendingSub;
|
||||||
|
|
||||||
|
const handleRefresh = () => {
|
||||||
|
refetchClient();
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-subscriptions", id] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-tickets-all", id] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["client-invoices", id] });
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="ghost" size="sm" onClick={() => router.push("/clients")}>
|
<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>
|
</Button>
|
||||||
<div>
|
<div className="flex-1">
|
||||||
<h1 className="text-2xl font-bold text-gray-900">
|
<h1 className="text-2xl font-bold text-gray-900">{client.firstName} {client.lastName}</h1>
|
||||||
{client.firstName} {client.lastName}
|
<p className="text-sm text-gray-500">{client.accountNumber} · {client.area?.name ?? "No area"}</p>
|
||||||
</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>
|
</div>
|
||||||
|
<Badge variant={statusColor[clientStatus] ?? "muted"}>{clientStatus}</Badge>
|
||||||
|
<Button size="sm" variant="outline" onClick={handleRefresh}><RefreshCw className="h-4 w-4" /></Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Activation Flow Banner — only when client is not yet active */}
|
||||||
|
{needsActivation && (
|
||||||
|
<ActivationFlowCard
|
||||||
|
client={client}
|
||||||
|
subscriptions={subscriptions}
|
||||||
|
tickets={allTickets}
|
||||||
|
invoices={invoicesData?.data ?? []}
|
||||||
|
onRefresh={handleRefresh}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="flex border-b border-gray-200">
|
<div className="flex border-b border-gray-200 overflow-x-auto">
|
||||||
{[
|
{tabs.map(tab => (
|
||||||
{ key: "profile" as Tab, label: "Profile" },
|
<button key={tab.key} onClick={() => setActiveTab(tab.key)}
|
||||||
{ key: "subscriptions" as Tab, label: "Subscriptions" },
|
className={`px-4 py-2.5 text-sm font-medium border-b-2 whitespace-nowrap transition-colors ${
|
||||||
{ key: "invoices" as Tab, label: "Invoices" },
|
activeTab === tab.key ? "border-blue-600 text-blue-600" : "border-transparent text-gray-500 hover:text-gray-700"
|
||||||
{ key: "tickets" as Tab, label: "Tickets" },
|
}`}>{tab.label}</button>
|
||||||
].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>
|
</div>
|
||||||
|
|
||||||
{/* Profile Tab */}
|
{/* Profile */}
|
||||||
{activeTab === "profile" && (
|
{activeTab === "profile" && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader><CardTitle>Client Profile</CardTitle></CardHeader>
|
||||||
<CardTitle>Client Profile</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
{[
|
{[
|
||||||
{ label: "Account Number", value: client.accountNumber },
|
{ label: "Account Number", value: client.accountNumber },
|
||||||
{ label: "Full Name", value: `${client.firstName} ${client.lastName}` },
|
{ label: "Full Name", value: `${client.firstName} ${client.lastName}` },
|
||||||
{ label: "Email", value: client.email },
|
{ label: "Email", value: client.email || "—" },
|
||||||
{ label: "Phone", value: client.phone },
|
{ label: "Phone", value: client.phone },
|
||||||
{ label: "Address", value: client.address || "—" },
|
{ label: "Address", value: client.address || "—" },
|
||||||
{ label: "Area", value: client.area?.name || "—" },
|
{ label: "Area", value: client.area?.name || "—" },
|
||||||
{ label: "Status", value: client.isActive ? "Active" : "Inactive" },
|
{ label: "Status", value: client.isActive ? "Active" : "Inactive" },
|
||||||
|
{ label: "Location", value: client.lat && client.lng ? `${client.lat}, ${client.lng}` : "Not pinned" },
|
||||||
{ label: "Joined", value: formatDate(client.createdAt) },
|
{ label: "Joined", value: formatDate(client.createdAt) },
|
||||||
].map(({ label, value }) => (
|
].map(({ label, value }) => (
|
||||||
<div key={label}>
|
<div key={label}>
|
||||||
@@ -168,131 +547,155 @@ export default function ClientDetailPage() {
|
|||||||
<dd className="mt-0.5 text-sm text-gray-900">{value}</dd>
|
<dd className="mt-0.5 text-sm text-gray-900">{value}</dd>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs font-medium text-gray-400 uppercase tracking-wide">Portal Access</dt>
|
||||||
|
<dd className="mt-0.5 text-sm">
|
||||||
|
{client.portalAccessEnabled
|
||||||
|
? <span className="text-green-600 font-medium">Enabled</span>
|
||||||
|
: <span className="text-gray-400">Disabled</span>
|
||||||
|
}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Subscriptions Tab */}
|
{/* Subscriptions */}
|
||||||
{activeTab === "subscriptions" && (
|
{activeTab === "subscriptions" && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader><CardTitle>Subscriptions</CardTitle></CardHeader>
|
<CardHeader><CardTitle>Subscriptions</CardTitle></CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead><TableRow><Th>Plan</Th><Th>Type</Th><Th>Status</Th><Th>Start Date</Th><Th>Monthly Rate</Th></TableRow></TableHead>
|
||||||
<TableRow>
|
|
||||||
<Th>Plan</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Start Date</Th>
|
|
||||||
<Th>Monthly Rate</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{subsError ? (
|
{subscriptions.length === 0 ? <EmptyState message="No subscriptions" /> :
|
||||||
<tr><td colSpan={4} className="py-8 text-center text-gray-400 text-sm">No data yet</td></tr>
|
subscriptions.map(sub => (
|
||||||
) : !subscriptions || subscriptions.length === 0 ? (
|
<TableRow key={sub.id}>
|
||||||
<EmptyState message="No subscriptions yet" />
|
<Td className="font-medium">{sub.plan?.name ?? "—"}</Td>
|
||||||
) : (
|
<Td><Badge variant="muted">{sub.type ?? sub.plan?.type ?? "—"}</Badge></Td>
|
||||||
subscriptions.map((sub) => (
|
<Td><Badge variant={statusColor[sub.status] ?? "muted"}>{sub.status}</Badge></Td>
|
||||||
<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>
|
|
||||||
<Td>{formatDate(sub.startDate)}</Td>
|
<Td>{formatDate(sub.startDate)}</Td>
|
||||||
<Td>{formatCurrency(sub.plan?.monthlyPrice ?? sub.monthlyRate ?? sub.mrc ?? 0)}</Td>
|
<Td>{formatCurrency(Number(sub.monthlyPrice ?? sub.plan?.monthlyPrice ?? 0))}</Td>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
)}
|
}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Invoices Tab */}
|
{/* Invoices */}
|
||||||
{activeTab === "invoices" && (
|
{activeTab === "invoices" && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader><CardTitle>Invoices</CardTitle></CardHeader>
|
<CardHeader><CardTitle>Invoices</CardTitle></CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead><TableRow><Th>Invoice #</Th><Th>Total</Th><Th>Balance</Th><Th>Due Date</Th><Th>Status</Th><Th></Th></TableRow></TableHead>
|
||||||
<TableRow>
|
|
||||||
<Th>Invoice #</Th>
|
|
||||||
<Th>Amount</Th>
|
|
||||||
<Th>Due Date</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{!invoicesData?.data || invoicesData.data.length === 0 ? (
|
{!invoicesData?.data || invoicesData.data.length === 0 ? <EmptyState message="No invoices" /> :
|
||||||
<EmptyState message="No invoices yet" />
|
invoicesData.data.map((inv: any) => (
|
||||||
) : (
|
|
||||||
invoicesData.data.map((inv) => (
|
|
||||||
<TableRow key={inv.id}>
|
<TableRow key={inv.id}>
|
||||||
<Td className="font-mono text-xs">{inv.invoiceNumber ?? inv.id.slice(0, 8)}</Td>
|
<Td className="font-mono text-xs">{inv.invoiceNumber ?? inv.id.slice(0, 8)}</Td>
|
||||||
<Td>{formatCurrency(inv.amount ?? inv.totalAmount ?? 0)}</Td>
|
<Td>{formatCurrency(Number(inv.total ?? inv.amount ?? 0))}</Td>
|
||||||
<Td>{formatDate(inv.dueDate)}</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>
|
<Td>
|
||||||
<Badge
|
{["SENT", "PARTIAL", "OVERDUE"].includes(inv.status) && (
|
||||||
variant={
|
<Button size="sm" onClick={() => {
|
||||||
inv.status === "paid" || inv.status === "PAID" ? "success" :
|
setPayInvoice(inv);
|
||||||
inv.status === "overdue" || inv.status === "OVERDUE" ? "danger" : "warning"
|
setPayForm(f => ({ ...f, amount: String(Number(inv.balance ?? inv.total ?? 0)) }));
|
||||||
}
|
}}>Pay</Button>
|
||||||
>
|
)}
|
||||||
{inv.status}
|
|
||||||
</Badge>
|
|
||||||
</Td>
|
</Td>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
)}
|
}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Tickets Tab */}
|
{/* Payments */}
|
||||||
{activeTab === "tickets" && (
|
{activeTab === "payments" && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader><CardTitle>Tickets</CardTitle></CardHeader>
|
<CardHeader><CardTitle>Payment History</CardTitle></CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead><TableRow><Th>Date</Th><Th>Amount</Th><Th>Channel</Th><Th>Reference</Th><Th>Notes</Th></TableRow></TableHead>
|
||||||
<TableRow>
|
|
||||||
<Th>Subject</Th>
|
|
||||||
<Th>Type</Th>
|
|
||||||
<Th>Priority</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Created</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{!ticketsData?.data || ticketsData.data.length === 0 ? (
|
{!paymentsData?.data || paymentsData.data.length === 0 ? <EmptyState message="No payments yet" /> :
|
||||||
<EmptyState message="No tickets yet" />
|
paymentsData.data.map((p: any) => (
|
||||||
) : (
|
<TableRow key={p.id}>
|
||||||
ticketsData.data.map((ticket) => (
|
<Td className="text-sm">{p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</Td>
|
||||||
<TableRow key={ticket.id}>
|
<Td className="font-medium text-green-700">{formatCurrency(Number(p.amount))}</Td>
|
||||||
<Td className="font-medium">{ticket.subject}</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><Badge variant="muted">{ticket.type}</Badge></Td>
|
<Td className="text-xs text-gray-500">{p.referenceNumber ?? p.orNumber ?? "—"}</Td>
|
||||||
<Td>
|
<Td className="text-xs text-gray-500">{p.notes ?? "—"}</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>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
)}
|
}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</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>
|
||||||
|
{allTickets.length === 0 ? <EmptyState message="No tickets" /> :
|
||||||
|
allTickets.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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,192 +1,214 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api } from '@/lib/api';
|
import { useRouter } from "next/navigation";
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { UserPlus, Search, ChevronRight, RefreshCw } from "lucide-react";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Button } from "@/components/ui/Button";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Input } from "@/components/ui/Input";
|
||||||
import { Search, UserPlus, ChevronRight } from 'lucide-react';
|
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 {
|
interface Client {
|
||||||
id: string;
|
id: string; accountNumber: string; firstName: string; lastName: string;
|
||||||
accountNumber: string;
|
phone: string; email: string; address?: string; isActive: boolean;
|
||||||
firstName: string;
|
area: { id: string; name: string } | null;
|
||||||
lastName: string;
|
subscriptions: Array<{ status: string; type: string; monthlyPrice: string; plan?: { name: string }; }>;
|
||||||
phone: string;
|
|
||||||
isActive: boolean;
|
|
||||||
area: { name: string } | null;
|
|
||||||
subscriptions: Array<{
|
|
||||||
status: string;
|
|
||||||
type: string;
|
|
||||||
monthlyPrice: string;
|
|
||||||
plan?: { name: string };
|
|
||||||
}>;
|
|
||||||
}
|
}
|
||||||
|
interface ClientsMeta { total: number; page: number; limit: number; totalPages: number; }
|
||||||
|
interface ClientsResponse { data: Client[]; meta: ClientsMeta; }
|
||||||
|
|
||||||
interface ClientsResponse {
|
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
||||||
data: Client[];
|
ACTIVE: "success", PENDING: "warning", SUSPENDED: "danger", DISCONNECTED: "muted", CANCELLED: "muted",
|
||||||
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',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function ClientsPage() {
|
export default function ClientsPage() {
|
||||||
const [search, setSearch] = useState('');
|
const router = useRouter();
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
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>({
|
const { data, isLoading, refetch } = useQuery<ClientsResponse>({
|
||||||
queryKey: ['clients', search, page],
|
queryKey: ["clients", search, page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ page: String(page), limit: '20' });
|
const params = new URLSearchParams({ page: String(page), limit: "20" });
|
||||||
if (search) params.set('search', search);
|
if (search) params.set("search", search);
|
||||||
const res = await api.get(`/api/v1/clients?${params}`);
|
const res = await api.get<ClientsResponse>(`/api/v1/clients?${params}`);
|
||||||
return res.data;
|
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", {
|
||||||
|
firstName: form.firstName, lastName: form.lastName,
|
||||||
|
email: form.email, phone: form.phone, address: form.address,
|
||||||
|
areaId: form.areaId || undefined,
|
||||||
|
planId: form.planId || undefined,
|
||||||
|
});
|
||||||
|
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?.id) router.push(`/clients/${data.id}`);
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create client"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const clients = data?.data ?? [];
|
const clients = data?.data ?? [];
|
||||||
const total = data?.total ?? 0;
|
const total = data?.meta?.total ?? 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Clients</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Clients</h1>
|
||||||
<p className="text-slate-500 text-sm mt-1">{total} total clients</p>
|
<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" data-testid="add-client-btn"><UserPlus size={14} className="mr-1" />Add Client</Button>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* Search */}
|
<Card>
|
||||||
<div className="relative mb-4">
|
<CardHeader>
|
||||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
<div className="relative">
|
||||||
<Input
|
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||||
placeholder="Search by name or account number..."
|
<input
|
||||||
className="pl-9"
|
className="w-full pl-9 pr-4 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
value={search}
|
placeholder="Search by name or account number..."
|
||||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
|
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>
|
|
||||||
</div>
|
</div>
|
||||||
|
</CardHeader>
|
||||||
{/* Pagination */}
|
<CardContent className="p-0">
|
||||||
{total > 20 && (
|
<table className="w-full text-sm">
|
||||||
<div className="flex items-center justify-between px-4 py-3 border-t">
|
<thead>
|
||||||
<p className="text-sm text-slate-500">
|
<tr className="border-b bg-gray-50">
|
||||||
Showing {(page - 1) * 20 + 1}–{Math.min(page * 20, total)} of {total}
|
<th className="text-left px-4 py-3 font-medium text-gray-500">Account #</th>
|
||||||
</p>
|
<th className="text-left px-4 py-3 font-medium text-gray-500">Name</th>
|
||||||
<div className="flex gap-2">
|
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden md:table-cell">Area</th>
|
||||||
<button
|
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden lg:table-cell">Plan</th>
|
||||||
disabled={page === 1}
|
<th className="text-left px-4 py-3 font-medium text-gray-500">Status</th>
|
||||||
onClick={() => setPage(p => p - 1)}
|
<th className="text-left px-4 py-3 font-medium text-gray-500 hidden xl:table-cell">Monthly</th>
|
||||||
className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
|
<th className="px-4 py-3"></th>
|
||||||
>
|
</tr>
|
||||||
Prev
|
</thead>
|
||||||
</button>
|
<tbody>
|
||||||
<button
|
{isLoading ? (
|
||||||
disabled={page * 20 >= total}
|
Array.from({ length: 8 }).map((_, i) => (
|
||||||
onClick={() => setPage(p => p + 1)}
|
<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>
|
||||||
className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
|
))
|
||||||
>
|
) : clients.map((client) => {
|
||||||
Next
|
const sub = client.subscriptions?.[0];
|
||||||
</button>
|
const status = sub?.status ?? (client.isActive ? "ACTIVE" : "INACTIVE");
|
||||||
</div>
|
return (
|
||||||
</div>
|
<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 && (
|
{!isLoading && clients.length === 0 && (
|
||||||
<div className="text-center py-12 text-slate-400">
|
<div className="text-center py-12 text-gray-400">No clients found{search ? ` for "${search}"` : ""}</div>
|
||||||
No clients found{search ? ` for "${search}"` : ''}
|
)}
|
||||||
|
{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 cursor-pointer">Prev</button>
|
||||||
|
<button disabled={page >= (data?.meta?.totalPages ?? 1)} onClick={() => setPage(p => p + 1)} className="px-3 py-1 border rounded-md disabled:opacity-40 cursor-pointer">Next</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,21 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Users, Wifi, FileText, DollarSign, Ticket, CheckSquare, TrendingUp, Database, RefreshCw } from "lucide-react";
|
import { Users, Wifi, FileText, DollarSign, Ticket, TrendingUp, Database, RefreshCw, AlertCircle } from "lucide-react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { Button } from "@/components/ui/Button";
|
import { Button } from "@/components/ui/Button";
|
||||||
import { Badge } from "@/components/ui/Badge";
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { formatCurrency, formatDateTime } from "@/lib/utils";
|
import { formatCurrency, formatDateTime } from "@/lib/utils";
|
||||||
|
import { useAuthStore } from "@/lib/auth-store";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import api from "@/lib/api";
|
import api from "@/lib/api";
|
||||||
import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types";
|
import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types";
|
||||||
import {
|
import {
|
||||||
LineChart,
|
LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
|
||||||
Line,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Legend,
|
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
|
|
||||||
interface KpiCardProps {
|
interface KpiCardProps {
|
||||||
@@ -46,44 +43,67 @@ function KpiCard({ title, value, icon: Icon, color, subtitle, href }: KpiCardPro
|
|||||||
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
||||||
{subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>}
|
{subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>}
|
||||||
</div>
|
</div>
|
||||||
{href && (
|
{href && <div className="ml-auto text-gray-300 text-xs">→</div>}
|
||||||
<div className="ml-auto text-gray-300 text-xs">→</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function KpiSkeleton() {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex items-center gap-4 py-5">
|
||||||
|
<div className="h-12 w-12 rounded-xl skeleton shrink-0" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<div className="h-3 skeleton rounded w-24" />
|
||||||
|
<div className="h-7 skeleton rounded w-16" />
|
||||||
|
<div className="h-2 skeleton rounded w-20" />
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center py-12 text-gray-400 gap-3">
|
||||||
|
<AlertCircle className="h-10 w-10 text-red-300" />
|
||||||
|
<p className="text-sm text-gray-500">{message}</p>
|
||||||
|
<Button size="sm" variant="outline" onClick={onRetry}>Retry</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const priorityVariant: Record<string, "danger" | "warning" | "default" | "muted"> = {
|
const priorityVariant: Record<string, "danger" | "warning" | "default" | "muted"> = {
|
||||||
URGENT: "danger",
|
URGENT: "danger", urgent: "danger",
|
||||||
urgent: "danger",
|
HIGH: "warning", high: "warning",
|
||||||
HIGH: "warning",
|
NORMAL: "default", normal: "default",
|
||||||
high: "warning",
|
MEDIUM: "default", medium: "default",
|
||||||
NORMAL: "default",
|
LOW: "muted", low: "muted",
|
||||||
normal: "default",
|
|
||||||
MEDIUM: "default",
|
|
||||||
medium: "default",
|
|
||||||
LOW: "muted",
|
|
||||||
low: "muted",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Build mock time-series data from revenue for the chart
|
|
||||||
function buildChartData(stats: DashboardSummary | undefined) {
|
function buildChartData(stats: DashboardSummary | undefined) {
|
||||||
if (!stats) return [];
|
if (!stats) return [];
|
||||||
// Create a simple 2-month comparison from revenue data
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const thisMonth = now.toLocaleString("default", { month: "short" });
|
const thisMonth = now.toLocaleString("default", { month: "short" });
|
||||||
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" });
|
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" });
|
||||||
return [
|
return [
|
||||||
{ month: lastMonth, revenue: stats.revenue.lastMonth, clients: stats.subscribers.total },
|
{ month: lastMonth, revenue: stats.revenue.lastMonth },
|
||||||
{ month: thisMonth, revenue: stats.revenue.thisMonth, clients: stats.subscribers.active },
|
{ month: thisMonth, revenue: stats.revenue.thisMonth },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const isAdmin = user?.roles?.some(r => r.toLowerCase() === "admin" || r.toLowerCase() === "super_admin");
|
||||||
|
|
||||||
const { data: stats, isLoading: statsLoading, refetch: refetchStats } = useQuery<DashboardSummary>({
|
const {
|
||||||
|
data: stats,
|
||||||
|
isLoading: statsLoading,
|
||||||
|
isError: statsError,
|
||||||
|
refetch: refetchStats,
|
||||||
|
} = useQuery<DashboardSummary>({
|
||||||
queryKey: ["dashboard-summary"],
|
queryKey: ["dashboard-summary"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
|
const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
|
||||||
@@ -91,7 +111,11 @@ export default function DashboardPage() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: ticketsData, refetch: refetchTickets } = useQuery<PaginatedResponse<TicketType>>({
|
const {
|
||||||
|
data: ticketsData,
|
||||||
|
isLoading: ticketsLoading,
|
||||||
|
refetch: refetchTickets,
|
||||||
|
} = useQuery<PaginatedResponse<TicketType>>({
|
||||||
queryKey: ["recent-tickets"],
|
queryKey: ["recent-tickets"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
|
const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
|
||||||
@@ -106,7 +130,7 @@ export default function DashboardPage() {
|
|||||||
refetchStats();
|
refetchStats();
|
||||||
refetchTickets();
|
refetchTickets();
|
||||||
},
|
},
|
||||||
onError: (err: { response?: { data?: { message?: string } } }) => {
|
onError: (err: any) => {
|
||||||
toast.error(err?.response?.data?.message || "Seed failed");
|
toast.error(err?.response?.data?.message || "Seed failed");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -117,99 +141,60 @@ export default function DashboardPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
|
||||||
<p className="text-sm text-gray-500 mt-0.5">Overview of your ISP operations</p>
|
<p className="text-sm text-gray-500 mt-0.5">Overview of your ISP operations</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2 flex-wrap justify-end">
|
<div className="flex gap-2 flex-wrap">
|
||||||
<Button
|
<Button size="sm" variant="outline" onClick={() => { refetchStats(); refetchTickets(); }}>
|
||||||
size="sm"
|
<RefreshCw className="h-4 w-4" /> Refresh
|
||||||
variant="outline"
|
|
||||||
onClick={() => { refetchStats(); refetchTickets(); }}
|
|
||||||
>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
Refresh
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="secondary"
|
|
||||||
onClick={() => seedMutation.mutate()}
|
|
||||||
isLoading={seedMutation.isPending}
|
|
||||||
>
|
|
||||||
<Database className="h-4 w-4" />
|
|
||||||
Seed Demo Data
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" onClick={() => router.push("/clients")}>
|
|
||||||
+ New Client
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="secondary" onClick={() => router.push("/payments")}>
|
|
||||||
+ Record Payment
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="secondary" onClick={() => router.push("/tickets")}>
|
|
||||||
+ New Ticket
|
|
||||||
</Button>
|
</Button>
|
||||||
|
{isAdmin && (
|
||||||
|
<Button size="sm" variant="secondary"
|
||||||
|
onClick={() => seedMutation.mutate()}
|
||||||
|
isLoading={seedMutation.isPending}>
|
||||||
|
<Database className="h-4 w-4" /> Seed Demo Data
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button size="sm" data-testid="new-client-btn" onClick={() => router.push("/clients")}>+ New Client</Button>
|
||||||
|
<Button size="sm" variant="secondary" onClick={() => router.push("/payments")}>+ Record Payment</Button>
|
||||||
|
<Button size="sm" variant="secondary" onClick={() => router.push("/tickets")}>+ New Ticket</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* KPI Cards */}
|
{/* KPI Cards */}
|
||||||
{statsLoading ? (
|
{statsLoading ? (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
{[1, 2, 3, 4].map((i) => (
|
{[1,2,3,4].map(i => <KpiSkeleton key={i} />)}
|
||||||
<Card key={i}>
|
|
||||||
<CardContent className="py-5">
|
|
||||||
<div className="h-16 animate-pulse bg-gray-100 rounded-lg" />
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
|
) : statsError ? (
|
||||||
|
<Card><CardContent className="py-2">
|
||||||
|
<ErrorState message="Failed to load dashboard stats." onRetry={refetchStats} />
|
||||||
|
</CardContent></Card>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
<KpiCard
|
<KpiCard title="Total Clients" value={stats?.subscribers.total ?? 0} icon={Users}
|
||||||
title="Total Clients"
|
color="bg-blue-500" subtitle={`${stats?.subscribers.active ?? 0} active`} href="/clients" />
|
||||||
value={stats?.subscribers.total ?? 0}
|
<KpiCard title="Active Subscriptions" value={stats?.subscribers.active ?? 0} icon={Wifi}
|
||||||
icon={Users}
|
color="bg-green-500" subtitle={`${stats?.subscribers.suspended ?? 0} suspended`} />
|
||||||
color="bg-blue-500"
|
<KpiCard title="Overdue Invoices" value={stats?.billing.overdueInvoices ?? 0} icon={FileText}
|
||||||
subtitle={`${stats?.subscribers.active ?? 0} active`}
|
color="bg-red-500" subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`} href="/invoices" />
|
||||||
href="/clients"
|
{isAdmin && (
|
||||||
/>
|
<KpiCard title="Monthly Revenue" value={formatCurrency(stats?.revenue.thisMonth ?? 0)}
|
||||||
<KpiCard
|
icon={DollarSign} color="bg-purple-500"
|
||||||
title="Active Subscriptions"
|
subtitle={stats?.revenue.growth != null
|
||||||
value={stats?.subscribers.active ?? 0}
|
|
||||||
icon={Wifi}
|
|
||||||
color="bg-green-500"
|
|
||||||
subtitle={`${stats?.subscribers.suspended ?? 0} suspended`}
|
|
||||||
href="/subscriptions"
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
title="Overdue Invoices"
|
|
||||||
value={stats?.billing.overdueInvoices ?? 0}
|
|
||||||
icon={FileText}
|
|
||||||
color="bg-red-500"
|
|
||||||
subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`}
|
|
||||||
href="/invoices?status=OVERDUE"
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
title="Monthly Revenue"
|
|
||||||
value={formatCurrency(stats?.revenue.thisMonth ?? 0)}
|
|
||||||
icon={DollarSign}
|
|
||||||
color="bg-purple-500"
|
|
||||||
subtitle={
|
|
||||||
stats?.revenue.growth != null
|
|
||||||
? `${stats.revenue.growth > 0 ? "+" : ""}${stats.revenue.growth.toFixed(1)}% vs last month`
|
? `${stats.revenue.growth > 0 ? "+" : ""}${stats.revenue.growth.toFixed(1)}% vs last month`
|
||||||
: "vs last month"
|
: "vs last month"} href="/payments" />
|
||||||
}
|
)}
|
||||||
href="/payments"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Secondary stats */}
|
{/* Secondary stats */}
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
<Card
|
<Card className="cursor-pointer hover:shadow-md transition-shadow"
|
||||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
onClick={() => router.push("/tickets")}>
|
||||||
onClick={() => router.push("/tickets?status=OPEN")}
|
|
||||||
>
|
|
||||||
<CardContent className="flex items-center gap-3 py-4">
|
<CardContent className="flex items-center gap-3 py-4">
|
||||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-50 shrink-0">
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-50 shrink-0">
|
||||||
<Ticket className="h-5 w-5 text-amber-600" />
|
<Ticket className="h-5 w-5 text-amber-600" />
|
||||||
@@ -220,10 +205,8 @@ export default function DashboardPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card
|
<Card className="cursor-pointer hover:shadow-md transition-shadow"
|
||||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
onClick={() => router.push("/tickets")}>
|
||||||
onClick={() => router.push("/tickets?status=IN_PROGRESS")}
|
|
||||||
>
|
|
||||||
<CardContent className="flex items-center gap-3 py-4">
|
<CardContent className="flex items-center gap-3 py-4">
|
||||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 shrink-0">
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 shrink-0">
|
||||||
<TrendingUp className="h-5 w-5 text-blue-600" />
|
<TrendingUp className="h-5 w-5 text-blue-600" />
|
||||||
@@ -234,24 +217,10 @@ export default function DashboardPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card
|
|
||||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
|
||||||
onClick={() => router.push("/tasks")}
|
|
||||||
>
|
|
||||||
<CardContent className="flex items-center gap-3 py-4">
|
|
||||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-50 shrink-0">
|
|
||||||
<CheckSquare className="h-5 w-5 text-green-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-gray-500">Pending Tasks</p>
|
|
||||||
<p className="text-xl font-bold text-gray-900">{stats?.tasks.pending ?? 0}</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Revenue Chart */}
|
{/* Revenue Chart — admin only */}
|
||||||
{!statsLoading && (
|
{isAdmin && !statsLoading && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Revenue Overview</CardTitle>
|
<CardTitle>Revenue Overview</CardTitle>
|
||||||
@@ -262,33 +231,17 @@ export default function DashboardPage() {
|
|||||||
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
|
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
|
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
|
||||||
<XAxis dataKey="month" tick={{ fontSize: 12 }} />
|
<XAxis dataKey="month" tick={{ fontSize: 12 }} />
|
||||||
<YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `₱${(v / 1000).toFixed(0)}k`} />
|
<YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `₱${(v/1000).toFixed(0)}k`} />
|
||||||
<Tooltip formatter={(v) => formatCurrency(Number(v))} />
|
<Tooltip formatter={(v) => formatCurrency(Number(v))} />
|
||||||
<Legend />
|
<Legend />
|
||||||
<Line
|
<Line type="monotone" dataKey="revenue" stroke="#0891B2"
|
||||||
type="monotone"
|
strokeWidth={2} dot={{ r: 4 }} name="Revenue" />
|
||||||
dataKey="revenue"
|
|
||||||
stroke="#3b82f6"
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4 }}
|
|
||||||
name="Revenue"
|
|
||||||
/>
|
|
||||||
</LineChart>
|
</LineChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col items-center justify-center h-32 text-gray-400">
|
<div className="flex flex-col items-center justify-center h-32 text-gray-400">
|
||||||
<TrendingUp className="h-8 w-8 mb-2 opacity-40" />
|
<TrendingUp className="h-8 w-8 mb-2 opacity-40" />
|
||||||
<p className="text-sm">Revenue data will appear once payments are recorded.</p>
|
<p className="text-sm">Revenue data will appear once payments are recorded.</p>
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="secondary"
|
|
||||||
className="mt-3"
|
|
||||||
onClick={() => seedMutation.mutate()}
|
|
||||||
isLoading={seedMutation.isPending}
|
|
||||||
>
|
|
||||||
<Database className="h-4 w-4" />
|
|
||||||
Seed Demo Data
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -299,34 +252,38 @@ export default function DashboardPage() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Recent Tickets</CardTitle>
|
<CardTitle>Recent Tickets</CardTitle>
|
||||||
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>
|
<Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>View all →</Button>
|
||||||
View all →
|
|
||||||
</Button>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
{recentTickets.length === 0 ? (
|
{ticketsLoading ? (
|
||||||
|
<div className="divide-y">
|
||||||
|
{[1,2,3].map(i => (
|
||||||
|
<div key={i} className="flex items-center gap-4 px-6 py-3">
|
||||||
|
<div className="flex-1 space-y-1.5">
|
||||||
|
<div className="h-3 skeleton rounded w-48" />
|
||||||
|
<div className="h-2 skeleton rounded w-32" />
|
||||||
|
</div>
|
||||||
|
<div className="h-5 skeleton rounded w-16" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : recentTickets.length === 0 ? (
|
||||||
<div className="py-10 text-center text-gray-400 text-sm">No tickets yet</div>
|
<div className="py-10 text-center text-gray-400 text-sm">No tickets yet</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="divide-y divide-gray-50">
|
<div className="divide-y divide-gray-50">
|
||||||
{recentTickets.map((ticket) => (
|
{recentTickets.map((ticket) => (
|
||||||
<div
|
<div key={ticket.id}
|
||||||
key={ticket.id}
|
|
||||||
className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 cursor-pointer transition-colors"
|
className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 cursor-pointer transition-colors"
|
||||||
onClick={() => router.push("/tickets")}
|
onClick={() => router.push("/tickets")}>
|
||||||
>
|
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium text-gray-800">{ticket.subject}</p>
|
<p className="text-sm font-medium text-gray-800">{ticket.subject}</p>
|
||||||
<p className="text-xs text-gray-400 mt-0.5">
|
<p className="text-xs text-gray-400 mt-0.5">
|
||||||
{ticket.client
|
{ticket.client ? `${ticket.client.firstName} ${ticket.client.lastName}` : "No client"}
|
||||||
? `${ticket.client.firstName} ${ticket.client.lastName}`
|
{" • "}{formatDateTime(ticket.createdAt)}
|
||||||
: "No client"}{" "}
|
|
||||||
• {formatDateTime(ticket.createdAt)}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Badge variant={priorityVariant[ticket.priority] ?? "muted"}>
|
<Badge variant={priorityVariant[ticket.priority] ?? "muted"}>{ticket.priority}</Badge>
|
||||||
{ticket.priority}
|
|
||||||
</Badge>
|
|
||||||
<Badge variant="muted">{ticket.status}</Badge>
|
<Badge variant="muted">{ticket.status}</Badge>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,170 +1,211 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api } from '@/lib/api';
|
import { RefreshCw, FileText } from "lucide-react";
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { Search, ChevronRight } from 'lucide-react';
|
import { Button } from "@/components/ui/Button";
|
||||||
import { format } from 'date-fns';
|
import { Input } from "@/components/ui/Input";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { formatDate, formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
interface Invoice {
|
interface Invoice {
|
||||||
id: string;
|
id: string; invoiceNumber: string; clientId: string;
|
||||||
invoiceNumber: string;
|
|
||||||
dueDate: string;
|
|
||||||
subtotal: string;
|
|
||||||
lateFee: string;
|
|
||||||
total: string;
|
|
||||||
amountPaid: string;
|
|
||||||
balance: string;
|
|
||||||
status: string;
|
|
||||||
client?: { firstName: string; lastName: string; accountNumber: string };
|
client?: { firstName: string; lastName: string; accountNumber: string };
|
||||||
|
subtotal: string; lateFee: string; total: string;
|
||||||
|
amountPaid: string; balance: string;
|
||||||
|
status: string; dueDate: string; periodStart?: string; periodEnd?: string; notes?: string;
|
||||||
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
interface InvoicesResponse { data: Invoice[]; total: number; page: number; limit: number; }
|
||||||
|
|
||||||
interface InvoicesResponse {
|
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
||||||
data: Invoice[];
|
PAID: "success", PARTIAL: "warning", OVERDUE: "danger",
|
||||||
total: number;
|
SENT: "muted", DRAFT: "muted", VOID: "muted",
|
||||||
}
|
|
||||||
|
|
||||||
const statusColors: Record<string, string> = {
|
|
||||||
SENT: 'bg-blue-100 text-blue-700',
|
|
||||||
PARTIAL: 'bg-yellow-100 text-yellow-700',
|
|
||||||
PAID: 'bg-green-100 text-green-700',
|
|
||||||
OVERDUE: 'bg-red-100 text-red-700',
|
|
||||||
DRAFT: 'bg-gray-100 text-gray-500',
|
|
||||||
VOID: 'bg-gray-100 text-gray-400',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const peso = (v: string | number) =>
|
const statusFilters = ["", "SENT", "PARTIAL", "OVERDUE", "PAID", "VOID"];
|
||||||
'₱' + Number(v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
|
|
||||||
|
|
||||||
export default function InvoicesPage() {
|
export default function InvoicesPage() {
|
||||||
const [search, setSearch] = useState('');
|
const qc = useQueryClient();
|
||||||
const [statusFilter, setStatusFilter] = useState('');
|
const [search, setSearch] = useState("");
|
||||||
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const [selected, setSelected] = useState<Invoice | null>(null);
|
||||||
|
const [payForm, setPayForm] = useState({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });
|
||||||
|
|
||||||
const { data, isLoading } = useQuery<InvoicesResponse>({
|
const { data, isLoading, isError, refetch } = useQuery<InvoicesResponse>({
|
||||||
queryKey: ['invoices', search, statusFilter, page],
|
queryKey: ["invoices", search, statusFilter, page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ page: String(page), limit: '20' });
|
const params = new URLSearchParams({ page: String(page), limit: "20" });
|
||||||
if (search) params.set('search', search);
|
if (search) params.set("search", search);
|
||||||
if (statusFilter) params.set('status', statusFilter);
|
if (statusFilter) params.set("status", statusFilter);
|
||||||
const res = await api.get(`/api/v1/invoices?${params}`);
|
const res = await api.get<InvoicesResponse>(`/api/v1/invoices?${params}`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
staleTime: 30_000,
|
});
|
||||||
|
|
||||||
|
const recordPayment = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/payments", {
|
||||||
|
clientId: selected!.clientId, invoiceId: selected!.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!");
|
||||||
|
setSelected(null);
|
||||||
|
setPayForm({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });
|
||||||
|
qc.invalidateQueries({ queryKey: ["invoices"] });
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Payment failed"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const voidInvoice = useMutation({
|
||||||
|
mutationFn: async (id: string) => { await api.patch(`/api/v1/invoices/${id}/void`); },
|
||||||
|
onSuccess: () => { toast.success("Invoice voided"); setSelected(null); qc.invalidateQueries({ queryKey: ["invoices"] }); },
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to void"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const invoices = data?.data ?? [];
|
const invoices = data?.data ?? [];
|
||||||
const total = data?.total ?? 0;
|
const total = data?.total ?? 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Invoices</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Invoices</h1>
|
||||||
<p className="text-slate-500 text-sm mt-1">{total} invoices</p>
|
<p className="text-sm text-gray-500 mt-1">{total} total invoices</p>
|
||||||
</div>
|
</div>
|
||||||
|
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-3 mb-4">
|
<Card>
|
||||||
<div className="relative flex-1">
|
<CardHeader>
|
||||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
<div className="flex flex-wrap gap-3 items-center">
|
||||||
<Input
|
<input className="flex-1 min-w-[200px] border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
placeholder="Search by invoice # or client..."
|
placeholder="Search by client or invoice #..."
|
||||||
className="pl-9"
|
value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
|
||||||
value={search}
|
<div className="flex gap-2 flex-wrap">
|
||||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
|
{statusFilters.map(s => (
|
||||||
/>
|
<button key={s} onClick={() => { setStatusFilter(s); setPage(1); }}
|
||||||
</div>
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${statusFilter === s ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
|
||||||
<select
|
{s || "All"}
|
||||||
className="border rounded-md px-3 py-2 text-sm text-slate-700 bg-white"
|
</button>
|
||||||
value={statusFilter}
|
))}
|
||||||
onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
|
</div>
|
||||||
>
|
|
||||||
<option value="">All Statuses</option>
|
|
||||||
{['SENT', 'PARTIAL', 'PAID', 'OVERDUE', 'DRAFT', 'VOID'].map((s) => (
|
|
||||||
<option key={s} value={s}>{s}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<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">Invoice #</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Client</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Due Date</th>
|
|
||||||
<th className="text-right px-4 py-3 font-medium text-slate-500">Total</th>
|
|
||||||
<th className="text-right px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Balance</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Status</th>
|
|
||||||
<th className="px-4 py-3"></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{isLoading
|
|
||||||
? Array.from({ length: 8 }).map((_, i) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
{Array.from({ length: 7 }).map((_, j) => (
|
|
||||||
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
: invoices.map((inv) => (
|
|
||||||
<tr key={inv.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">{inv.invoiceNumber}</td>
|
|
||||||
<td className="px-4 py-3 text-slate-700 hidden md:table-cell">
|
|
||||||
{inv.client
|
|
||||||
? `${inv.client.firstName} ${inv.client.lastName}`
|
|
||||||
: '—'}
|
|
||||||
<div className="text-xs text-slate-400">{inv.client?.accountNumber}</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
|
|
||||||
{inv.dueDate ? format(new Date(inv.dueDate), 'MMM d, yyyy') : '—'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-right font-medium text-slate-800">{peso(inv.total)}</td>
|
|
||||||
<td className="px-4 py-3 text-right text-slate-600 hidden md:table-cell">
|
|
||||||
{Number(inv.balance) > 0 ? (
|
|
||||||
<span className="text-red-600 font-medium">{peso(inv.balance)}</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-green-600">Paid</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[inv.status] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{inv.status}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-400"><ChevronRight size={16} /></td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
|
</CardHeader>
|
||||||
{!isLoading && invoices.length === 0 && (
|
<CardContent className="p-0">
|
||||||
<div className="text-center py-12 text-slate-400">No invoices found</div>
|
<Table>
|
||||||
)}
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Invoice #</Th><Th>Client</Th><Th>Total</Th><Th>Paid</Th><Th>Balance</Th><Th>Due Date</Th><Th>Status</Th><Th></Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 8 }).map((_, i) => (
|
||||||
|
<TableRow key={i}><Td colSpan={8}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
|
||||||
|
))
|
||||||
|
) : isError ? (
|
||||||
|
<TableRow><Td colSpan={8}><p className="text-center py-6 text-red-400 text-sm">Failed to load invoices. <button onClick={() => refetch()} className="underline">Retry</button></p></Td></TableRow>
|
||||||
|
) : invoices.length === 0 ? (
|
||||||
|
<EmptyState colSpan={8} message="No invoices found" icon={<FileText size={24} />} />
|
||||||
|
) : invoices.map(inv => (
|
||||||
|
<TableRow key={inv.id} onClick={() => setSelected(inv)} className="cursor-pointer hover:bg-blue-50 transition-colors">
|
||||||
|
<Td className="font-mono text-xs">{inv.invoiceNumber}</Td>
|
||||||
|
<Td className="font-medium">
|
||||||
|
{inv.client ? `${inv.client.firstName} ${inv.client.lastName}` : "—"}
|
||||||
|
<div className="text-xs text-gray-400">{inv.client?.accountNumber}</div>
|
||||||
|
</Td>
|
||||||
|
<Td>{formatCurrency(Number(inv.total))}</Td>
|
||||||
|
<Td className="text-green-700">{formatCurrency(Number(inv.amountPaid))}</Td>
|
||||||
|
<Td className={Number(inv.balance) > 0 ? "text-red-600 font-medium" : "text-gray-400"}>
|
||||||
|
{formatCurrency(Number(inv.balance))}
|
||||||
|
</Td>
|
||||||
|
<Td className={new Date(inv.dueDate) < new Date() && inv.status !== "PAID" ? "text-red-500" : ""}>
|
||||||
|
{formatDate(inv.dueDate)}
|
||||||
|
</Td>
|
||||||
|
<Td><Badge variant={statusVariant[inv.status] ?? "muted"}>{inv.status}</Badge></Td>
|
||||||
|
<Td className="text-gray-400 text-xs">View →</Td>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
{total > 20 && (
|
{total > 20 && (
|
||||||
<div className="flex items-center justify-between px-4 py-3 border-t">
|
<div className="flex items-center justify-between px-4 py-3 border-t text-sm text-gray-500">
|
||||||
<p className="text-sm text-slate-500">
|
<span>Showing {(page - 1) * 20 + 1}–{Math.min(page * 20, total)} of {total}</span>
|
||||||
Showing {(page - 1) * 20 + 1}–{Math.min(page * 20, total)} of {total}
|
|
||||||
</p>
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button disabled={page === 1} onClick={() => setPage(p => p - 1)}
|
<button disabled={page === 1} onClick={() => setPage(p => p - 1)} className="px-3 py-1 border rounded-md disabled:opacity-40">Prev</button>
|
||||||
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 border rounded-md disabled:opacity-40">Next</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>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Invoice Detail Modal */}
|
||||||
|
<Modal isOpen={!!selected} onClose={() => setSelected(null)} title={`Invoice ${selected?.invoiceNumber ?? ""}`} 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">Client</span>
|
||||||
|
<span className="font-medium">{selected.client ? `${selected.client.firstName} ${selected.client.lastName}` : "—"}</span></div>
|
||||||
|
<div className="flex justify-between"><span className="text-gray-500">Period</span>
|
||||||
|
<span>{selected.periodStart ? `${formatDate(selected.periodStart)} – ${formatDate(selected.periodEnd!)}` : "—"}</span></div>
|
||||||
|
<div className="flex justify-between"><span className="text-gray-500">Due Date</span>
|
||||||
|
<span className={new Date(selected.dueDate) < new Date() && selected.status !== "PAID" ? "text-red-500 font-medium" : ""}>
|
||||||
|
{formatDate(selected.dueDate)}</span></div>
|
||||||
|
<hr />
|
||||||
|
<div className="flex justify-between"><span className="text-gray-500">Subtotal</span><span>{formatCurrency(Number(selected.subtotal))}</span></div>
|
||||||
|
<div className="flex justify-between"><span className="text-gray-500">Late Fee</span><span>{formatCurrency(Number(selected.lateFee))}</span></div>
|
||||||
|
<div className="flex justify-between font-semibold text-base"><span>Total</span><span>{formatCurrency(Number(selected.total))}</span></div>
|
||||||
|
<div className="flex justify-between text-green-700"><span className="text-gray-500">Amount Paid</span><span>{formatCurrency(Number(selected.amountPaid))}</span></div>
|
||||||
|
<div className={`flex justify-between font-bold ${Number(selected.balance) > 0 ? "text-red-600" : "text-green-600"}`}>
|
||||||
|
<span>Balance</span><span>{formatCurrency(Number(selected.balance))}</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>
|
||||||
|
|
||||||
|
{/* Pay form (only for unpaid) */}
|
||||||
|
{["SENT", "PARTIAL", "OVERDUE"].includes(selected.status) && (
|
||||||
|
<div className="border rounded-lg p-4 space-y-3 bg-blue-50">
|
||||||
|
<p className="text-sm font-semibold text-blue-800">Record Payment</p>
|
||||||
|
<Input label="Amount" type="number" value={payForm.amount}
|
||||||
|
onChange={e => setPayForm(f => ({ ...f, amount: e.target.value }))}
|
||||||
|
hint={`Balance due: ${formatCurrency(Number(selected.balance))}`} />
|
||||||
|
<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 }))} />
|
||||||
|
<Button className="w-full" onClick={() => recordPayment.mutate()} isLoading={recordPayment.isPending}
|
||||||
|
disabled={!payForm.amount}>Record Payment</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-between pt-1">
|
||||||
|
{selected.status !== "VOID" && selected.status !== "PAID" && (
|
||||||
|
<Button variant="danger" size="sm" onClick={() => voidInvoice.mutate(selected.id)} isLoading={voidInvoice.isPending}>Void Invoice</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setSelected(null)} className="ml-auto">Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|||||||
@@ -1,32 +1,37 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { UserPlus, RefreshCw } from "lucide-react";
|
import { UserPlus, RefreshCw } from "lucide-react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { Badge } from "@/components/ui/Badge";
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { Button } from "@/components/ui/Button";
|
import { Button } from "@/components/ui/Button";
|
||||||
import { Input } from "@/components/ui/Input";
|
import { Input } from "@/components/ui/Input";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
import { formatDate } from "@/lib/utils";
|
import { formatDate } from "@/lib/utils";
|
||||||
import api from "@/lib/api";
|
import api from "@/lib/api";
|
||||||
|
import { toast } from "sonner";
|
||||||
import type { Lead } from "@/types";
|
import type { Lead } from "@/types";
|
||||||
|
|
||||||
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted" | "default"> = {
|
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted" | "default"> = {
|
||||||
NEW: "muted",
|
NEW: "muted", CONTACTED: "default" as any, INTERESTED: "warning", CONVERTED: "success", LOST: "danger",
|
||||||
CONTACTED: "default",
|
|
||||||
INTERESTED: "warning",
|
|
||||||
CONVERTED: "success",
|
|
||||||
LOST: "danger",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function LeadsPage() {
|
const statusOptions = ["NEW", "CONTACTED", "INTERESTED", "CONVERTED", "LOST"];
|
||||||
const [search, setSearch] = useState("");
|
|
||||||
|
|
||||||
const { data, isLoading, refetch } = useQuery<Lead[]>({
|
export default function LeadsPage() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [selected, setSelected] = useState<Lead | null>(null);
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const [form, setForm] = useState({ firstName: "", lastName: "", phone: "", email: "", address: "", notes: "", source: "" });
|
||||||
|
const [statusUpdate, setStatusUpdate] = useState("");
|
||||||
|
|
||||||
|
const { data = [], isLoading, refetch } = useQuery<Lead[]>({
|
||||||
queryKey: ["leads", search],
|
queryKey: ["leads", search],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ limit: "50" });
|
const params = new URLSearchParams({ limit: "100" });
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
const res = await api.get<Lead[] | { data: Lead[] }>(`/api/v1/leads?${params}`);
|
const res = await api.get<Lead[] | { data: Lead[] }>(`/api/v1/leads?${params}`);
|
||||||
const d = res.data;
|
const d = res.data;
|
||||||
@@ -34,7 +39,47 @@ export default function LeadsPage() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const leads = data ?? [];
|
const addLead = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/leads", {
|
||||||
|
firstName: form.firstName, lastName: form.lastName,
|
||||||
|
phone: form.phone, email: form.email || undefined,
|
||||||
|
address: form.address || undefined, notes: form.notes || undefined,
|
||||||
|
source: form.source || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Lead added!");
|
||||||
|
setShowAdd(false);
|
||||||
|
setForm({ firstName: "", lastName: "", phone: "", email: "", address: "", notes: "", source: "" });
|
||||||
|
qc.invalidateQueries({ queryKey: ["leads"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to add lead"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateStatus = useMutation({
|
||||||
|
mutationFn: async ({ id, status }: { id: string; status: string }) => {
|
||||||
|
await api.patch(`/api/v1/leads/${id}`, { status });
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Status updated!");
|
||||||
|
qc.invalidateQueries({ queryKey: ["leads"] });
|
||||||
|
if (selected) setSelected(prev => prev ? { ...prev, status: statusUpdate as Lead["status"] } : prev);
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to update"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteLead = useMutation({
|
||||||
|
mutationFn: async (id: string) => { await api.delete(`/api/v1/leads/${id}`); },
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Lead deleted");
|
||||||
|
setSelected(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["leads"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to delete"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const counts = statusOptions.reduce((acc, s) => ({ ...acc, [s]: data.filter(l => l.status === s).length }), {} as Record<string, number>);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@@ -43,79 +88,124 @@ export default function LeadsPage() {
|
|||||||
<h1 className="text-2xl font-bold text-gray-900">Leads</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Leads</h1>
|
||||||
<p className="text-sm text-gray-500 mt-1">Prospective customers pipeline</p>
|
<p className="text-sm text-gray-500 mt-1">Prospective customers pipeline</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => refetch()} variant="outline" size="sm">
|
<div className="flex gap-2">
|
||||||
<RefreshCw size={14} className="mr-1.5" /> Refresh
|
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
|
||||||
</Button>
|
<Button onClick={() => setShowAdd(true)} size="sm"><UserPlus size={14} className="mr-1" />Add Lead</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Status summary */}
|
{/* Pipeline summary */}
|
||||||
<div className="flex gap-3 flex-wrap">
|
<div className="flex gap-3 flex-wrap">
|
||||||
{Object.entries(statusVariant).map(([status]) => {
|
{statusOptions.map(status => (
|
||||||
const count = leads.filter(l => l.status === status).length;
|
<div key={status} className="bg-white border rounded-xl px-4 py-3 text-center min-w-[90px] shadow-sm">
|
||||||
return count > 0 ? (
|
<p className="text-2xl font-bold text-gray-800">{counts[status] ?? 0}</p>
|
||||||
<div key={status} className="bg-white border rounded-lg px-3 py-2 text-center min-w-[80px]">
|
<Badge variant={statusVariant[status] ?? "muted"} className="mt-1">{status}</Badge>
|
||||||
<p className="text-lg font-bold text-gray-800">{count}</p>
|
</div>
|
||||||
<p className="text-xs text-gray-500">{status}</p>
|
))}
|
||||||
</div>
|
<div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 text-center min-w-[90px]">
|
||||||
) : null;
|
<p className="text-2xl font-bold text-blue-700">{data.length}</p>
|
||||||
})}
|
<p className="text-xs text-blue-600 font-medium mt-1">TOTAL</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-center justify-between gap-4">
|
<div className="flex items-center justify-between gap-4">
|
||||||
<CardTitle>All Leads ({leads.length})</CardTitle>
|
<CardTitle>All Leads ({data.length})</CardTitle>
|
||||||
<Input
|
<input className="border rounded-lg px-3 py-2 text-sm max-w-xs w-full focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
placeholder="Search by name or phone..."
|
placeholder="Search by name or phone..."
|
||||||
value={search}
|
value={search} onChange={e => setSearch(e.target.value)} />
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
className="max-w-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead>
|
||||||
<TableRow>
|
<TableRow><Th>Name</Th><Th>Phone</Th><Th>Email</Th><Th>Address</Th><Th>Status</Th><Th>Source</Th><Th>Added</Th></TableRow>
|
||||||
<Th>Name</Th>
|
|
||||||
<Th>Phone</Th>
|
|
||||||
<Th>Email</Th>
|
|
||||||
<Th>Address</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Assigned To</Th>
|
|
||||||
<Th>Added</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<TableRow><Td colSpan={7} className="text-center py-8 text-gray-400">Loading...</Td></TableRow>
|
Array.from({ length: 6 }).map((_, i) => (
|
||||||
) : leads.length === 0 ? (
|
<TableRow key={i}><Td colSpan={7}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
|
||||||
<EmptyState colSpan={7} message="No leads yet" icon={<UserPlus size={24} />} />
|
|
||||||
) : (
|
|
||||||
leads.map((lead) => (
|
|
||||||
<TableRow key={lead.id}>
|
|
||||||
<Td className="font-medium">{lead.firstName} {lead.lastName}</Td>
|
|
||||||
<Td>{lead.phone}</Td>
|
|
||||||
<Td className="text-gray-500">{lead.email ?? "—"}</Td>
|
|
||||||
<Td className="text-gray-500 max-w-[150px] truncate">{lead.address ?? "—"}</Td>
|
|
||||||
<Td>
|
|
||||||
<Badge variant={statusVariant[lead.status] ?? "muted"}>
|
|
||||||
{lead.status}
|
|
||||||
</Badge>
|
|
||||||
</Td>
|
|
||||||
<Td className="text-gray-500">
|
|
||||||
{lead.assignedTo
|
|
||||||
? `${lead.assignedTo.firstName} ${lead.assignedTo.lastName}`
|
|
||||||
: "—"}
|
|
||||||
</Td>
|
|
||||||
<Td className="text-gray-400 text-sm">{formatDate(lead.createdAt)}</Td>
|
|
||||||
</TableRow>
|
|
||||||
))
|
))
|
||||||
)}
|
) : data.length === 0 ? (
|
||||||
|
<EmptyState colSpan={7} message="No leads yet" icon={<UserPlus size={24} />} />
|
||||||
|
) : data.map(lead => (
|
||||||
|
<TableRow key={lead.id} onClick={() => { setSelected(lead); setStatusUpdate(lead.status); }}
|
||||||
|
className="cursor-pointer hover:bg-blue-50 transition-colors">
|
||||||
|
<Td className="font-medium">{lead.firstName} {lead.lastName}</Td>
|
||||||
|
<Td>{lead.phone}</Td>
|
||||||
|
<Td className="text-gray-500">{lead.email ?? "—"}</Td>
|
||||||
|
<Td className="text-gray-500 max-w-[150px] truncate">{lead.address ?? "—"}</Td>
|
||||||
|
<Td><Badge variant={statusVariant[lead.status] ?? "muted"}>{lead.status}</Badge></Td>
|
||||||
|
<Td className="text-gray-400 text-sm">{lead.source ?? "—"}</Td>
|
||||||
|
<Td className="text-gray-400 text-xs">{formatDate(lead.createdAt)}</Td>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Lead Detail Modal */}
|
||||||
|
<Modal isOpen={!!selected} onClose={() => setSelected(null)} title={`${selected?.firstName ?? ""} ${selected?.lastName ?? ""}`}>
|
||||||
|
{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">Phone</span><span className="font-medium">{selected.phone}</span></div>
|
||||||
|
{selected.email && <div className="flex justify-between"><span className="text-gray-500">Email</span><span>{selected.email}</span></div>}
|
||||||
|
{selected.address && <div className="flex justify-between"><span className="text-gray-500">Address</span><span className="text-right max-w-[200px]">{selected.address}</span></div>}
|
||||||
|
{selected.source && <div className="flex justify-between"><span className="text-gray-500">Source</span><span>{selected.source}</span></div>}
|
||||||
|
{selected.notes && <div className="flex justify-between items-start"><span className="text-gray-500">Notes</span><span className="text-right max-w-[200px]">{selected.notes}</span></div>}
|
||||||
|
<div className="flex justify-between"><span className="text-gray-500">Added</span><span>{formatDate(selected.createdAt)}</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Update Status</label>
|
||||||
|
<div className="flex gap-2 flex-wrap">
|
||||||
|
{statusOptions.map(s => (
|
||||||
|
<button key={s} onClick={() => setStatusUpdate(s)}
|
||||||
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors border ${statusUpdate === s ? "border-blue-600 bg-blue-600 text-white" : "border-gray-200 text-gray-600 hover:border-blue-400"}`}>
|
||||||
|
{s}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{statusUpdate !== selected.status && (
|
||||||
|
<Button size="sm" className="mt-1" onClick={() => updateStatus.mutate({ id: selected.id, status: statusUpdate })} isLoading={updateStatus.isPending}>
|
||||||
|
Update to {statusUpdate}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-between pt-1">
|
||||||
|
<Button variant="danger" size="sm" onClick={() => { if (confirm("Delete this lead?")) deleteLead.mutate(selected.id); }} isLoading={deleteLead.isPending}>Delete</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setSelected(null)}>Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Add Lead Modal */}
|
||||||
|
<Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add New Lead">
|
||||||
|
<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="Phone *" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
|
||||||
|
<Input label="Email" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
|
||||||
|
<Input label="Address" value={form.address} onChange={e => setForm(f => ({ ...f, address: e.target.value }))} />
|
||||||
|
<Input label="Source (e.g. Facebook, Referral)" value={form.source} onChange={e => setForm(f => ({ ...f, source: e.target.value }))} />
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Notes</label>
|
||||||
|
<textarea className="border rounded-lg px-3 py-2 text-sm resize-none h-16 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} />
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setShowAdd(false)}>Cancel</Button>
|
||||||
|
<Button onClick={() => addLead.mutate()} isLoading={addLead.isPending} disabled={!form.firstName || !form.lastName || !form.phone}>Add Lead</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,136 +1,177 @@
|
|||||||
'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 { RefreshCw, CreditCard, AlertCircle } from "lucide-react";
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader } from "@/components/ui/Card";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { Search } from 'lucide-react';
|
import { Button } from "@/components/ui/Button";
|
||||||
import { format } from 'date-fns';
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { formatDate, formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
interface Payment {
|
interface Payment {
|
||||||
id: string;
|
id: string; clientId: string;
|
||||||
amount: string;
|
|
||||||
channel: string;
|
|
||||||
paymentDate: string;
|
|
||||||
notes: string | null;
|
|
||||||
client?: { firstName: string; lastName: string; accountNumber: string };
|
client?: { firstName: string; lastName: string; accountNumber: string };
|
||||||
|
invoice?: { invoiceNumber: string; total: string };
|
||||||
|
invoiceId?: string;
|
||||||
|
amount: string; channel: string;
|
||||||
|
referenceNumber?: string; orNumber?: string; notes?: string;
|
||||||
|
paymentDate?: string; createdAt: string;
|
||||||
recordedBy?: { firstName: string; lastName: string };
|
recordedBy?: { firstName: string; lastName: string };
|
||||||
invoice?: { invoiceNumber: string };
|
|
||||||
}
|
}
|
||||||
|
interface PaymentsResponse { data: Payment[]; total: number; page: number; limit: number; }
|
||||||
|
|
||||||
const channelColors: Record<string, string> = {
|
const channelVariant: Record<string, "success" | "warning" | "muted" | "default"> = {
|
||||||
CASH: 'bg-green-100 text-green-700',
|
CASH: "success", GCASH: "default", MAYA: "default", BANK_TRANSFER: "warning", CHECK: "muted",
|
||||||
GCASH: 'bg-blue-100 text-blue-700',
|
|
||||||
MAYA: 'bg-purple-100 text-purple-700',
|
|
||||||
BANK_TRANSFER: 'bg-orange-100 text-orange-700',
|
|
||||||
CHECK: 'bg-gray-100 text-gray-700',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const peso = (v: string | number) =>
|
const channelFilters = ["", "CASH", "GCASH", "MAYA", "BANK_TRANSFER", "CHECK"];
|
||||||
'₱' + Number(v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
|
|
||||||
|
|
||||||
export default function PaymentsPage() {
|
export default function PaymentsPage() {
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState("");
|
||||||
const [channelFilter, setChannelFilter] = useState('');
|
const [channelFilter, setChannelFilter] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const [selected, setSelected] = useState<Payment | null>(null);
|
||||||
|
|
||||||
const { data, isLoading } = useQuery<{ data: Payment[]; total: number }>({
|
const { data, isLoading, isError, refetch } = useQuery<PaymentsResponse>({
|
||||||
queryKey: ['payments', search, channelFilter, page],
|
queryKey: ["payments", search, channelFilter, page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ page: String(page), limit: '20' });
|
const params = new URLSearchParams({ page: String(page), limit: "20" });
|
||||||
if (channelFilter) params.set('channel', channelFilter);
|
if (search) params.set("search", search);
|
||||||
const res = await api.get(`/api/v1/payments?${params}`);
|
if (channelFilter) params.set("channel", channelFilter);
|
||||||
|
const res = await api.get<PaymentsResponse>(`/api/v1/payments?${params}`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
staleTime: 30_000,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const payments = data?.data ?? [];
|
const payments = data?.data ?? [];
|
||||||
const total = data?.total ?? 0;
|
const total = data?.total ?? 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Payments</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Payments</h1>
|
||||||
<p className="text-slate-500 text-sm mt-1">{total} payments</p>
|
<p className="text-sm text-gray-500 mt-1">{total} total payments</p>
|
||||||
</div>
|
</div>
|
||||||
|
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-3 mb-4">
|
<Card>
|
||||||
<div className="relative flex-1">
|
<CardHeader>
|
||||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
<div className="flex flex-wrap gap-3 items-center">
|
||||||
<Input placeholder="Search..." className="pl-9" value={search}
|
<input className="flex-1 min-w-[200px] border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
|
placeholder="Search by client..."
|
||||||
</div>
|
value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
|
||||||
<select
|
<div className="flex gap-2 flex-wrap">
|
||||||
className="border rounded-md px-3 py-2 text-sm text-slate-700 bg-white"
|
{channelFilters.map(c => (
|
||||||
value={channelFilter}
|
<button key={c} onClick={() => { setChannelFilter(c); setPage(1); }}
|
||||||
onChange={(e) => { setChannelFilter(e.target.value); setPage(1); }}
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${channelFilter === c ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
|
||||||
>
|
{c || "All"}
|
||||||
<option value="">All Channels</option>
|
</button>
|
||||||
{['CASH', 'GCASH', 'MAYA', 'BANK_TRANSFER', 'CHECK'].map((c) => (
|
))}
|
||||||
<option key={c} value={c}>{c.replace('_', ' ')}</option>
|
</div>
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<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">Date</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Client</th>
|
|
||||||
<th className="text-right px-4 py-3 font-medium text-slate-500">Amount</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Channel</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Recorded By</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Invoice</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{isLoading
|
|
||||||
? Array.from({ length: 8 }).map((_, i) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
{Array.from({ length: 6 }).map((_, j) => (
|
|
||||||
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
: payments.map((p) => (
|
|
||||||
<tr key={p.id} className="border-b hover:bg-slate-50 transition-colors">
|
|
||||||
<td className="px-4 py-3 text-slate-600">
|
|
||||||
{p.paymentDate ? format(new Date(p.paymentDate), 'MMM d, yyyy') : '—'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-700 hidden md:table-cell">
|
|
||||||
{p.client ? `${p.client.firstName} ${p.client.lastName}` : '—'}
|
|
||||||
<div className="text-xs text-slate-400">{p.client?.accountNumber}</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-right font-semibold text-slate-800">{peso(p.amount)}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${channelColors[p.channel] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{p.channel?.replace('_', ' ')}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
|
|
||||||
{p.recordedBy ? `${p.recordedBy.firstName} ${p.recordedBy.lastName}` : '—'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-500 font-mono text-xs hidden xl:table-cell">
|
|
||||||
{p.invoice?.invoiceNumber ?? '—'}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
{!isLoading && payments.length === 0 && (
|
</CardHeader>
|
||||||
<div className="text-center py-12 text-slate-400">No payments found</div>
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow><Th>Date</Th><Th>Client</Th><Th>Amount</Th><Th>Method</Th><Th>Reference</Th><Th>Invoice</Th><Th></Th></TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 8 }).map((_, i) => (
|
||||||
|
<TableRow key={i}><Td colSpan={7}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
|
||||||
|
))
|
||||||
|
) : isError ? (
|
||||||
|
<TableRow><Td colSpan={7}><div className="flex items-center gap-2 py-6 justify-center text-red-400 text-sm"><AlertCircle size={16} />Failed to load payments. <button onClick={() => refetch()} className="underline">Retry</button></div></Td></TableRow>
|
||||||
|
) : payments.length === 0 ? (
|
||||||
|
<EmptyState colSpan={7} message="No payments found" icon={<CreditCard size={24} />} />
|
||||||
|
) : payments.map(p => (
|
||||||
|
<TableRow key={p.id} data-testid="payment-row" onClick={() => setSelected(p)} className="cursor-pointer hover:bg-blue-50 transition-colors">
|
||||||
|
<Td className="text-sm">{p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</Td>
|
||||||
|
<Td className="font-medium">
|
||||||
|
{p.client ? `${p.client.firstName} ${p.client.lastName}` : "—"}
|
||||||
|
<div className="text-xs text-gray-400">{p.client?.accountNumber}</div>
|
||||||
|
</Td>
|
||||||
|
<Td className="font-semibold text-green-700">{formatCurrency(Number(p.amount))}</Td>
|
||||||
|
<Td><Badge variant={channelVariant[p.channel] ?? "muted"}>{p.channel}</Badge></Td>
|
||||||
|
<Td className="text-xs text-gray-500">{p.referenceNumber ?? p.orNumber ?? "—"}</Td>
|
||||||
|
<Td className="text-xs font-mono text-gray-500">{p.invoice?.invoiceNumber ?? (p.invoiceId ? p.invoiceId.slice(0, 8) : "—")}</Td>
|
||||||
|
<Td className="text-gray-400 text-xs">View →</Td>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
{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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Payment Detail Modal */}
|
||||||
|
<Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Payment Details">
|
||||||
|
{selected && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="bg-gray-50 rounded-lg p-4 space-y-2.5 text-sm">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Client</span>
|
||||||
|
<span className="font-medium">{selected.client ? `${selected.client.firstName} ${selected.client.lastName}` : "—"}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Account #</span>
|
||||||
|
<span className="font-mono text-xs">{selected.client?.accountNumber ?? "—"}</span>
|
||||||
|
</div>
|
||||||
|
<hr />
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Amount</span>
|
||||||
|
<span className="text-xl font-bold text-green-700">{formatCurrency(Number(selected.amount))}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Method</span>
|
||||||
|
<Badge variant={channelVariant[selected.channel] ?? "muted"}>{selected.channel}</Badge>
|
||||||
|
</div>
|
||||||
|
{(selected.referenceNumber || selected.orNumber) && (
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Reference #</span>
|
||||||
|
<span className="font-mono text-xs">{selected.referenceNumber ?? selected.orNumber}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Invoice</span>
|
||||||
|
<span className="font-mono text-xs">{selected.invoice?.invoiceNumber ?? (selected.invoiceId ? selected.invoiceId.slice(0, 8) : "—")}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Payment Date</span>
|
||||||
|
<span>{selected.paymentDate ? formatDate(selected.paymentDate) : formatDate(selected.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
{selected.notes && (
|
||||||
|
<div className="flex justify-between items-start">
|
||||||
|
<span className="text-gray-500">Notes</span>
|
||||||
|
<span className="text-right max-w-[200px]">{selected.notes}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{selected.recordedBy && (
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-gray-500">Recorded By</span>
|
||||||
|
<span>{selected.recordedBy.firstName} {selected.recordedBy.lastName}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button variant="outline" onClick={() => setSelected(null)}>Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
393
app/(app)/plans/page.tsx
Normal file
393
app/(app)/plans/page.tsx
Normal file
@@ -0,0 +1,393 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { RefreshCw, Package, Plus, Pencil, Trash2 } from "lucide-react";
|
||||||
|
import { Card, CardContent, CardHeader } 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 { Input } from "@/components/ui/Input";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
interface Plan {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: "PREPAID" | "POSTPAID";
|
||||||
|
speedDownMbps: number;
|
||||||
|
speedUpMbps: number;
|
||||||
|
monthlyPrice: string | number;
|
||||||
|
description?: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const typeVariant: Record<string, "success" | "muted"> = {
|
||||||
|
PREPAID: "success",
|
||||||
|
POSTPAID: "muted",
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyForm = {
|
||||||
|
name: "",
|
||||||
|
type: "POSTPAID" as "PREPAID" | "POSTPAID",
|
||||||
|
speedDownMbps: "",
|
||||||
|
speedUpMbps: "",
|
||||||
|
monthlyPrice: "",
|
||||||
|
description: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function PlansPage() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
|
||||||
|
// Modals
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [editPlan, setEditPlan] = useState<Plan | null>(null);
|
||||||
|
const [deletePlan, setDeletePlan] = useState<Plan | null>(null);
|
||||||
|
|
||||||
|
// Forms
|
||||||
|
const [createForm, setCreateForm] = useState({ ...emptyForm });
|
||||||
|
const [editForm, setEditForm] = useState({ ...emptyForm });
|
||||||
|
|
||||||
|
// GET /plans returns a plain array (not paginated)
|
||||||
|
const { data: allPlans = [], isLoading, isError, refetch } = useQuery<Plan[]>({
|
||||||
|
queryKey: ["plans"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<Plan[] | { data: Plan[] }>("/api/v1/plans");
|
||||||
|
return Array.isArray(res.data) ? res.data : (res.data as any).data ?? [];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Client-side search filter
|
||||||
|
const plans = search
|
||||||
|
? allPlans.filter(p =>
|
||||||
|
p.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
p.type.toLowerCase().includes(search.toLowerCase())
|
||||||
|
)
|
||||||
|
: allPlans;
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/plans", {
|
||||||
|
name: createForm.name,
|
||||||
|
type: createForm.type,
|
||||||
|
speedDownMbps: Number(createForm.speedDownMbps),
|
||||||
|
speedUpMbps: Number(createForm.speedUpMbps),
|
||||||
|
monthlyPrice: Number(createForm.monthlyPrice),
|
||||||
|
description: createForm.description || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Plan created!");
|
||||||
|
setShowCreate(false);
|
||||||
|
setCreateForm({ ...emptyForm });
|
||||||
|
qc.invalidateQueries({ queryKey: ["plans"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create plan"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.patch(`/api/v1/plans/${editPlan!.id}`, {
|
||||||
|
name: editForm.name,
|
||||||
|
type: editForm.type,
|
||||||
|
speedDownMbps: Number(editForm.speedDownMbps),
|
||||||
|
speedUpMbps: Number(editForm.speedUpMbps),
|
||||||
|
monthlyPrice: Number(editForm.monthlyPrice),
|
||||||
|
description: editForm.description || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Plan updated!");
|
||||||
|
setEditPlan(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["plans"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to update plan"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.delete(`/api/v1/plans/${deletePlan!.id}`);
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Plan deleted!");
|
||||||
|
setDeletePlan(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["plans"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to delete plan"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const openEdit = (plan: Plan) => {
|
||||||
|
setEditForm({
|
||||||
|
name: plan.name,
|
||||||
|
type: plan.type,
|
||||||
|
speedDownMbps: String(plan.speedDownMbps),
|
||||||
|
speedUpMbps: String(plan.speedUpMbps),
|
||||||
|
monthlyPrice: String(plan.monthlyPrice),
|
||||||
|
description: plan.description ?? "",
|
||||||
|
});
|
||||||
|
setEditPlan(plan);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Plans</h1>
|
||||||
|
<p className="text-sm text-gray-500 mt-1">{allPlans.length} total plans</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button onClick={() => refetch()} variant="outline" size="sm" data-testid="btn-refresh">
|
||||||
|
<RefreshCw size={14} className="mr-1" />Refresh
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setShowCreate(true)} size="sm" data-testid="btn-add-plan">
|
||||||
|
<Plus size={14} className="mr-1" />Add Plan
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<input
|
||||||
|
className="w-full max-w-sm border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
placeholder="Search plans..."
|
||||||
|
value={search}
|
||||||
|
onChange={e => setSearch(e.target.value)}
|
||||||
|
data-testid="input-search"
|
||||||
|
/>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<Th>Name</Th>
|
||||||
|
<Th>Type</Th>
|
||||||
|
<Th>Speed (Down/Up)</Th>
|
||||||
|
<Th>Monthly Price</Th>
|
||||||
|
<Th>Status</Th>
|
||||||
|
<Th>Description</Th>
|
||||||
|
<Th></Th>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 5 }).map((_, i) => (
|
||||||
|
<TableRow key={i}>
|
||||||
|
<Td colSpan={7}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
) : isError ? (
|
||||||
|
<TableRow>
|
||||||
|
<Td colSpan={7}>
|
||||||
|
<p className="text-center py-6 text-red-400 text-sm">
|
||||||
|
Failed to load plans.{" "}
|
||||||
|
<button onClick={() => refetch()} className="underline">Retry</button>
|
||||||
|
</p>
|
||||||
|
</Td>
|
||||||
|
</TableRow>
|
||||||
|
) : plans.length === 0 ? (
|
||||||
|
<EmptyState colSpan={7} message="No plans found" icon={<Package size={24} />} />
|
||||||
|
) : (
|
||||||
|
plans.map(plan => (
|
||||||
|
<TableRow key={plan.id} data-testid="plan-row">
|
||||||
|
<Td className="font-medium">{plan.name}</Td>
|
||||||
|
<Td>
|
||||||
|
<Badge variant={typeVariant[plan.type] ?? "muted"}>{plan.type}</Badge>
|
||||||
|
</Td>
|
||||||
|
<Td className="font-mono text-sm">{plan.speedDownMbps}/{plan.speedUpMbps} Mbps</Td>
|
||||||
|
<Td className="font-semibold">{formatCurrency(Number(plan.monthlyPrice))}</Td>
|
||||||
|
<Td>
|
||||||
|
<Badge variant={plan.isActive ? "success" : "muted"}>
|
||||||
|
{plan.isActive ? "Active" : "Inactive"}
|
||||||
|
</Badge>
|
||||||
|
</Td>
|
||||||
|
<Td className="text-gray-500 text-sm max-w-xs truncate">{plan.description ?? "—"}</Td>
|
||||||
|
<Td>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button
|
||||||
|
onClick={() => openEdit(plan)}
|
||||||
|
className="p-1.5 rounded hover:bg-blue-50 text-blue-600 transition-colors"
|
||||||
|
data-testid="btn-edit-plan"
|
||||||
|
title="Edit plan"
|
||||||
|
>
|
||||||
|
<Pencil size={14} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setDeletePlan(plan)}
|
||||||
|
className="p-1.5 rounded hover:bg-red-50 text-red-500 transition-colors"
|
||||||
|
data-testid="btn-delete-plan"
|
||||||
|
title="Delete plan"
|
||||||
|
>
|
||||||
|
<Trash2 size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Td>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Create Plan Modal */}
|
||||||
|
<Modal isOpen={showCreate} onClose={() => { setShowCreate(false); setCreateForm({ ...emptyForm }); }} title="Add Plan" className="max-w-md">
|
||||||
|
<div className="space-y-4" data-testid="modal-create-plan">
|
||||||
|
<Input
|
||||||
|
label="Plan Name"
|
||||||
|
value={createForm.name}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, name: e.target.value }))}
|
||||||
|
placeholder="e.g. Basic 25Mbps"
|
||||||
|
data-testid="input-plan-name"
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Type</label>
|
||||||
|
<select
|
||||||
|
className="border rounded-lg px-3 py-2 text-sm"
|
||||||
|
value={createForm.type}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, type: e.target.value as "PREPAID" | "POSTPAID" }))}
|
||||||
|
data-testid="select-plan-type"
|
||||||
|
>
|
||||||
|
<option value="POSTPAID">POSTPAID</option>
|
||||||
|
<option value="PREPAID">PREPAID</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Download (Mbps)"
|
||||||
|
type="number"
|
||||||
|
value={createForm.speedDownMbps}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, speedDownMbps: e.target.value }))}
|
||||||
|
placeholder="e.g. 25"
|
||||||
|
data-testid="input-plan-speed-down"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Upload (Mbps)"
|
||||||
|
type="number"
|
||||||
|
value={createForm.speedUpMbps}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, speedUpMbps: e.target.value }))}
|
||||||
|
placeholder="e.g. 10"
|
||||||
|
data-testid="input-plan-speed-up"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Monthly Price (₱)"
|
||||||
|
type="number"
|
||||||
|
value={createForm.monthlyPrice}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, monthlyPrice: e.target.value }))}
|
||||||
|
placeholder="e.g. 999"
|
||||||
|
data-testid="input-plan-price"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Description (optional)"
|
||||||
|
value={createForm.description}
|
||||||
|
onChange={e => setCreateForm(f => ({ ...f, description: e.target.value }))}
|
||||||
|
placeholder="e.g. Perfect for households"
|
||||||
|
data-testid="input-plan-description"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2 justify-end pt-2">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => { setShowCreate(false); setCreateForm({ ...emptyForm }); }}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => createMutation.mutate()}
|
||||||
|
isLoading={createMutation.isPending}
|
||||||
|
disabled={!createForm.name || !createForm.speedDownMbps || !createForm.speedUpMbps || !createForm.monthlyPrice}
|
||||||
|
data-testid="btn-submit-create"
|
||||||
|
>
|
||||||
|
Create Plan
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Edit Plan Modal */}
|
||||||
|
<Modal isOpen={!!editPlan} onClose={() => setEditPlan(null)} title={`Edit Plan: ${editPlan?.name ?? ""}`} className="max-w-md">
|
||||||
|
<div className="space-y-4" data-testid="modal-edit-plan">
|
||||||
|
<Input
|
||||||
|
label="Plan Name"
|
||||||
|
value={editForm.name}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, name: e.target.value }))}
|
||||||
|
data-testid="input-edit-name"
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Type</label>
|
||||||
|
<select
|
||||||
|
className="border rounded-lg px-3 py-2 text-sm"
|
||||||
|
value={editForm.type}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, type: e.target.value as "PREPAID" | "POSTPAID" }))}
|
||||||
|
data-testid="select-edit-type"
|
||||||
|
>
|
||||||
|
<option value="POSTPAID">POSTPAID</option>
|
||||||
|
<option value="PREPAID">PREPAID</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input
|
||||||
|
label="Download (Mbps)"
|
||||||
|
type="number"
|
||||||
|
value={editForm.speedDownMbps}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, speedDownMbps: e.target.value }))}
|
||||||
|
data-testid="input-edit-speed-down"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Upload (Mbps)"
|
||||||
|
type="number"
|
||||||
|
value={editForm.speedUpMbps}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, speedUpMbps: e.target.value }))}
|
||||||
|
data-testid="input-edit-speed-up"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
label="Monthly Price (₱)"
|
||||||
|
type="number"
|
||||||
|
value={editForm.monthlyPrice}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, monthlyPrice: e.target.value }))}
|
||||||
|
data-testid="input-edit-price"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Description (optional)"
|
||||||
|
value={editForm.description}
|
||||||
|
onChange={e => setEditForm(f => ({ ...f, description: e.target.value }))}
|
||||||
|
data-testid="input-edit-description"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2 justify-end pt-2">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setEditPlan(null)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => updateMutation.mutate()}
|
||||||
|
isLoading={updateMutation.isPending}
|
||||||
|
disabled={!editForm.name || !editForm.speedDownMbps || !editForm.speedUpMbps || !editForm.monthlyPrice}
|
||||||
|
data-testid="btn-submit-edit"
|
||||||
|
>
|
||||||
|
Save Changes
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Delete Confirmation Modal */}
|
||||||
|
<Modal isOpen={!!deletePlan} onClose={() => setDeletePlan(null)} title="Delete Plan" className="max-w-sm">
|
||||||
|
<div className="space-y-4" data-testid="modal-delete-plan">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Are you sure you want to delete <strong>{deletePlan?.name}</strong>? This action cannot be undone.
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-2 justify-end pt-2">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setDeletePlan(null)} data-testid="btn-cancel-delete">Cancel</Button>
|
||||||
|
<Button
|
||||||
|
variant="danger"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => deleteMutation.mutate()}
|
||||||
|
isLoading={deleteMutation.isPending}
|
||||||
|
data-testid="btn-confirm-delete"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,126 +1,223 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useState } from "react";
|
||||||
import { api } from '@/lib/api';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { RefreshCw, ArrowLeftRight, CheckCircle, Plus } from "lucide-react";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
import { ChevronRight, CheckCircle } from 'lucide-react';
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { format } from 'date-fns';
|
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 {
|
interface Remittance {
|
||||||
id: string;
|
id: string; collectorId?: string;
|
||||||
totalAmount: string;
|
collector?: { firstName: string; lastName: string };
|
||||||
notes: string | null;
|
totalAmount: number | string; notes?: string; status: string;
|
||||||
status: string;
|
payments?: Payment[]; createdAt: string;
|
||||||
createdAt: string;
|
|
||||||
collectedBy?: { firstName: string; lastName: string };
|
|
||||||
confirmedBy?: { firstName: string; lastName: string };
|
|
||||||
payments?: Array<{ id: string; amount: string }>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const peso = (v: string | number) =>
|
const statusVariant: Record<string, "success" | "warning" | "muted"> = {
|
||||||
'₱' + Number(v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
|
CONFIRMED: "success", PENDING: "warning", DISPUTED: "muted",
|
||||||
|
};
|
||||||
|
|
||||||
export default function RemittancesPage() {
|
export default function RemittancesPage() {
|
||||||
const qc = useQueryClient();
|
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 }>({
|
const { data: remittances = [], isLoading, refetch } = useQuery<Remittance[]>({
|
||||||
queryKey: ['remittances'],
|
queryKey: ["remittances"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await api.get('/api/v1/remittances?limit=30');
|
const res = await api.get("/api/v1/remittances?limit=50");
|
||||||
return res.data;
|
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({
|
const confirm = useMutation({
|
||||||
mutationFn: async (id: string) => {
|
mutationFn: async (id: string) => { await api.patch(`/api/v1/remittances/${id}/confirm`); },
|
||||||
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"),
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['remittances'] }),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
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 (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="mb-6">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Remittances</h1>
|
<div>
|
||||||
<p className="text-slate-500 text-sm mt-1">Cash collections submitted by collectors</p>
|
<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 data-testid="btn-submit-remittance" onClick={() => setShowSubmit(true)} size="sm"><Plus size={14} className="mr-1" />Submit Remittance</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="border shadow-sm">
|
<Card>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<div className="overflow-x-auto">
|
<Table>
|
||||||
<table className="w-full text-sm">
|
<TableHead>
|
||||||
<thead>
|
<TableRow><Th>Date</Th><Th>Collector</Th><Th>Amount</Th><Th>Status</Th><Th>Notes</Th><Th></Th></TableRow>
|
||||||
<tr className="border-b bg-slate-50">
|
</TableHead>
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Date</th>
|
<TableBody>
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Collector</th>
|
{isLoading ? (
|
||||||
<th className="text-right px-4 py-3 font-medium text-slate-500">Amount</th>
|
Array.from({ length: 5 }).map((_, i) => (
|
||||||
<th className="text-right px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Payments</th>
|
<TableRow key={i}><Td colSpan={6}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
|
||||||
<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>
|
) : remittances.length === 0 ? (
|
||||||
<th className="px-4 py-3"></th>
|
<EmptyState colSpan={6} message="No remittances yet" icon={<ArrowLeftRight size={24} />} />
|
||||||
</tr>
|
) : remittances.map(r => (
|
||||||
</thead>
|
<TableRow key={r.id} data-testid="remittance-row" onClick={() => setSelected(r)} className="cursor-pointer hover:bg-blue-50 transition-colors">
|
||||||
<tbody>
|
<Td>{formatDate(r.createdAt)}</Td>
|
||||||
{isLoading
|
<Td className="font-medium">{r.collector ? `${r.collector.firstName} ${r.collector.lastName}` : "—"}</Td>
|
||||||
? Array.from({ length: 6 }).map((_, i) => (
|
<Td className="font-semibold text-blue-700">{formatCurrency(Number(r.totalAmount))}</Td>
|
||||||
<tr key={i} className="border-b">
|
<Td><Badge variant={statusVariant[r.status] ?? "muted"}>{r.status}</Badge></Td>
|
||||||
{[...Array(7)].map((_, j) => (
|
<Td className="text-gray-500 text-sm">{r.notes ?? "—"}</Td>
|
||||||
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
|
<Td>
|
||||||
))}
|
{r.status === "PENDING" && (
|
||||||
</tr>
|
<Button size="sm" variant="secondary" data-testid="btn-confirm-remittance" onClick={e => { e.stopPropagation(); confirm.mutate(r.id); }}>
|
||||||
))
|
<CheckCircle size={13} className="mr-1" />Confirm
|
||||||
: remittances.map((r) => (
|
</Button>
|
||||||
<tr key={r.id} className="border-b hover:bg-slate-50 transition-colors">
|
)}
|
||||||
<td className="px-4 py-3 text-slate-600">
|
</Td>
|
||||||
{r.createdAt ? format(new Date(r.createdAt), 'MMM d, yyyy') : '—'}
|
</TableRow>
|
||||||
</td>
|
))}
|
||||||
<td className="px-4 py-3 text-slate-700 hidden md:table-cell">
|
</TableBody>
|
||||||
{r.collectedBy ? `${r.collectedBy.firstName} ${r.collectedBy.lastName}` : '—'}
|
</Table>
|
||||||
</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>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</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.totalAmount))}</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 ? p.clientId.slice(0, 8) : p.id.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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,193 +1,265 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { api } from '@/lib/api';
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
|
||||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';
|
|
||||||
|
|
||||||
const peso = (v: number) => '₱' + (v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line, CartesianGrid } from "recharts";
|
||||||
|
import { RefreshCw, TrendingUp, Users, AlertTriangle, DollarSign } from "lucide-react";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { Button } from "@/components/ui/Button";
|
||||||
|
import { Badge } from "@/components/ui/Badge";
|
||||||
|
import { formatCurrency } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
|
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,93 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
|
||||||
import { MapPin, Plus, ChevronRight } from 'lucide-react';
|
|
||||||
import { api } from '@/lib/api';
|
|
||||||
|
|
||||||
interface Zone {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
interface Area {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
zones?: Zone[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AreasPage() {
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey: ['areas'],
|
|
||||||
queryFn: async () => (await api.get('/api/v1/areas')).data,
|
|
||||||
});
|
|
||||||
|
|
||||||
const areas: Area[] = Array.isArray(data) ? data : (data?.data ?? []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="mb-6 flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Areas & Zones</h1>
|
|
||||||
<p className="text-slate-500 text-sm mt-1">Service area and coverage zones</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button variant="outline" size="sm">
|
|
||||||
<Plus size={14} className="mr-1.5" />Add Zone
|
|
||||||
</Button>
|
|
||||||
<Button style={{ backgroundColor: '#0891B2', color: 'white' }} size="sm">
|
|
||||||
<Plus size={14} className="mr-1.5" />Add Area
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{Array.from({ length: 3 }).map((_, i) => (
|
|
||||||
<Skeleton key={i} className="h-20 w-full rounded-xl" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : areas.length === 0 ? (
|
|
||||||
<div className="text-center py-16 text-slate-400">
|
|
||||||
<MapPin size={40} className="mx-auto mb-3 opacity-30" />
|
|
||||||
<p>No service areas yet</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{areas.map((area) => (
|
|
||||||
<Card key={area.id} className="hover:border-cyan-200 transition-colors">
|
|
||||||
<CardContent className="p-4">
|
|
||||||
<div className="flex items-start justify-between">
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<div className="w-8 h-8 rounded-lg bg-cyan-50 flex items-center justify-center mt-0.5">
|
|
||||||
<MapPin size={16} className="text-cyan-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold text-slate-800">{area.name}</p>
|
|
||||||
{area.description && <p className="text-sm text-slate-500 mt-0.5">{area.description}</p>}
|
|
||||||
{area.zones && area.zones.length > 0 && (
|
|
||||||
<div className="mt-2 flex gap-1.5 flex-wrap">
|
|
||||||
{area.zones.map(z => (
|
|
||||||
<span key={z.id} className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600">
|
|
||||||
{z.name}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-xs text-slate-400">{area.zones?.length ?? 0} zone{(area.zones?.length ?? 0) !== 1 ? 's' : ''}</span>
|
|
||||||
<ChevronRight size={16} className="text-slate-300" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</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>
|
||||||
@@ -285,16 +285,14 @@ function AreasSettings() {
|
|||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-center justify-between">
|
<CardTitle>Areas & Zones</CardTitle>
|
||||||
<CardTitle>Areas & Zones</CardTitle>
|
<div className="flex gap-2">
|
||||||
<div className="flex gap-2">
|
<Button size="sm" variant="outline" onClick={() => setShowAddArea(true)}>
|
||||||
<Button size="sm" variant="outline" onClick={() => setShowAddArea(true)}>
|
+ Area
|
||||||
+ Area
|
</Button>
|
||||||
</Button>
|
<Button size="sm" variant="outline" onClick={() => setShowAddZone(true)}>
|
||||||
<Button size="sm" variant="outline" onClick={() => setShowAddZone(true)}>
|
+ Zone
|
||||||
+ Zone
|
</Button>
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
@@ -399,12 +397,14 @@ function PlansSettings() {
|
|||||||
const [speedUp, setSpeedUp] = useState("");
|
const [speedUp, setSpeedUp] = useState("");
|
||||||
const [price, setPrice] = useState("");
|
const [price, setPrice] = useState("");
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
|
const [editPlan, setEditPlan] = useState<Plan | null>(null);
|
||||||
|
const [editForm, setEditForm] = useState({ name: "", type: "POSTPAID", speedDown: "", speedUp: "", price: "", description: "" });
|
||||||
|
|
||||||
const { data, isLoading, refetch } = useQuery<Plan[]>({
|
const { data, isLoading, refetch } = useQuery<Plan[]>({
|
||||||
queryKey: ["plans"],
|
queryKey: ["plans"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
try {
|
try {
|
||||||
const res = await api.get<Plan[] | { data: Plan[] }>("/api/v1/plans");
|
const res = await api.get<Plan[] | { data: Plan[] }>("/api/v1/plans?includeInactive=true");
|
||||||
const d = res.data;
|
const d = res.data;
|
||||||
return Array.isArray(d) ? d : (d as { data: Plan[] }).data ?? [];
|
return Array.isArray(d) ? d : (d as { data: Plan[] }).data ?? [];
|
||||||
} catch {
|
} catch {
|
||||||
@@ -444,6 +444,38 @@ function PlansSettings() {
|
|||||||
onError: () => toast.error("Failed to update plan"),
|
onError: () => toast.error("Failed to update plan"),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const editPlanMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
if (!editPlan) return;
|
||||||
|
await api.patch(`/api/v1/plans/${editPlan.id}`, {
|
||||||
|
name: editForm.name,
|
||||||
|
type: editForm.type,
|
||||||
|
speedDownMbps: parseInt(editForm.speedDown),
|
||||||
|
speedUpMbps: parseInt(editForm.speedUp),
|
||||||
|
monthlyPrice: parseFloat(editForm.price),
|
||||||
|
description: editForm.description || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Plan updated");
|
||||||
|
setEditPlan(null);
|
||||||
|
refetch();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Failed to update plan"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function openEdit(p: Plan) {
|
||||||
|
setEditPlan(p);
|
||||||
|
setEditForm({
|
||||||
|
name: p.name,
|
||||||
|
type: p.type,
|
||||||
|
speedDown: String(p.speedDownMbps),
|
||||||
|
speedUp: String(p.speedUpMbps),
|
||||||
|
price: String(Number(p.monthlyPrice)),
|
||||||
|
description: p.description ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function resetAdd() {
|
function resetAdd() {
|
||||||
setPlanName(""); setPlanType("POSTPAID");
|
setPlanName(""); setPlanType("POSTPAID");
|
||||||
setSpeedDown(""); setSpeedUp(""); setPrice(""); setDescription("");
|
setSpeedDown(""); setSpeedUp(""); setPrice(""); setDescription("");
|
||||||
@@ -455,12 +487,10 @@ function PlansSettings() {
|
|||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-center justify-between">
|
<CardTitle>Plans</CardTitle>
|
||||||
<CardTitle>Plans</CardTitle>
|
<Button size="sm" onClick={() => setShowAdd(true)}>
|
||||||
<Button size="sm" onClick={() => setShowAdd(true)}>
|
+ Add Plan
|
||||||
+ Add Plan
|
</Button>
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<Table>
|
<Table>
|
||||||
@@ -498,13 +528,22 @@ function PlansSettings() {
|
|||||||
</Badge>
|
</Badge>
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
<Button
|
<div className="flex items-center gap-1">
|
||||||
size="sm"
|
<Button
|
||||||
variant="ghost"
|
size="sm"
|
||||||
onClick={() => toggleActiveMutation.mutate({ id: p.id, isActive: p.isActive })}
|
variant="ghost"
|
||||||
>
|
onClick={() => openEdit(p)}
|
||||||
{p.isActive ? "Archive" : "Restore"}
|
>
|
||||||
</Button>
|
Edit
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => toggleActiveMutation.mutate({ id: p.id, isActive: p.isActive })}
|
||||||
|
>
|
||||||
|
{p.isActive ? "Archive" : "Restore"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</Td>
|
</Td>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
@@ -514,6 +553,34 @@ function PlansSettings() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Edit Plan Modal */}
|
||||||
|
<Modal isOpen={!!editPlan} onClose={() => setEditPlan(null)} title="Edit Plan" className="max-w-lg">
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); editPlanMutation.mutate(); }} className="space-y-4">
|
||||||
|
<Input label="Plan Name" value={editForm.name} onChange={(e) => setEditForm(f => ({ ...f, name: e.target.value }))} />
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Type</label>
|
||||||
|
<select
|
||||||
|
className="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={editForm.type}
|
||||||
|
onChange={(e) => setEditForm(f => ({ ...f, type: e.target.value }))}
|
||||||
|
>
|
||||||
|
<option value="POSTPAID">Postpaid</option>
|
||||||
|
<option value="PREPAID">Prepaid</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Input label="Download (Mbps)" type="number" min="1" value={editForm.speedDown} onChange={(e) => setEditForm(f => ({ ...f, speedDown: e.target.value }))} />
|
||||||
|
<Input label="Upload (Mbps)" type="number" min="1" value={editForm.speedUp} onChange={(e) => setEditForm(f => ({ ...f, speedUp: e.target.value }))} />
|
||||||
|
</div>
|
||||||
|
<Input label="Monthly Price (₱)" type="number" min="0" step="0.01" value={editForm.price} onChange={(e) => setEditForm(f => ({ ...f, price: e.target.value }))} />
|
||||||
|
<Input label="Description (optional)" value={editForm.description} onChange={(e) => setEditForm(f => ({ ...f, description: e.target.value }))} />
|
||||||
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setEditPlan(null)}>Cancel</Button>
|
||||||
|
<Button type="submit" size="sm" isLoading={editPlanMutation.isPending}>Save Changes</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
{/* Add Plan Modal */}
|
{/* Add Plan Modal */}
|
||||||
<Modal isOpen={showAdd} onClose={() => { setShowAdd(false); resetAdd(); }} title="Add Plan" className="max-w-lg">
|
<Modal isOpen={showAdd} onClose={() => { setShowAdd(false); resetAdd(); }} title="Add Plan" className="max-w-lg">
|
||||||
<form onSubmit={(e) => { e.preventDefault(); addPlanMutation.mutate(); }} className="space-y-4">
|
<form onSubmit={(e) => { e.preventDefault(); addPlanMutation.mutate(); }} className="space-y-4">
|
||||||
@@ -559,15 +626,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 +646,99 @@ 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>
|
<CardTitle>Users ({users.length})</CardTitle>
|
||||||
<TableHead>
|
<Button size="sm" onClick={() => setShowAdd(true)}>+ Add User</Button>
|
||||||
<TableRow>
|
</CardHeader>
|
||||||
<Th>Name</Th>
|
<CardContent className="p-0">
|
||||||
<Th>Email</Th>
|
<Table>
|
||||||
<Th>Status</Th>
|
<TableHead>
|
||||||
</TableRow>
|
<TableRow><Th>Name</Th><Th>Email</Th><Th>Role</Th><Th>Status</Th><Th>Actions</Th></TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
Array.from({ length: 3 }).map((_, i) => (
|
Array.from({ length: 3 }).map((_, i) => (
|
||||||
<TableRow key={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>
|
||||||
{[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.length === 0 ? (
|
) : users.map(u => {
|
||||||
<EmptyState message="No users found" />
|
const role = u.roleAssignments?.[0]?.role ?? "—";
|
||||||
) : (
|
return (
|
||||||
users.map((u) => (
|
<TableRow key={u.id}>
|
||||||
<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="font-medium">{u.firstName} {u.lastName}</Td>
|
<Td className="text-sm text-gray-600">{u.email}</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>
|
<Td><Badge variant={u.isActive ? "success" : "muted"}>{u.isActive ? "Active" : "Inactive"}</Badge></Td>
|
||||||
<Badge variant={u.isActive ? "success" : "muted"}>
|
<Td>
|
||||||
{u.isActive ? "Active" : "Inactive"}
|
<Button size="sm" variant="ghost" onClick={() => toggleActive.mutate({ id: u.id, isActive: u.isActive })}>
|
||||||
</Badge>
|
{u.isActive ? "Deactivate" : "Activate"}
|
||||||
</Td>
|
</Button>
|
||||||
</TableRow>
|
</Td>
|
||||||
))
|
</TableRow>
|
||||||
)}
|
);
|
||||||
</TableBody>
|
})}
|
||||||
</Table>
|
</TableBody>
|
||||||
</CardContent>
|
</Table>
|
||||||
</Card>
|
</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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Plus } from 'lucide-react';
|
|
||||||
|
|
||||||
export default function PlansPage() {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="mb-6 flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Service Plans</h1>
|
|
||||||
<p className="text-slate-500 text-sm mt-1">Manage internet subscription plans</p>
|
|
||||||
</div>
|
|
||||||
<Button style={{ backgroundColor: '#0891B2' }}>
|
|
||||||
<Plus size={16} className="mr-2" />
|
|
||||||
Add Plan
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
|
||||||
<Card className="border shadow-sm border-dashed border-slate-300">
|
|
||||||
<CardContent className="flex flex-col items-center justify-center py-12 text-slate-400">
|
|
||||||
<Plus size={24} className="mb-2" />
|
|
||||||
<p className="text-sm">Create your first plan</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
|
|
||||||
export default function TenantSettingsPage() {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="mb-6">
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Tenant Settings</h1>
|
|
||||||
<p className="text-slate-500 text-sm mt-1">Configure your ISP business details</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card className="border shadow-sm max-w-2xl">
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-base">Business Information</CardTitle>
|
|
||||||
<CardDescription>Update your ISP company details</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label>Business Name</Label>
|
|
||||||
<Input placeholder="e.g. My Internet Services" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label>Address</Label>
|
|
||||||
<Input placeholder="Business address" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label>Phone</Label>
|
|
||||||
<Input placeholder="+63 9XX XXX XXXX" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label>Email</Label>
|
|
||||||
<Input type="email" placeholder="info@yourisp.com" />
|
|
||||||
</div>
|
|
||||||
<Button style={{ backgroundColor: '#0891B2' }}>Save Changes</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
'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 { Badge } from '@/components/ui/badge';
|
|
||||||
import { UserPlus } from 'lucide-react';
|
|
||||||
|
|
||||||
interface User {
|
|
||||||
id: string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
email: string;
|
|
||||||
isActive: boolean;
|
|
||||||
roles: Array<{ role: string }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const roleColors: Record<string, string> = {
|
|
||||||
ADMIN: 'bg-purple-100 text-purple-700',
|
|
||||||
STAFF: 'bg-blue-100 text-blue-700',
|
|
||||||
TECHNICIAN: 'bg-orange-100 text-orange-700',
|
|
||||||
COLLECTOR: 'bg-green-100 text-green-700',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function UsersSettingsPage() {
|
|
||||||
const qc = useQueryClient();
|
|
||||||
|
|
||||||
const { data: users, isLoading } = useQuery<User[]>({
|
|
||||||
queryKey: ['users'],
|
|
||||||
queryFn: async () => {
|
|
||||||
const res = await api.get('/api/v1/users');
|
|
||||||
return res.data;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const toggleActive = useMutation({
|
|
||||||
mutationFn: async ({ id, isActive }: { id: string; isActive: boolean }) => {
|
|
||||||
await api.patch(`/api/v1/users/${id}`, { isActive: !isActive });
|
|
||||||
},
|
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }),
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center justify-between mb-6">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Users</h1>
|
|
||||||
<p className="text-slate-500 text-sm mt-1">Manage staff access and roles</p>
|
|
||||||
</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 User
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card className="border shadow-sm">
|
|
||||||
<CardContent className="p-0">
|
|
||||||
<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">Name</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Email</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Role</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Status</th>
|
|
||||||
<th className="px-4 py-3"></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{isLoading
|
|
||||||
? Array.from({ length: 4 }).map((_, i) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
{[...Array(5)].map((_, j) => (
|
|
||||||
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
: users?.map((u) => {
|
|
||||||
const role = u.roles?.[0]?.role ?? 'STAFF';
|
|
||||||
return (
|
|
||||||
<tr key={u.id} className="border-b hover:bg-slate-50">
|
|
||||||
<td className="px-4 py-3 font-medium text-slate-800">
|
|
||||||
{u.firstName} {u.lastName}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600 hidden md:table-cell">{u.email}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${roleColors[role] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{role}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${u.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
|
||||||
{u.isActive ? 'Active' : 'Inactive'}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<button
|
|
||||||
onClick={() => toggleActive.mutate({ id: u.id, isActive: u.isActive })}
|
|
||||||
className="text-xs text-slate-500 hover:text-slate-800 underline"
|
|
||||||
>
|
|
||||||
{u.isActive ? 'Deactivate' : 'Activate'}
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,157 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { useEffect } from "react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { RefreshCw, Wifi, AlertCircle } from "lucide-react";
|
export default function SubscriptionsRedirect() {
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
|
||||||
import { Table, TableHead, TableBody, TableRow, Th, Td } from "@/components/ui/Table";
|
|
||||||
import { Badge } from "@/components/ui/Badge";
|
|
||||||
import { Button } from "@/components/ui/Button";
|
|
||||||
import { formatDate, formatCurrency } from "@/lib/utils";
|
|
||||||
import api from "@/lib/api";
|
|
||||||
import type { PaginatedResponse } from "@/types";
|
|
||||||
|
|
||||||
interface Subscription {
|
|
||||||
id: string;
|
|
||||||
clientId: string;
|
|
||||||
status: string;
|
|
||||||
startDate: string;
|
|
||||||
endDate?: string;
|
|
||||||
client?: { firstName: string; lastName: string; accountNumber: string };
|
|
||||||
plan?: { name: string; type: string; monthlyPrice: number };
|
|
||||||
planId?: string;
|
|
||||||
monthlyRate?: number;
|
|
||||||
mrc?: number;
|
|
||||||
type?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
|
||||||
ACTIVE: "success",
|
|
||||||
active: "success",
|
|
||||||
SUSPENDED: "warning",
|
|
||||||
suspended: "warning",
|
|
||||||
CANCELLED: "danger",
|
|
||||||
cancelled: "danger",
|
|
||||||
DISCONNECTED: "danger",
|
|
||||||
disconnected: "danger",
|
|
||||||
PENDING: "muted",
|
|
||||||
pending: "muted",
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function SubscriptionsPage() {
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
useEffect(() => { router.replace("/clients"); }, [router]);
|
||||||
const { data, isLoading, isError, error, refetch, isFetching } = useQuery<PaginatedResponse<Subscription>>({
|
return <div className="p-8 text-gray-400">Redirecting to clients…</div>;
|
||||||
queryKey: ["subscriptions"],
|
|
||||||
queryFn: async () => {
|
|
||||||
const res = await api.get<PaginatedResponse<Subscription>>("/api/v1/subscriptions?page=1&limit=50");
|
|
||||||
return res.data;
|
|
||||||
},
|
|
||||||
retry: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const subscriptions = data?.data ?? [];
|
|
||||||
const meta = data?.meta;
|
|
||||||
|
|
||||||
const isNotFound =
|
|
||||||
isError &&
|
|
||||||
(error as { response?: { status?: number } })?.response?.status === 404;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Subscriptions</h1>
|
|
||||||
<p className="text-sm text-gray-500">{meta?.total ?? 0} total subscriptions</p>
|
|
||||||
</div>
|
|
||||||
<Button size="sm" variant="outline" onClick={() => refetch()} disabled={isFetching}>
|
|
||||||
<RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
|
|
||||||
{isFetching ? "Checking…" : "Retry"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>All Subscriptions</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="p-0">
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="p-6 space-y-3">
|
|
||||||
{Array.from({ length: 4 }).map((_, i) => (
|
|
||||||
<div key={i} className="h-10 animate-pulse bg-gray-100 rounded-lg" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : isNotFound || (isError && !data) ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-center px-6">
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-50 mb-4">
|
|
||||||
<Wifi className="h-8 w-8 text-blue-400" />
|
|
||||||
</div>
|
|
||||||
<h3 className="text-base font-semibold text-gray-700 mb-2">Subscriptions Module Not Yet Available</h3>
|
|
||||||
<p className="text-sm text-gray-500 max-w-sm mb-4">
|
|
||||||
Subscription data will appear here once the module is deployed.
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 px-3 py-1.5 rounded-full mb-5">
|
|
||||||
<AlertCircle className="h-3.5 w-3.5" />
|
|
||||||
<span>API endpoint not yet available</span>
|
|
||||||
</div>
|
|
||||||
<Button variant="secondary" onClick={() => refetch()} disabled={isFetching}>
|
|
||||||
<RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
|
|
||||||
{isFetching ? "Checking…" : "Retry Now"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : subscriptions.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-center px-6">
|
|
||||||
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-gray-100 mb-3">
|
|
||||||
<Wifi className="h-7 w-7 text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-gray-500">No subscriptions yet.</p>
|
|
||||||
<Button variant="secondary" size="sm" className="mt-3" onClick={() => refetch()}>
|
|
||||||
<RefreshCw className="h-4 w-4" /> Refresh
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Table>
|
|
||||||
<TableHead>
|
|
||||||
<TableRow>
|
|
||||||
<Th>Client</Th>
|
|
||||||
<Th>Plan</Th>
|
|
||||||
<Th>Type</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Start Date</Th>
|
|
||||||
<Th>MRC</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
|
||||||
{subscriptions.map((sub) => (
|
|
||||||
<TableRow
|
|
||||||
key={sub.id}
|
|
||||||
className="hover:bg-gray-50 transition-colors cursor-pointer"
|
|
||||||
onClick={() => sub.clientId && router.push(`/clients/${sub.clientId}`)}
|
|
||||||
>
|
|
||||||
<Td>
|
|
||||||
{sub.client ? (
|
|
||||||
<div>
|
|
||||||
<p className="font-medium text-sm">{sub.client.firstName} {sub.client.lastName}</p>
|
|
||||||
<p className="text-xs text-gray-400 font-mono">{sub.client.accountNumber}</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400 text-sm">—</span>
|
|
||||||
)}
|
|
||||||
</Td>
|
|
||||||
<Td className="font-medium">{sub.plan?.name ?? sub.planId ?? "—"}</Td>
|
|
||||||
<Td><Badge variant="muted">{sub.plan?.type ?? sub.type ?? "—"}</Badge></Td>
|
|
||||||
<Td>
|
|
||||||
<Badge variant={statusVariant[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>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,123 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { useEffect } from "react";
|
||||||
import { useState } from "react";
|
import { useRouter } from "next/navigation";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
export default function TasksRedirect() {
|
||||||
import { ChevronLeft, ChevronRight, RefreshCw } from "lucide-react";
|
const router = useRouter();
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
useEffect(() => { router.replace("/tickets"); }, [router]);
|
||||||
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
return <div className="p-8 text-gray-400">Redirecting to tickets…</div>;
|
||||||
import { Badge } from "@/components/ui/Badge";
|
|
||||||
import { Button } from "@/components/ui/Button";
|
|
||||||
import { formatDate } from "@/lib/utils";
|
|
||||||
import api from "@/lib/api";
|
|
||||||
import type { Task, PaginatedResponse } from "@/types";
|
|
||||||
|
|
||||||
const statusVariant: Record<string, "success" | "warning" | "default" | "muted"> = {
|
|
||||||
done: "success",
|
|
||||||
DONE: "success",
|
|
||||||
completed: "success",
|
|
||||||
COMPLETED: "success",
|
|
||||||
in_progress: "default",
|
|
||||||
IN_PROGRESS: "default",
|
|
||||||
pending: "warning",
|
|
||||||
PENDING: "warning",
|
|
||||||
cancelled: "muted",
|
|
||||||
CANCELLED: "muted",
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function TasksPage() {
|
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
|
|
||||||
const { data, isLoading, refetch } = useQuery<PaginatedResponse<Task>>({
|
|
||||||
queryKey: ["tasks", page],
|
|
||||||
queryFn: async () => {
|
|
||||||
const res = await api.get<PaginatedResponse<Task>>(`/api/v1/manual-tasks?page=${page}&limit=20`);
|
|
||||||
return res.data;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const tasks = data?.data ?? [];
|
|
||||||
const meta = data?.meta;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Tasks</h1>
|
|
||||||
<p className="text-sm text-gray-500">{meta?.total ?? 0} total tasks</p>
|
|
||||||
</div>
|
|
||||||
<Button size="sm" variant="outline" onClick={() => refetch()}>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
Refresh
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader><CardTitle>All Tasks</CardTitle></CardHeader>
|
|
||||||
<CardContent className="p-0">
|
|
||||||
<Table>
|
|
||||||
<TableHead>
|
|
||||||
<TableRow>
|
|
||||||
<Th>Title</Th>
|
|
||||||
<Th>Type</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Assigned To</Th>
|
|
||||||
<Th>Due Date</Th>
|
|
||||||
<Th>Linked Ticket</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
|
||||||
{isLoading ? (
|
|
||||||
Array.from({ length: 5 }).map((_, i) => (
|
|
||||||
<TableRow key={i}>
|
|
||||||
{Array.from({ length: 6 }).map((_, j) => (
|
|
||||||
<Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
|
|
||||||
))}
|
|
||||||
</TableRow>
|
|
||||||
))
|
|
||||||
) : tasks.length === 0 ? (
|
|
||||||
<EmptyState message="No tasks yet" />
|
|
||||||
) : (
|
|
||||||
tasks.map((task) => (
|
|
||||||
<TableRow key={task.id} className="hover:bg-gray-50 transition-colors">
|
|
||||||
<Td className="font-medium">{task.type?.replace(/_/g," ")}</Td>
|
|
||||||
<Td><Badge variant="muted">{task.type}</Badge></Td>
|
|
||||||
<Td>
|
|
||||||
<Badge variant={statusVariant[task.status] ?? "muted"}>
|
|
||||||
{task.status}
|
|
||||||
</Badge>
|
|
||||||
</Td>
|
|
||||||
<Td className="text-gray-500">
|
|
||||||
{task.assignedUser
|
|
||||||
? `${task.assignedUser.firstName} ${task.assignedUser.lastName}`
|
|
||||||
: task.assignedTo ?? "—"}
|
|
||||||
</Td>
|
|
||||||
<Td className="text-gray-500">
|
|
||||||
{task.dueDate ? formatDate(task.dueDate) : "—"}
|
|
||||||
</Td>
|
|
||||||
<Td className="text-gray-400 text-xs font-mono">
|
|
||||||
{task.ticket?.subject ?? (task.ticketId ? task.ticketId.slice(0, 8) : "—")}
|
|
||||||
</Td>
|
|
||||||
</TableRow>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
|
|
||||||
{meta && meta.totalPages > 1 && (
|
|
||||||
<div className="flex items-center justify-between px-4 py-3 border-t border-gray-100">
|
|
||||||
<p className="text-sm text-gray-500">Page {meta.page} of {meta.totalPages}</p>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
|
||||||
<ChevronLeft className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)}>
|
|
||||||
<ChevronRight className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,168 +1,294 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api } from '@/lib/api';
|
import { RefreshCw, Ticket, Plus, Send } from "lucide-react";
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader } from "@/components/ui/Card";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Badge } from "@/components/ui/Badge";
|
||||||
import { Search, Plus, ChevronRight } from 'lucide-react';
|
import { Button } from "@/components/ui/Button";
|
||||||
import { format } from 'date-fns';
|
import { Input } from "@/components/ui/Input";
|
||||||
|
import { Modal } from "@/components/ui/Modal";
|
||||||
|
import { formatDate } from "@/lib/utils";
|
||||||
|
import api from "@/lib/api";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
interface Ticket {
|
interface TicketComment { id: string; body: string; createdAt: string; sender?: { firstName: string; lastName: string }; author?: { firstName: string; lastName: string }; }
|
||||||
id: string;
|
interface TicketItem {
|
||||||
subject: string;
|
id: string; ticketNumber?: string; subject: string; description?: string;
|
||||||
type: string;
|
type: string; priority: string; status: string; clientId?: string;
|
||||||
status: string;
|
client?: { id: string; firstName: string; lastName: string; accountNumber: string };
|
||||||
priority: string;
|
assignedTo?: { id: string; firstName: string; lastName: string } | string;
|
||||||
createdAt: string;
|
createdAt: string; updatedAt?: string;
|
||||||
client?: { firstName: string; lastName: string; accountNumber: string };
|
comments?: TicketComment[];
|
||||||
assignedTo?: { firstName: string; lastName: string };
|
|
||||||
}
|
}
|
||||||
|
interface PaginatedResponse<T> { data: T[]; meta: { total: number; page: number; limit: number; }; }
|
||||||
|
|
||||||
const statusColors: Record<string, string> = {
|
const statusVariant: Record<string, "success" | "warning" | "danger" | "muted"> = {
|
||||||
OPEN: 'bg-blue-100 text-blue-700',
|
OPEN: "warning", IN_PROGRESS: "default" as any, RESOLVED: "success", CLOSED: "muted",
|
||||||
IN_PROGRESS: 'bg-yellow-100 text-yellow-700',
|
};
|
||||||
RESOLVED: 'bg-green-100 text-green-700',
|
const priorityVariant: Record<string, "danger" | "warning" | "muted"> = {
|
||||||
CLOSED: 'bg-gray-100 text-gray-500',
|
HIGH: "danger", NORMAL: "muted", LOW: "muted",
|
||||||
};
|
};
|
||||||
|
|
||||||
const priorityColors: Record<string, string> = {
|
const statusFilters = ["", "OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"];
|
||||||
HIGH: 'bg-red-100 text-red-700',
|
const typeFilters = ["", "SUPPORT", "BILLING", "INSTALLATION"];
|
||||||
NORMAL: 'bg-slate-100 text-slate-600',
|
|
||||||
};
|
|
||||||
|
|
||||||
const typeColors: Record<string, string> = {
|
|
||||||
INSTALLATION: 'bg-cyan-100 text-cyan-700',
|
|
||||||
SUPPORT: 'bg-purple-100 text-purple-700',
|
|
||||||
BILLING: 'bg-orange-100 text-orange-700',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function TicketsPage() {
|
export default function TicketsPage() {
|
||||||
const [search, setSearch] = useState('');
|
const qc = useQueryClient();
|
||||||
const [statusFilter, setStatusFilter] = useState('');
|
const [search, setSearch] = useState("");
|
||||||
const [typeFilter, setTypeFilter] = useState('');
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
|
const [typeFilter, setTypeFilter] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const [selected, setSelected] = useState<TicketItem | null>(null);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [comment, setComment] = useState("");
|
||||||
|
const [newForm, setNewForm] = useState({ subject: "", description: "", type: "SUPPORT", priority: "NORMAL", clientSearch: "", clientId: "" });
|
||||||
|
|
||||||
const { data, isLoading } = useQuery<{ data: Ticket[]; total: number }>({
|
const { data, isLoading, refetch } = useQuery<PaginatedResponse<TicketItem>>({
|
||||||
queryKey: ['tickets', search, statusFilter, typeFilter, page],
|
queryKey: ["tickets", search, statusFilter, typeFilter, page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ page: String(page), limit: '20' });
|
const params = new URLSearchParams({ page: String(page), limit: "20" });
|
||||||
if (statusFilter) params.set('status', statusFilter);
|
if (search) params.set("search", search);
|
||||||
if (typeFilter) params.set('type', typeFilter);
|
if (statusFilter) params.set("status", statusFilter);
|
||||||
const res = await api.get(`/api/v1/tickets?${params}`);
|
if (typeFilter) params.set("type", typeFilter);
|
||||||
|
const res = await api.get<PaginatedResponse<TicketItem>>(`/api/v1/tickets?${params}`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
staleTime: 30_000,
|
});
|
||||||
|
|
||||||
|
const { data: ticketDetail, refetch: refetchDetail } = useQuery<TicketItem>({
|
||||||
|
queryKey: ["ticket", selected?.id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get<TicketItem>(`/api/v1/tickets/${selected!.id}`);
|
||||||
|
return res.data;
|
||||||
|
},
|
||||||
|
enabled: !!selected?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: clientSearch = [], isFetching: searchingClients } = useQuery({
|
||||||
|
queryKey: ["client-search", newForm.clientSearch],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!newForm.clientSearch || newForm.clientSearch.length < 2) return [];
|
||||||
|
const res = await api.get(`/api/v1/clients?search=${encodeURIComponent(newForm.clientSearch)}&limit=10`);
|
||||||
|
return res.data?.data ?? [];
|
||||||
|
},
|
||||||
|
enabled: newForm.clientSearch.length >= 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateStatus = useMutation({
|
||||||
|
mutationFn: async ({ id, status }: { id: string; status: string }) => {
|
||||||
|
await api.patch(`/api/v1/tickets/${id}`, { status });
|
||||||
|
},
|
||||||
|
onSuccess: () => { toast.success("Status updated"); refetch(); refetchDetail(); qc.invalidateQueries({ queryKey: ["ticket"] }); },
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const addComment = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post(`/api/v1/tickets/${selected!.id}/messages`, { body: comment });
|
||||||
|
},
|
||||||
|
onSuccess: () => { toast.success("Comment added"); setComment(""); refetchDetail(); },
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const createTicket = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
await api.post("/api/v1/tickets", {
|
||||||
|
subject: newForm.subject, description: newForm.description,
|
||||||
|
type: newForm.type, priority: newForm.priority,
|
||||||
|
clientId: newForm.clientId || undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Ticket created!");
|
||||||
|
setShowCreate(false);
|
||||||
|
setNewForm({ subject: "", description: "", type: "SUPPORT", priority: "NORMAL", clientSearch: "", clientId: "" });
|
||||||
|
qc.invalidateQueries({ queryKey: ["tickets"] });
|
||||||
|
},
|
||||||
|
onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create ticket"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const tickets = data?.data ?? [];
|
const tickets = data?.data ?? [];
|
||||||
const total = data?.total ?? 0;
|
const total = data?.meta?.total ?? 0;
|
||||||
|
const detail = ticketDetail ?? selected;
|
||||||
|
const comments = (ticketDetail as any)?.messages ?? [];
|
||||||
|
|
||||||
|
const nextStatus: Record<string, string> = { OPEN: "IN_PROGRESS", IN_PROGRESS: "RESOLVED", RESOLVED: "CLOSED" };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-800">Tickets</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Tickets</h1>
|
||||||
<p className="text-slate-500 text-sm mt-1">{total} tickets</p>
|
<p className="text-sm text-gray-500 mt-1">{total} total tickets</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
|
||||||
|
<Button onClick={() => setShowCreate(true)} size="sm"><Plus size={14} className="mr-1" />New Ticket</Button>
|
||||||
</div>
|
</div>
|
||||||
<button
|
|
||||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
|
|
||||||
style={{ backgroundColor: '#0891B2' }}
|
|
||||||
>
|
|
||||||
<Plus size={16} />
|
|
||||||
New Ticket
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-3 mb-4 flex-wrap">
|
<Card>
|
||||||
<div className="relative flex-1 min-w-[200px]">
|
<CardHeader>
|
||||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
<div className="flex flex-wrap gap-3">
|
||||||
<Input placeholder="Search tickets..." className="pl-9" value={search}
|
<input className="flex-1 min-w-[200px] border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
|
placeholder="Search tickets..." value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
|
||||||
</div>
|
<div className="flex gap-2 flex-wrap">
|
||||||
<select className="border rounded-md px-3 py-2 text-sm bg-white"
|
{statusFilters.map(s => (
|
||||||
value={typeFilter} onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }}>
|
<button key={s} onClick={() => { setStatusFilter(s); setPage(1); }}
|
||||||
<option value="">All Types</option>
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${statusFilter === s ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
|
||||||
{['INSTALLATION', 'SUPPORT', 'BILLING'].map(t => (
|
{s || "All Status"}
|
||||||
<option key={t} value={t}>{t}</option>
|
</button>
|
||||||
))}
|
))}
|
||||||
</select>
|
</div>
|
||||||
<select className="border rounded-md px-3 py-2 text-sm bg-white"
|
<div className="flex gap-2 flex-wrap">
|
||||||
value={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}>
|
{typeFilters.map(t => (
|
||||||
<option value="">All Statuses</option>
|
<button key={t} onClick={() => { setTypeFilter(t); setPage(1); }}
|
||||||
{['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'].map(s => (
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${typeFilter === t ? "bg-purple-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
|
||||||
<option key={s} value={s}>{s.replace('_', ' ')}</option>
|
{t || "All Types"}
|
||||||
))}
|
</button>
|
||||||
</select>
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<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">Subject</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Client</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Type</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500">Priority</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 lg:table-cell">Assigned</th>
|
|
||||||
<th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Created</th>
|
|
||||||
<th className="px-4 py-3"></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{isLoading
|
|
||||||
? Array.from({ length: 8 }).map((_, i) => (
|
|
||||||
<tr key={i} className="border-b">
|
|
||||||
{Array.from({ length: 8 }).map((_, j) => (
|
|
||||||
<td key={j} className="px-4 py-3"><Skeleton className="h-4 w-16" /></td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
: tickets.map((t) => (
|
|
||||||
<tr key={t.id} className="border-b hover:bg-slate-50 cursor-pointer transition-colors">
|
|
||||||
<td className="px-4 py-3 text-slate-800 font-medium max-w-[200px] truncate">
|
|
||||||
{t.subject}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600 hidden md:table-cell">
|
|
||||||
{t.client ? `${t.client.firstName} ${t.client.lastName}` : '—'}
|
|
||||||
<div className="text-xs text-slate-400">{t.client?.accountNumber}</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${typeColors[t.type] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{t.type}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${priorityColors[t.priority] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{t.priority}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[t.status] ?? 'bg-gray-100 text-gray-500'}`}>
|
|
||||||
{t.status?.replace('_', ' ')}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
|
|
||||||
{t.assignedTo ? `${t.assignedTo.firstName} ${t.assignedTo.lastName}` : 'Unassigned'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-500 hidden xl:table-cell">
|
|
||||||
{t.createdAt ? format(new Date(t.createdAt), 'MMM d') : '—'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-400"><ChevronRight size={16} /></td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
{!isLoading && tickets.length === 0 && (
|
</CardHeader>
|
||||||
<div className="text-center py-12 text-slate-400">No tickets found</div>
|
<CardContent className="p-0">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow><Th>Subject</Th><Th>Client</Th><Th>Type</Th><Th>Priority</Th><Th>Status</Th><Th>Created</Th><Th></Th></TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
Array.from({ length: 8 }).map((_, i) => (
|
||||||
|
<TableRow key={i}><Td colSpan={7}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
|
||||||
|
))
|
||||||
|
) : tickets.length === 0 ? (
|
||||||
|
<EmptyState colSpan={7} message="No tickets found" icon={<Ticket size={24} />} />
|
||||||
|
) : tickets.map(t => (
|
||||||
|
<TableRow key={t.id} onClick={() => setSelected(t)} className="cursor-pointer hover:bg-blue-50 transition-colors">
|
||||||
|
<Td className="font-medium max-w-[200px] truncate">{t.subject}</Td>
|
||||||
|
<Td className="text-sm text-gray-600">{t.client ? `${t.client.firstName} ${t.client.lastName}` : "—"}</Td>
|
||||||
|
<Td><Badge variant="muted">{t.type}</Badge></Td>
|
||||||
|
<Td><Badge variant={priorityVariant[t.priority] ?? "muted"}>{t.priority}</Badge></Td>
|
||||||
|
<Td><Badge variant={statusVariant[t.status] ?? "muted"}>{t.status}</Badge></Td>
|
||||||
|
<Td className="text-xs text-gray-400">{formatDate(t.createdAt)}</Td>
|
||||||
|
<Td className="text-gray-400 text-xs">View →</Td>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
{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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Ticket Detail Modal */}
|
||||||
|
<Modal isOpen={!!selected} onClose={() => setSelected(null)} title={`Ticket — ${detail?.subject ?? ""}`} className="max-w-2xl">
|
||||||
|
{detail && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-3 text-sm bg-gray-50 rounded-lg p-4">
|
||||||
|
<div><span className="text-gray-500">Client</span><p className="font-medium">{detail.client ? `${detail.client.firstName} ${detail.client.lastName}` : "—"}</p></div>
|
||||||
|
<div><span className="text-gray-500">Type</span><p><Badge variant="muted">{detail.type}</Badge></p></div>
|
||||||
|
<div><span className="text-gray-500">Priority</span><p><Badge variant={priorityVariant[detail.priority] ?? "muted"}>{detail.priority}</Badge></p></div>
|
||||||
|
<div><span className="text-gray-500">Status</span><p><Badge variant={statusVariant[detail.status] ?? "muted"}>{detail.status}</Badge></p></div>
|
||||||
|
<div className="col-span-2"><span className="text-gray-500">Created</span><p>{formatDate(detail.createdAt)}</p></div>
|
||||||
|
{detail.description && <div className="col-span-2"><span className="text-gray-500">Description</span><p className="mt-1 text-gray-800 whitespace-pre-wrap">{detail.description}</p></div>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Status actions */}
|
||||||
|
{nextStatus[detail.status] && (
|
||||||
|
<Button size="sm" onClick={() => updateStatus.mutate({ id: detail.id, status: nextStatus[detail.status] })} isLoading={updateStatus.isPending}>
|
||||||
|
Move to {nextStatus[detail.status].replace("_", " ")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Comments */}
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-700 mb-2">Comments ({comments.length})</p>
|
||||||
|
<div className="space-y-2 max-h-48 overflow-y-auto mb-3">
|
||||||
|
{comments.length === 0 ? <p className="text-sm text-gray-400">No comments yet.</p> :
|
||||||
|
comments.map((c: TicketComment) => (
|
||||||
|
<div key={c.id} className="bg-white border rounded-lg px-3 py-2 text-sm">
|
||||||
|
<p className="font-medium text-gray-700 text-xs">{(c.sender || c.author) ? `${(c.sender || c.author)!.firstName} ${(c.sender || c.author)!.lastName}` : "Staff"} · {formatDate(c.createdAt)}</p>
|
||||||
|
<p className="text-gray-800 mt-0.5">{c.body}</p>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input className="flex-1 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
placeholder="Add a comment..." value={comment} onChange={e => setComment(e.target.value)}
|
||||||
|
onKeyDown={e => e.key === "Enter" && !e.shiftKey && comment.trim() && addComment.mutate()} />
|
||||||
|
<Button size="sm" onClick={() => addComment.mutate()} isLoading={addComment.isPending} disabled={!comment.trim()}>
|
||||||
|
<Send size={14} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setSelected(null)}>Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Create Ticket Modal */}
|
||||||
|
<Modal isOpen={showCreate} onClose={() => setShowCreate(false)} title="New Ticket">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Input label="Subject *" value={newForm.subject} onChange={e => setNewForm(f => ({ ...f, subject: e.target.value }))} />
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Description</label>
|
||||||
|
<textarea className="border rounded-lg px-3 py-2 text-sm resize-none h-24 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={newForm.description} onChange={e => setNewForm(f => ({ ...f, description: e.target.value }))} />
|
||||||
|
</div>
|
||||||
|
<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">Type</label>
|
||||||
|
<select className="border rounded-lg px-3 py-2 text-sm" value={newForm.type} onChange={e => setNewForm(f => ({ ...f, type: e.target.value }))}>
|
||||||
|
<option value="SUPPORT">Support</option>
|
||||||
|
<option value="BILLING">Billing</option>
|
||||||
|
<option value="INSTALLATION">Installation</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Priority</label>
|
||||||
|
<select className="border rounded-lg px-3 py-2 text-sm" value={newForm.priority} onChange={e => setNewForm(f => ({ ...f, priority: e.target.value }))}>
|
||||||
|
<option value="NORMAL">Normal</option>
|
||||||
|
<option value="HIGH">High</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Link to Client (optional)</label>
|
||||||
|
<input className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
placeholder="Search client by name..." value={newForm.clientSearch}
|
||||||
|
onChange={e => setNewForm(f => ({ ...f, clientSearch: e.target.value, clientId: "" }))} />
|
||||||
|
{(clientSearch as any[]).length > 0 && !newForm.clientId && (
|
||||||
|
<div className="border rounded-lg divide-y max-h-40 overflow-y-auto shadow-sm">
|
||||||
|
{(clientSearch as any[]).map((c: any) => (
|
||||||
|
<button key={c.id} onClick={() => setNewForm(f => ({ ...f, clientId: c.id, clientSearch: `${c.firstName} ${c.lastName}` }))}
|
||||||
|
className="w-full text-left px-3 py-2 text-sm hover:bg-blue-50 transition-colors">
|
||||||
|
<span className="font-medium">{c.firstName} {c.lastName}</span>
|
||||||
|
<span className="text-gray-400 ml-2 text-xs">{c.accountNumber}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{newForm.clientId && <p className="text-xs text-green-600">✓ Client linked</p>}
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setShowCreate(false)}>Cancel</Button>
|
||||||
|
<Button onClick={() => createTicket.mutate()} isLoading={createTicket.isPending} disabled={!newForm.subject}>Create Ticket</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { useEffect } from "react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useRouter } from "next/navigation";
|
||||||
import { RefreshCw } from "lucide-react";
|
export default function UsersRedirect() {
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
const router = useRouter();
|
||||||
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
|
useEffect(() => { router.replace("/settings"); }, [router]);
|
||||||
import { Badge } from "@/components/ui/Badge";
|
return <div className="p-8 text-gray-400">Redirecting to settings…</div>;
|
||||||
import { Button } from "@/components/ui/Button";
|
|
||||||
import { formatDate } from "@/lib/utils";
|
|
||||||
import api from "@/lib/api";
|
|
||||||
import type { User, UsersResponse } from "@/types";
|
|
||||||
|
|
||||||
export default function UsersPage() {
|
|
||||||
const { data: users, isLoading, refetch } = useQuery<UsersResponse>({
|
|
||||||
queryKey: ["users"],
|
|
||||||
queryFn: async () => {
|
|
||||||
const res = await api.get<UsersResponse>("/api/v1/users?page=1&limit=20");
|
|
||||||
// Handle both array and paginated response
|
|
||||||
const d = res.data;
|
|
||||||
if (Array.isArray(d)) return d;
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const anyD = d as any;
|
|
||||||
if (anyD.data) return anyD.data as UsersResponse;
|
|
||||||
return [];
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const userList: User[] = users ?? [];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Users</h1>
|
|
||||||
<p className="text-sm text-gray-500">{userList.length} total users</p>
|
|
||||||
</div>
|
|
||||||
<Button size="sm" variant="outline" onClick={() => refetch()}>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
Refresh
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader><CardTitle>All Users</CardTitle></CardHeader>
|
|
||||||
<CardContent className="p-0">
|
|
||||||
<Table>
|
|
||||||
<TableHead>
|
|
||||||
<TableRow>
|
|
||||||
<Th>Name</Th>
|
|
||||||
<Th>Email</Th>
|
|
||||||
<Th>Role</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Last Login</Th>
|
|
||||||
<Th>Joined</Th>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
|
||||||
{isLoading ? (
|
|
||||||
Array.from({ length: 3 }).map((_, i) => (
|
|
||||||
<TableRow key={i}>
|
|
||||||
{Array.from({ length: 6 }).map((_, j) => (
|
|
||||||
<Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
|
|
||||||
))}
|
|
||||||
</TableRow>
|
|
||||||
))
|
|
||||||
) : userList.length === 0 ? (
|
|
||||||
<EmptyState message="No users found" />
|
|
||||||
) : (
|
|
||||||
userList.map((user) => {
|
|
||||||
const roles = user.roleAssignments?.map((r) => r.role) ?? [];
|
|
||||||
return (
|
|
||||||
<TableRow key={user.id} className="hover:bg-gray-50 transition-colors">
|
|
||||||
<Td className="font-medium">{user.firstName} {user.lastName}</Td>
|
|
||||||
<Td className="text-gray-500">{user.email}</Td>
|
|
||||||
<Td>
|
|
||||||
<div className="flex gap-1 flex-wrap">
|
|
||||||
{roles.length === 0 ? (
|
|
||||||
<Badge variant="muted">No role</Badge>
|
|
||||||
) : (
|
|
||||||
roles.map((role) => (
|
|
||||||
<Badge
|
|
||||||
key={role}
|
|
||||||
variant={role === "ADMIN" ? "default" : role === "TECHNICIAN" ? "success" : "muted"}
|
|
||||||
>
|
|
||||||
{role}
|
|
||||||
</Badge>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Td>
|
|
||||||
<Td>
|
|
||||||
<Badge variant={user.isActive ? "success" : "muted"}>
|
|
||||||
{user.isActive ? "Active" : "Inactive"}
|
|
||||||
</Badge>
|
|
||||||
</Td>
|
|
||||||
<Td className="text-xs text-gray-400">
|
|
||||||
{user.lastLoginAt ? formatDate(user.lastLoginAt) : "Never"}
|
|
||||||
</Td>
|
|
||||||
<Td className="text-xs text-gray-400">{formatDate(user.createdAt)}</Td>
|
|
||||||
</TableRow>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,136 +2,89 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { useForm } from 'react-hook-form';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { z } from 'zod';
|
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { api } from '@/lib/api';
|
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Loader2 } from 'lucide-react';
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import api from '@/lib/api';
|
||||||
const loginSchema = z.object({
|
import { useAuthStore } from '@/lib/auth-store';
|
||||||
tenantSlug: z.string().min(1, 'Tenant slug is required'),
|
|
||||||
email: z.string().email('Invalid email address'),
|
|
||||||
password: z.string().min(6, 'Password must be at least 6 characters'),
|
|
||||||
});
|
|
||||||
|
|
||||||
type LoginForm = z.infer<typeof loginSchema>;
|
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const setAuth = useAuthStore((s) => s.setAuth);
|
const setAuth = useAuthStore((s) => s.setAuth);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [form, setForm] = useState({ tenantSlug: '', email: '', password: '' });
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
const {
|
const validate = () => {
|
||||||
register,
|
const e: Record<string, string> = {};
|
||||||
handleSubmit,
|
if (!form.tenantSlug) e.tenantSlug = 'Required';
|
||||||
formState: { errors },
|
if (!form.email || !/\S+@\S+\.\S+/.test(form.email)) e.email = 'Valid email required';
|
||||||
} = useForm<LoginForm>({
|
if (!form.password || form.password.length < 6) e.password = 'Min 6 characters';
|
||||||
resolver: zodResolver(loginSchema),
|
setErrors(e);
|
||||||
});
|
return Object.keys(e).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
const onSubmit = async (data: LoginForm) => {
|
const onSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!validate()) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await api.post('/api/v1/auth/login', data);
|
const res = await api.post('/api/v1/auth/login', form);
|
||||||
const { accessToken, user } = res.data;
|
const { accessToken, user } = res.data;
|
||||||
setAuth({ accessToken, tenantSlug: data.tenantSlug, user });
|
setAuth({ accessToken, tenantSlug: form.tenantSlug, user });
|
||||||
toast.success('Welcome back, ' + user.firstName + '!');
|
toast.success(`Welcome back, ${user.firstName}!`);
|
||||||
router.push('/dashboard');
|
router.push('/dashboard');
|
||||||
} catch (err: unknown) {
|
} catch (err: any) {
|
||||||
const error = err as { response?: { data?: { message?: string } } };
|
toast.error(err.response?.data?.message || 'Login failed. Check your credentials.');
|
||||||
toast.error(error.response?.data?.message || 'Login failed. Check your credentials.');
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const field = (key: keyof typeof form) => ({
|
||||||
|
value: form[key],
|
||||||
|
onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
|
||||||
|
setForm(f => ({ ...f, [key]: e.target.value })),
|
||||||
|
});
|
||||||
|
|
||||||
|
const inputClass = (key: string) =>
|
||||||
|
`w-full border rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 ${errors[key] ? 'border-red-400' : 'border-gray-300'}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className="min-h-screen flex items-center justify-center p-4" style={{ backgroundColor: '#F8FAFC' }}>
|
||||||
className="min-h-screen flex items-center justify-center p-4"
|
<div className="w-full max-w-sm">
|
||||||
style={{ backgroundColor: '#F8FAFC' }}
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-md">
|
|
||||||
{/* Logo */}
|
{/* Logo */}
|
||||||
<div className="text-center mb-8">
|
<div className="text-center mb-8">
|
||||||
<div
|
<div className="w-14 h-14 rounded-2xl flex items-center justify-center text-white font-bold text-2xl mx-auto mb-3 shadow-md"
|
||||||
className="w-12 h-12 rounded-xl flex items-center justify-center text-white font-bold text-xl mx-auto mb-3"
|
style={{ backgroundColor: '#0891B2' }}>F</div>
|
||||||
style={{ backgroundColor: '#0891B2' }}
|
<h1 className="text-2xl font-bold text-gray-800">FiberOps</h1>
|
||||||
>
|
<p className="text-gray-500 text-sm mt-1">ISP Management Platform</p>
|
||||||
F
|
|
||||||
</div>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">FiberOps</h1>
|
|
||||||
<p className="text-slate-500 text-sm mt-1">ISP Management Platform</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="shadow-sm">
|
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
|
||||||
<CardHeader>
|
<h2 className="text-base font-semibold text-gray-800 mb-5">Sign in to your account</h2>
|
||||||
<CardTitle className="text-lg">Sign in to your account</CardTitle>
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<CardDescription>Enter your tenant and credentials to continue</CardDescription>
|
<div>
|
||||||
</CardHeader>
|
<label className="block text-sm font-medium text-gray-700 mb-1">Tenant Slug</label>
|
||||||
<CardContent>
|
<input {...field('tenantSlug')} className={inputClass('tenantSlug')} placeholder="e.g. demo-isp" autoComplete="off" />
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
{errors.tenantSlug && <p className="text-xs text-red-500 mt-1">{errors.tenantSlug}</p>}
|
||||||
<div className="space-y-1.5">
|
</div>
|
||||||
<Label htmlFor="tenantSlug">Tenant Slug</Label>
|
<div>
|
||||||
<Input
|
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||||
id="tenantSlug"
|
<input {...field('email')} type="email" className={inputClass('email')} placeholder="admin@yourisp.com" autoComplete="email" />
|
||||||
placeholder="e.g. demo-isp"
|
{errors.email && <p className="text-xs text-red-500 mt-1">{errors.email}</p>}
|
||||||
{...register('tenantSlug')}
|
</div>
|
||||||
/>
|
<div>
|
||||||
{errors.tenantSlug && (
|
<label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
|
||||||
<p className="text-xs text-red-500">{errors.tenantSlug.message}</p>
|
<input {...field('password')} type="password" className={inputClass('password')} placeholder="••••••••" autoComplete="current-password" />
|
||||||
)}
|
{errors.password && <p className="text-xs text-red-500 mt-1">{errors.password}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
<button type="submit" disabled={loading}
|
||||||
<div className="space-y-1.5">
|
className="w-full py-2.5 rounded-lg text-white font-medium text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-70"
|
||||||
<Label htmlFor="email">Email</Label>
|
style={{ backgroundColor: '#0891B2' }}>
|
||||||
<Input
|
{loading ? <><Loader2 size={16} className="animate-spin" />Signing in…</> : 'Sign In'}
|
||||||
id="email"
|
</button>
|
||||||
type="email"
|
</form>
|
||||||
placeholder="admin@yourisp.com"
|
</div>
|
||||||
{...register('email')}
|
|
||||||
/>
|
|
||||||
{errors.email && (
|
|
||||||
<p className="text-xs text-red-500">{errors.email.message}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label htmlFor="password">Password</Label>
|
|
||||||
<Input
|
|
||||||
id="password"
|
|
||||||
type="password"
|
|
||||||
placeholder="••••••••"
|
|
||||||
{...register('password')}
|
|
||||||
/>
|
|
||||||
{errors.password && (
|
|
||||||
<p className="text-xs text-red-500">{errors.password.message}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="w-full"
|
|
||||||
disabled={loading}
|
|
||||||
style={{ backgroundColor: '#0891B2' }}
|
|
||||||
>
|
|
||||||
{loading ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
||||||
Signing in…
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
'Sign In'
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
130
app/globals.css
130
app/globals.css
@@ -1,64 +1,104 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600;700&family=Fira+Sans:wght@300;400;500;600;700&display=swap');
|
||||||
|
|
||||||
@tailwind base;
|
@tailwind base;
|
||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* FiberOps Design System — Pixel/Conan approved */
|
||||||
|
/* Primary: #0891B2 | CTA: #059669 | BG: #F8FAFC | Text: #0F172A */
|
||||||
|
/* Fonts: Fira Sans (body) + Fira Code (data/numbers) */
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
:root {
|
:root {
|
||||||
--background: 0 0% 100%;
|
/* FiberOps tokens */
|
||||||
--foreground: 222.2 84% 4.9%;
|
--color-primary: #0891B2;
|
||||||
--card: 0 0% 100%;
|
--color-primary-dark: #0E7490;
|
||||||
--card-foreground: 222.2 84% 4.9%;
|
--color-secondary: #22D3EE;
|
||||||
--popover: 0 0% 100%;
|
--color-cta: #059669;
|
||||||
--popover-foreground: 222.2 84% 4.9%;
|
--color-cta-hover: #047857;
|
||||||
--primary: 222.2 47.4% 11.2%;
|
--color-bg: #F8FAFC;
|
||||||
--primary-foreground: 210 40% 98%;
|
--color-surface: #FFFFFF;
|
||||||
--secondary: 210 40% 96.1%;
|
--color-text: #0F172A;
|
||||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
--color-muted: #64748B;
|
||||||
--muted: 210 40% 96.1%;
|
--color-border: #E2E8F0;
|
||||||
--muted-foreground: 215.4 16.3% 46.9%;
|
--color-danger: #EF4444;
|
||||||
--accent: 210 40% 96.1%;
|
--color-warning: #F59E0B;
|
||||||
--accent-foreground: 222.2 47.4% 11.2%;
|
--color-success: #059669;
|
||||||
--destructive: 0 84.2% 60.2%;
|
|
||||||
--destructive-foreground: 210 40% 98%;
|
|
||||||
--border: 214.3 31.8% 91.4%;
|
|
||||||
--input: 214.3 31.8% 91.4%;
|
|
||||||
--ring: 222.2 84% 4.9%;
|
|
||||||
--radius: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dark {
|
/* Shadows */
|
||||||
--background: 222.2 84% 4.9%;
|
--shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
|
||||||
--foreground: 210 40% 98%;
|
--shadow-md: 0 4px 6px rgba(0,0,0,0.07);
|
||||||
--card: 222.2 84% 4.9%;
|
--shadow-lg: 0 10px 15px rgba(0,0,0,0.08);
|
||||||
--card-foreground: 210 40% 98%;
|
--shadow-xl: 0 20px 25px rgba(0,0,0,0.12);
|
||||||
--popover: 222.2 84% 4.9%;
|
|
||||||
--popover-foreground: 210 40% 98%;
|
/* Radius */
|
||||||
--primary: 210 40% 98%;
|
--radius-sm: 6px;
|
||||||
--primary-foreground: 222.2 47.4% 11.2%;
|
--radius-md: 10px;
|
||||||
--secondary: 217.2 32.6% 17.5%;
|
--radius-lg: 14px;
|
||||||
--secondary-foreground: 210 40% 98%;
|
--radius-xl: 20px;
|
||||||
--muted: 217.2 32.6% 17.5%;
|
|
||||||
--muted-foreground: 215 20.2% 65.1%;
|
|
||||||
--accent: 217.2 32.6% 17.5%;
|
|
||||||
--accent-foreground: 210 40% 98%;
|
|
||||||
--destructive: 0 62.8% 30.6%;
|
|
||||||
--destructive-foreground: 210 40% 98%;
|
|
||||||
--border: 217.2 32.6% 17.5%;
|
|
||||||
--input: 217.2 32.6% 17.5%;
|
|
||||||
--ring: 212.7 26.8% 83.9%;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
@apply border-border;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground;
|
background-color: var(--color-bg);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-family: 'Fira Sans', 'Inter', system-ui, sans-serif;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.6;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Data values, numbers, IDs */
|
||||||
|
code, .font-mono, .tabular-nums {
|
||||||
|
font-family: 'Fira Code', 'JetBrains Mono', monospace;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer utilities {
|
@layer utilities {
|
||||||
.text-balance {
|
/* Skeleton loading animation */
|
||||||
text-wrap: balance;
|
.skeleton {
|
||||||
|
@apply animate-pulse bg-slate-200 rounded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Row hover for tables */
|
||||||
|
.table-row-hover:hover {
|
||||||
|
background-color: #F0FDFF;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Transition helper */
|
||||||
|
.transition-fast {
|
||||||
|
transition: all 150ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.transition-smooth {
|
||||||
|
transition: all 200ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Card base */
|
||||||
|
.fiberops-card {
|
||||||
|
background: white;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Status badge helpers */
|
||||||
|
.badge-active { background: #DCFCE7; color: #166534; }
|
||||||
|
.badge-inactive { background: #F1F5F9; color: #475569; }
|
||||||
|
.badge-suspended { background: #FEF3C7; color: #92400E; }
|
||||||
|
.badge-pending { background: #DBEAFE; color: #1E40AF; }
|
||||||
|
.badge-overdue { background: #FEE2E2; color: #991B1B; }
|
||||||
|
.badge-paid { background: #DCFCE7; color: #166534; }
|
||||||
|
.badge-partial { background: #FEF3C7; color: #92400E; }
|
||||||
|
.badge-void { background: #F1F5F9; color: #94A3B8; }
|
||||||
|
.badge-open { background: #DBEAFE; color: #1E40AF; }
|
||||||
|
.badge-in-progress { background: #FEF3C7; color: #92400E; }
|
||||||
|
.badge-resolved { background: #DCFCE7; color: #166534; }
|
||||||
|
.badge-closed { background: #F1F5F9; color: #475569; }
|
||||||
|
|
||||||
|
.text-balance { text-wrap: balance; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
import { Inter } from 'next/font/google';
|
|
||||||
import './globals.css';
|
import './globals.css';
|
||||||
import Providers from '@/components/providers';
|
import Providers from '@/components/providers';
|
||||||
|
|
||||||
const inter = Inter({ subsets: ['latin'] });
|
// next/font/google downloads at build time — fails in Docker (no outbound internet).
|
||||||
|
// Fonts are loaded via CSS @import in globals.css (runtime CDN load).
|
||||||
|
// CSS vars are set directly in globals.css :root — no JS injection needed.
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'FiberOps Admin',
|
title: 'FiberOps Admin',
|
||||||
description: 'ISP Management Platform',
|
description: 'ISP Management Platform',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}) {
|
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body className={inter.className}>
|
<body>
|
||||||
<Providers>{children}</Providers>
|
<Providers>{children}</Providers>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -4,23 +4,22 @@ import Link from 'next/link';
|
|||||||
import { usePathname } from 'next/navigation';
|
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,
|
||||||
Ticket, BarChart3, Settings, Wifi, ClipboardList, ScrollText,
|
ArrowLeftRight, Ticket, BarChart3, ScrollText, Settings, BookOpen,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, roles: [] },
|
{ label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, roles: [] },
|
||||||
{ label: 'Clients', href: '/clients', icon: Users, roles: [] },
|
{ label: 'Clients', href: '/clients', icon: Users, roles: [] },
|
||||||
{ label: 'Leads', href: '/leads', icon: UserPlus, roles: ['admin','staff'] },
|
{ label: 'Leads', href: '/leads', icon: UserPlus, roles: ['admin', 'staff'] },
|
||||||
{ label: 'Subscriptions', href: '/subscriptions', icon: Wifi, roles: [] },
|
{ label: 'Invoices', href: '/invoices', icon: FileText, roles: [] },
|
||||||
{ label: 'Invoices', href: '/invoices', icon: FileText, roles: [] },
|
{ label: 'Payments', href: '/payments', icon: CreditCard, roles: [] },
|
||||||
{ label: 'Payments', href: '/payments', icon: CreditCard, roles: [] },
|
{ label: 'Remittances', href: '/remittances', icon: ArrowLeftRight, roles: ['admin', 'collector'] },
|
||||||
{ label: 'Remittances', href: '/remittances', icon: ArrowLeftRight, roles: [] },
|
{ label: 'Tickets', href: '/tickets', icon: Ticket, roles: [] },
|
||||||
{ label: 'Tickets', href: '/tickets', icon: Ticket, roles: [] },
|
{ label: 'Reports', href: '/reports', icon: BarChart3, roles: ['admin', 'staff'] },
|
||||||
{ label: 'Tasks', href: '/tasks', icon: ClipboardList, roles: ['admin','staff'] },
|
{ label: 'Accounting', href: '/accounting', icon: BookOpen, roles: ['admin'] },
|
||||||
{ 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', icon: Settings, roles: ['admin'] },
|
||||||
{ label: 'Settings', href: '/settings/tenant', icon: Settings, roles: ['admin'] },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
@@ -40,6 +39,7 @@ export default function Sidebar() {
|
|||||||
style={{ backgroundColor: '#0891B2' }}>F</div>
|
style={{ backgroundColor: '#0891B2' }}>F</div>
|
||||||
<span className="text-white font-semibold text-lg">FiberOps</span>
|
<span className="text-white font-semibold text-lg">FiberOps</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Nav */}
|
{/* Nav */}
|
||||||
<nav className="flex-1 px-3 py-4 space-y-0.5 overflow-y-auto">
|
<nav className="flex-1 px-3 py-4 space-y-0.5 overflow-y-auto">
|
||||||
{visibleItems.map((item) => {
|
{visibleItems.map((item) => {
|
||||||
@@ -47,16 +47,19 @@ export default function Sidebar() {
|
|||||||
const isActive = pathname === item.href || pathname.startsWith(item.href + '/');
|
const isActive = pathname === item.href || pathname.startsWith(item.href + '/');
|
||||||
return (
|
return (
|
||||||
<Link key={item.href} href={item.href}
|
<Link key={item.href} href={item.href}
|
||||||
className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors"
|
className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors cursor-pointer"
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: isActive ? '#0891B2' : 'transparent',
|
backgroundColor: isActive ? '#0891B2' : 'transparent',
|
||||||
color: isActive ? '#fff' : '#94A3B8',
|
color: isActive ? '#fff' : '#94A3B8',
|
||||||
}}>
|
}}
|
||||||
|
onMouseEnter={e => { if (!isActive) (e.currentTarget as HTMLElement).style.backgroundColor = '#1E293B'; }}
|
||||||
|
onMouseLeave={e => { if (!isActive) (e.currentTarget as HTMLElement).style.backgroundColor = 'transparent'; }}>
|
||||||
<Icon size={18} />{item.label}
|
<Icon size={18} />{item.label}
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="px-6 py-4 border-t border-slate-700">
|
<div className="px-6 py-4 border-t border-slate-700">
|
||||||
<p className="text-slate-500 text-xs">FiberOps v1.0</p>
|
<p className="text-slate-500 text-xs">FiberOps v1.0</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
import { useAuthStore } from '@/lib/auth-store';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { LogOut, User } from 'lucide-react';
|
import { LogOut, User } from 'lucide-react';
|
||||||
|
|
||||||
export default function Topbar() {
|
export default function Topbar() {
|
||||||
@@ -14,33 +13,27 @@ export default function Topbar() {
|
|||||||
router.push('/login');
|
router.push('/login');
|
||||||
};
|
};
|
||||||
|
|
||||||
const fullName = user ? `${user.firstName} ${user.lastName}` : 'Admin';
|
const fullName = user ? `${user.firstName ?? ''} ${user.lastName ?? ''}`.trim() : 'Admin';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header
|
<header className="h-14 border-b flex items-center justify-between px-6"
|
||||||
className="h-14 border-b flex items-center justify-between px-6"
|
style={{ backgroundColor: '#fff', borderColor: '#E2E8F0' }}>
|
||||||
style={{ backgroundColor: '#fff', borderColor: '#E2E8F0' }}
|
|
||||||
>
|
|
||||||
<div />
|
<div />
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="flex items-center gap-2 text-sm text-slate-600">
|
<div className="flex items-center gap-2 text-sm text-slate-600">
|
||||||
<User size={16} />
|
<User size={16} />
|
||||||
<span>{fullName}</span>
|
<span>{fullName}</span>
|
||||||
{user?.roles?.[0] && (
|
{user?.roles?.[0] && (
|
||||||
<span className="text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full capitalize">
|
<span className="text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full">
|
||||||
{user.roles[0]}
|
{user.roles[0]}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<button onClick={handleLogout}
|
||||||
variant="ghost"
|
className="flex items-center gap-1.5 text-sm text-slate-500 hover:text-red-500 px-2 py-1.5 rounded-lg hover:bg-red-50 transition-colors">
|
||||||
size="sm"
|
|
||||||
onClick={handleLogout}
|
|
||||||
className="text-slate-500 hover:text-red-500 gap-1.5"
|
|
||||||
>
|
|
||||||
<LogOut size={15} />
|
<LogOut size={15} />
|
||||||
Logout
|
Logout
|
||||||
</Button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import { Toaster } from '@/components/ui/sonner';
|
import { Toaster } from 'sonner';
|
||||||
|
|
||||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||||
// Must be created inside component — NOT at module level
|
// Must be created inside component — NOT at module level
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const badgeVariants = cva(
|
|
||||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
|
||||||
{
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
|
||||||
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
|
||||||
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
|
||||||
outline: "text-foreground",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
export interface BadgeProps
|
|
||||||
extends React.HTMLAttributes<HTMLDivElement>,
|
|
||||||
VariantProps<typeof badgeVariants> {}
|
|
||||||
|
|
||||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
|
||||||
return (
|
|
||||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Badge, badgeVariants }
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { Slot } from "@radix-ui/react-slot"
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const buttonVariants = cva(
|
|
||||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
|
||||||
{
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
|
||||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
|
||||||
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
|
||||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
|
||||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
|
||||||
},
|
|
||||||
size: {
|
|
||||||
default: "h-10 px-4 py-2",
|
|
||||||
sm: "h-9 rounded-md px-3",
|
|
||||||
lg: "h-11 rounded-md px-8",
|
|
||||||
icon: "h-10 w-10",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
size: "default",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
export interface ButtonProps
|
|
||||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
|
||||||
VariantProps<typeof buttonVariants> {
|
|
||||||
asChild?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
||||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
|
||||||
const Comp = asChild ? Slot : "button"
|
|
||||||
return (
|
|
||||||
<Comp
|
|
||||||
className={cn(buttonVariants({ variant, size, className }))}
|
|
||||||
ref={ref}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
Button.displayName = "Button"
|
|
||||||
|
|
||||||
export { Button, buttonVariants }
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<div
|
|
||||||
ref={ref}
|
|
||||||
className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)
|
|
||||||
Card.displayName = "Card"
|
|
||||||
|
|
||||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
CardHeader.displayName = "CardHeader"
|
|
||||||
|
|
||||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<h3
|
|
||||||
ref={ref}
|
|
||||||
className={cn("text-2xl font-semibold leading-none tracking-tight", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)
|
|
||||||
CardTitle.displayName = "CardTitle"
|
|
||||||
|
|
||||||
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
CardDescription.displayName = "CardDescription"
|
|
||||||
|
|
||||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
CardContent.displayName = "CardContent"
|
|
||||||
|
|
||||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
CardFooter.displayName = "CardFooter"
|
|
||||||
|
|
||||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
|
||||||
import { X } from "lucide-react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Dialog = DialogPrimitive.Root
|
|
||||||
const DialogTrigger = DialogPrimitive.Trigger
|
|
||||||
const DialogPortal = DialogPrimitive.Portal
|
|
||||||
const DialogClose = DialogPrimitive.Close
|
|
||||||
|
|
||||||
const DialogOverlay = React.forwardRef<
|
|
||||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<DialogPrimitive.Overlay
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
|
||||||
|
|
||||||
const DialogContent = React.forwardRef<
|
|
||||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
|
||||||
>(({ className, children, ...props }, ref) => (
|
|
||||||
<DialogPortal>
|
|
||||||
<DialogOverlay />
|
|
||||||
<DialogPrimitive.Content
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
<span className="sr-only">Close</span>
|
|
||||||
</DialogPrimitive.Close>
|
|
||||||
</DialogPrimitive.Content>
|
|
||||||
</DialogPortal>
|
|
||||||
))
|
|
||||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
|
||||||
|
|
||||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
|
||||||
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
|
|
||||||
)
|
|
||||||
DialogHeader.displayName = "DialogHeader"
|
|
||||||
|
|
||||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
|
||||||
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
|
|
||||||
)
|
|
||||||
DialogFooter.displayName = "DialogFooter"
|
|
||||||
|
|
||||||
const DialogTitle = React.forwardRef<
|
|
||||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<DialogPrimitive.Title
|
|
||||||
ref={ref}
|
|
||||||
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
|
||||||
|
|
||||||
const DialogDescription = React.forwardRef<
|
|
||||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<DialogPrimitive.Description
|
|
||||||
ref={ref}
|
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
|
||||||
|
|
||||||
export {
|
|
||||||
Dialog, DialogPortal, DialogOverlay, DialogClose, DialogTrigger,
|
|
||||||
DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription,
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>
|
|
||||||
|
|
||||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|
||||||
({ className, type, ...props }, ref) => {
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
type={type}
|
|
||||||
className={cn(
|
|
||||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
ref={ref}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
Input.displayName = "Input"
|
|
||||||
|
|
||||||
export { Input }
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const labelVariants = cva(
|
|
||||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
|
||||||
)
|
|
||||||
|
|
||||||
const Label = React.forwardRef<
|
|
||||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
|
||||||
VariantProps<typeof labelVariants>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<LabelPrimitive.Root
|
|
||||||
ref={ref}
|
|
||||||
className={cn(labelVariants(), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
Label.displayName = LabelPrimitive.Root.displayName
|
|
||||||
|
|
||||||
export { Label }
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
|
||||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Select = SelectPrimitive.Root
|
|
||||||
const SelectGroup = SelectPrimitive.Group
|
|
||||||
const SelectValue = SelectPrimitive.Value
|
|
||||||
|
|
||||||
const SelectTrigger = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
|
||||||
>(({ className, children, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.Trigger
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<SelectPrimitive.Icon asChild>
|
|
||||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
|
||||||
</SelectPrimitive.Icon>
|
|
||||||
</SelectPrimitive.Trigger>
|
|
||||||
))
|
|
||||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
|
||||||
|
|
||||||
const SelectScrollUpButton = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.ScrollUpButton
|
|
||||||
ref={ref}
|
|
||||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronUp className="h-4 w-4" />
|
|
||||||
</SelectPrimitive.ScrollUpButton>
|
|
||||||
))
|
|
||||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
|
||||||
|
|
||||||
const SelectScrollDownButton = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.ScrollDownButton
|
|
||||||
ref={ref}
|
|
||||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronDown className="h-4 w-4" />
|
|
||||||
</SelectPrimitive.ScrollDownButton>
|
|
||||||
))
|
|
||||||
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName
|
|
||||||
|
|
||||||
const SelectContent = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
|
||||||
>(({ className, children, position = "popper", ...props }, ref) => (
|
|
||||||
<SelectPrimitive.Portal>
|
|
||||||
<SelectPrimitive.Content
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
|
||||||
position === "popper" &&
|
|
||||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
position={position}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SelectScrollUpButton />
|
|
||||||
<SelectPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"p-1",
|
|
||||||
position === "popper" &&
|
|
||||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</SelectPrimitive.Viewport>
|
|
||||||
<SelectScrollDownButton />
|
|
||||||
</SelectPrimitive.Content>
|
|
||||||
</SelectPrimitive.Portal>
|
|
||||||
))
|
|
||||||
SelectContent.displayName = SelectPrimitive.Content.displayName
|
|
||||||
|
|
||||||
const SelectLabel = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.Label
|
|
||||||
ref={ref}
|
|
||||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
|
||||||
|
|
||||||
const SelectItem = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
|
||||||
>(({ className, children, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.Item
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
|
||||||
<SelectPrimitive.ItemIndicator>
|
|
||||||
<Check className="h-4 w-4" />
|
|
||||||
</SelectPrimitive.ItemIndicator>
|
|
||||||
</span>
|
|
||||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
|
||||||
</SelectPrimitive.Item>
|
|
||||||
))
|
|
||||||
SelectItem.displayName = SelectPrimitive.Item.displayName
|
|
||||||
|
|
||||||
const SelectSeparator = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SelectPrimitive.Separator
|
|
||||||
ref={ref}
|
|
||||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
|
||||||
|
|
||||||
export {
|
|
||||||
Select,
|
|
||||||
SelectGroup,
|
|
||||||
SelectValue,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectScrollUpButton,
|
|
||||||
SelectScrollDownButton,
|
|
||||||
SelectContent,
|
|
||||||
SelectLabel,
|
|
||||||
SelectItem,
|
|
||||||
SelectSeparator,
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
|
||||||
import { X } from "lucide-react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Sheet = SheetPrimitive.Root
|
|
||||||
const SheetTrigger = SheetPrimitive.Trigger
|
|
||||||
const SheetClose = SheetPrimitive.Close
|
|
||||||
const SheetPortal = SheetPrimitive.Portal
|
|
||||||
|
|
||||||
const SheetOverlay = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SheetPrimitive.Overlay>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SheetPrimitive.Overlay
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
ref={ref}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
|
||||||
|
|
||||||
const sheetVariants = cva(
|
|
||||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
|
||||||
{
|
|
||||||
variants: {
|
|
||||||
side: {
|
|
||||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
|
||||||
bottom: "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
|
||||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
|
||||||
right: "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
defaultVariants: {
|
|
||||||
side: "right",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
interface SheetContentProps
|
|
||||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
|
||||||
VariantProps<typeof sheetVariants> {}
|
|
||||||
|
|
||||||
const SheetContent = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
|
||||||
SheetContentProps
|
|
||||||
>(({ side = "right", className, children, ...props }, ref) => (
|
|
||||||
<SheetPortal>
|
|
||||||
<SheetOverlay />
|
|
||||||
<SheetPrimitive.Content
|
|
||||||
ref={ref}
|
|
||||||
className={cn(sheetVariants({ side }), className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
<span className="sr-only">Close</span>
|
|
||||||
</SheetPrimitive.Close>
|
|
||||||
</SheetPrimitive.Content>
|
|
||||||
</SheetPortal>
|
|
||||||
))
|
|
||||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
|
||||||
|
|
||||||
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
|
||||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
|
||||||
)
|
|
||||||
SheetHeader.displayName = "SheetHeader"
|
|
||||||
|
|
||||||
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
|
||||||
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
|
|
||||||
)
|
|
||||||
SheetFooter.displayName = "SheetFooter"
|
|
||||||
|
|
||||||
const SheetTitle = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} />
|
|
||||||
))
|
|
||||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
|
||||||
|
|
||||||
const SheetDescription = React.forwardRef<
|
|
||||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
|
||||||
))
|
|
||||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
|
||||||
|
|
||||||
export {
|
|
||||||
Sheet, SheetPortal, SheetOverlay, SheetTrigger, SheetClose,
|
|
||||||
SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription,
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
function Skeleton({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Skeleton }
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { Toaster as Sonner } from "sonner"
|
|
||||||
|
|
||||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
|
||||||
|
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
|
||||||
return (
|
|
||||||
<Sonner
|
|
||||||
theme="light"
|
|
||||||
className="toaster group"
|
|
||||||
toastOptions={{
|
|
||||||
classNames: {
|
|
||||||
toast:
|
|
||||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
|
||||||
description: "group-[.toast]:text-muted-foreground",
|
|
||||||
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
|
||||||
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Toaster }
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<div className="relative w-full overflow-auto">
|
|
||||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
)
|
|
||||||
Table.displayName = "Table"
|
|
||||||
|
|
||||||
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableHeader.displayName = "TableHeader"
|
|
||||||
|
|
||||||
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableBody.displayName = "TableBody"
|
|
||||||
|
|
||||||
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableFooter.displayName = "TableFooter"
|
|
||||||
|
|
||||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<tr
|
|
||||||
ref={ref}
|
|
||||||
className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableRow.displayName = "TableRow"
|
|
||||||
|
|
||||||
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<th
|
|
||||||
ref={ref}
|
|
||||||
className={cn("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableHead.displayName = "TableHead"
|
|
||||||
|
|
||||||
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableCell.displayName = "TableCell"
|
|
||||||
|
|
||||||
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
|
|
||||||
({ className, ...props }, ref) => (
|
|
||||||
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
|
|
||||||
)
|
|
||||||
)
|
|
||||||
TableCaption.displayName = "TableCaption"
|
|
||||||
|
|
||||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption }
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Tabs = TabsPrimitive.Root
|
|
||||||
|
|
||||||
const TabsList = React.forwardRef<
|
|
||||||
React.ElementRef<typeof TabsPrimitive.List>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<TabsPrimitive.List
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TabsList.displayName = TabsPrimitive.List.displayName
|
|
||||||
|
|
||||||
const TabsTrigger = React.forwardRef<
|
|
||||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<TabsPrimitive.Trigger
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
|
|
||||||
|
|
||||||
const TabsContent = React.forwardRef<
|
|
||||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<TabsPrimitive.Content
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TabsContent.displayName = TabsPrimitive.Content.displayName
|
|
||||||
|
|
||||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
|
||||||
50
e2e/accounting.spec.ts
Normal file
50
e2e/accounting.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Accounting', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('chart of accounts page loads', async ({ page }) => {
|
||||||
|
await page.goto('/accounting');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('h1').filter({ hasText: 'Accounting' }).first()).toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accounting sub-nav visible', async ({ page }) => {
|
||||||
|
await page.goto('/accounting');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('a').filter({ hasText: /Expenses/ }).first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('journal entries page loads', async ({ page }) => {
|
||||||
|
await page.goto('/accounting/journal-entries');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('h1').filter({ hasText: 'Accounting' }).first()).toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('expenses page loads', async ({ page }) => {
|
||||||
|
await page.goto('/accounting/expenses');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('h1').filter({ hasText: 'Accounting' }).first()).toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('company accounts page loads', async ({ page }) => {
|
||||||
|
await page.goto('/accounting/company-accounts');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('h1').filter({ hasText: 'Accounting' }).first()).toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('financial reports page loads', async ({ page }) => {
|
||||||
|
await page.goto('/accounting/reports');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('text=Trial Balance').first()).toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accounting link in sidebar', async ({ page }) => {
|
||||||
|
await page.goto('/dashboard');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('a[href="/accounting"]')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
30
e2e/audit-log.spec.ts
Normal file
30
e2e/audit-log.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Audit Log', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/audit-log');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('audit log page renders', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Audit Log")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('audit log entries load', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
const hasRows = await page.locator('tbody tr').count();
|
||||||
|
const hasEmpty = await page.locator('text=No audit').isVisible().catch(() => false);
|
||||||
|
expect(hasRows > 0 || hasEmpty).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pagination controls exist when multiple pages', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
// If there are enough logs, pagination should show
|
||||||
|
const prevBtn = page.locator('button:has-text("Prev"), button[disabled]:has-text("Prev")');
|
||||||
|
if (await prevBtn.isVisible()) {
|
||||||
|
expect(await prevBtn.isVisible()).toBeTruthy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
44
e2e/auth.spec.ts
Normal file
44
e2e/auth.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { test, expect, request } from '@playwright/test';
|
||||||
|
import { login, loginViaAPI, DEMO } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Authentication', () => {
|
||||||
|
test('login page renders correctly', async ({ page }) => {
|
||||||
|
await page.goto('/login');
|
||||||
|
await page.waitForLoadState('domcontentloaded');
|
||||||
|
await expect(page.locator('h1:has-text("FiberOps")')).toBeVisible();
|
||||||
|
await expect(page.locator('h2:has-text("Sign in")')).toBeVisible();
|
||||||
|
await expect(page.locator('input[type="email"]')).toBeVisible();
|
||||||
|
await expect(page.locator('input[type="password"]')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('login with valid credentials redirects to dashboard', async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
expect(page.url()).toContain('/dashboard');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('login with wrong credentials returns 401', async () => {
|
||||||
|
const ctx = await request.newContext({ baseURL: 'https://fiberops-api.juankibin.space' });
|
||||||
|
const resp = await ctx.post('/api/v1/auth/login', {
|
||||||
|
data: { tenantSlug: DEMO.tenant, email: DEMO.email, password: 'wrongpassword' },
|
||||||
|
headers: { 'Content-Type': 'application/json', 'x-tenant-slug': DEMO.tenant },
|
||||||
|
});
|
||||||
|
await ctx.dispose();
|
||||||
|
expect(resp.status()).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unauthenticated access redirects to login', async ({ page }) => {
|
||||||
|
await page.goto('/login');
|
||||||
|
await page.evaluate(() => localStorage.clear());
|
||||||
|
await page.goto('/dashboard');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
expect(page.url()).toContain('/login');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('logout returns to login', async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
const logoutBtn = page.locator('button:has-text("Logout"), a:has-text("Logout")').first();
|
||||||
|
await logoutBtn.click();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
expect(page.url()).toContain('/login');
|
||||||
|
});
|
||||||
|
});
|
||||||
282
e2e/business-flow.spec.ts
Normal file
282
e2e/business-flow.spec.ts
Normal file
@@ -0,0 +1,282 @@
|
|||||||
|
import { test, expect, Page } from '@playwright/test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FIBEROPS-248: Full business flow E2E
|
||||||
|
* Simulates complete ISP business day — admin ops (tests 1–16)
|
||||||
|
*
|
||||||
|
* Seed data (pre-created via API):
|
||||||
|
* Plan: Basic 25Mbps (₱999, POSTPAID)
|
||||||
|
* Client: Juan Santos, accountNumber: ACC-000029, portalAccessEnabled: true
|
||||||
|
* Sub: Active subscription to Basic 25Mbps
|
||||||
|
* Invoice: INV-2026-000015
|
||||||
|
* Ticket: "No internet connection"
|
||||||
|
* Lead: Maria Reyes
|
||||||
|
*
|
||||||
|
* Note: Subscriber portal tests (17–22) live in the fiberops-portal repo.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BASE = 'http://192.168.1.167:3002';
|
||||||
|
const TENANT_SLUG = 'demo-isp';
|
||||||
|
const ADMIN_EMAIL = 'admin@demo-isp.com';
|
||||||
|
const ADMIN_PASSWORD = 'Admin123!';
|
||||||
|
|
||||||
|
async function adminLogin(page: Page) {
|
||||||
|
await page.goto(`${BASE}/login`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
// Login form: tenantSlug, email, password (3 inputs)
|
||||||
|
await page.locator('input[placeholder*="demo-isp"]').fill(TENANT_SLUG);
|
||||||
|
await page.locator('input[type="email"]').fill(ADMIN_EMAIL);
|
||||||
|
await page.locator('input[type="password"]').fill(ADMIN_PASSWORD);
|
||||||
|
await page.locator('button[type="submit"]').click();
|
||||||
|
await page.waitForURL(/dashboard/, { timeout: 20000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Phase 1: Admin Login ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('1. Admin login → dashboard loads', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await expect(page).toHaveURL(/dashboard/);
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 2: Plans ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('2. Plans — Basic 25Mbps exists in list', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/plans`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Basic 25Mbps').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('3. Plans — create Pro 50Mbps via UI', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/plans`);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// Click "Add Plan" button (data-testid="btn-add-plan")
|
||||||
|
await page.locator('[data-testid="btn-add-plan"]').click();
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
|
// Fill modal fields using data-testid
|
||||||
|
await page.locator('[data-testid="input-plan-name"]').fill('Pro 50Mbps');
|
||||||
|
await page.locator('[data-testid="select-plan-type"]').selectOption('POSTPAID');
|
||||||
|
await page.locator('[data-testid="input-plan-speed-down"]').fill('50');
|
||||||
|
await page.locator('[data-testid="input-plan-speed-up"]').fill('20');
|
||||||
|
await page.locator('[data-testid="input-plan-price"]').fill('1499');
|
||||||
|
|
||||||
|
await page.locator('[data-testid="btn-submit-create"]').click();
|
||||||
|
await page.waitForTimeout(2500);
|
||||||
|
|
||||||
|
// Confirm plan appears
|
||||||
|
await page.goto(`${BASE}/plans`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Pro 50Mbps').first()).toBeVisible({ timeout: 8000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 3: Clients ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('4. Clients — Juan Santos appears in list', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/clients`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Juan').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('5. Clients — create new client Pedro Cruz via UI', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/clients`);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// Click "Add Client" button
|
||||||
|
await page.locator('[data-testid="add-client-btn"]').click();
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
|
// Fill via getByLabel (Input component renders label-linked inputs)
|
||||||
|
await page.getByLabel('First Name').fill('Pedro');
|
||||||
|
await page.getByLabel('Last Name').fill('Cruz');
|
||||||
|
await page.getByLabel('Email').fill('pedro.cruz@example.com');
|
||||||
|
await page.getByLabel('Phone').fill('09201234567');
|
||||||
|
await page.getByLabel('Address').fill('789 Bonifacio Ave, Mallig');
|
||||||
|
|
||||||
|
// Select all required dropdowns (Area, Billing Type, Plan)
|
||||||
|
const selects = page.locator('select');
|
||||||
|
const selectCount = await selects.count();
|
||||||
|
for (let i = 0; i < selectCount; i++) {
|
||||||
|
const sel = selects.nth(i);
|
||||||
|
const opts = await sel.locator('option').all();
|
||||||
|
if (opts.length > 1) await sel.selectOption({ index: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Submit — wait for button to be enabled (Plan required), then click
|
||||||
|
const createClientBtn = page.locator('button:has-text("Create Client")');
|
||||||
|
await expect(createClientBtn).toBeEnabled({ timeout: 8000 });
|
||||||
|
await createClientBtn.click();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
await page.goto(`${BASE}/clients`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Pedro').first()).toBeVisible({ timeout: 8000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('6. Clients — Juan Santos profile shows subscription', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/clients`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Click on Juan Santos row
|
||||||
|
await page.locator('text=Juan Santos').first().click();
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
await expect(page.locator('text=Juan').first()).toBeVisible();
|
||||||
|
// ACC-000029 should be visible
|
||||||
|
await expect(page.locator('text=ACC-000029').first()).toBeVisible({ timeout: 8000 }).catch(() => {
|
||||||
|
// Account number may be abbreviated — just check page loaded
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 4: Invoices & Payments ────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('7. Invoices — INV-2026 exists', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/invoices`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=INV-2026').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('8. Invoices — record payment for INV-2026-000015', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/invoices`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Click on the first invoice row
|
||||||
|
await page.locator('text=INV-2026').first().click();
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// "Record Payment" section uses getByLabel('Amount')
|
||||||
|
const amtField = page.getByLabel('Amount').first();
|
||||||
|
if (await amtField.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||||
|
await amtField.fill('999');
|
||||||
|
|
||||||
|
// Payment Method select
|
||||||
|
const methodSelect = page.locator('select').first();
|
||||||
|
if (await methodSelect.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||||
|
await methodSelect.selectOption('CASH');
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.locator('button:has-text("Record Payment")').click();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
// Invoice should now show PAID
|
||||||
|
await expect(page.locator('text=PAID, text=Paid').first()).toBeVisible({ timeout: 8000 }).catch(() => {
|
||||||
|
// May need to reload
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// At minimum — page didn't crash
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('9. Payments — list renders with at least one payment', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/payments`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
// At least one data row
|
||||||
|
const rows = await page.locator('tbody tr, [role="row"]').count();
|
||||||
|
expect(rows).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 5: Remittances ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('10. Remittances — page loads', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/remittances`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 6: Tickets ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('11. Tickets — "No internet connection" exists', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/tickets`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=No internet').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('12. Tickets — New Ticket button opens modal', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/tickets`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Verify "New Ticket" button is visible and clickable
|
||||||
|
const newTicketBtn = page.locator('button:has-text("New Ticket")');
|
||||||
|
await expect(newTicketBtn).toBeVisible({ timeout: 8000 });
|
||||||
|
|
||||||
|
// Click and verify modal opens (bg overlay appears)
|
||||||
|
await newTicketBtn.click();
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// Modal should be visible — check for "Create Ticket" button inside it
|
||||||
|
await expect(page.locator('button:has-text("Create Ticket")')).toBeVisible({ timeout: 8000 });
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('button:has-text("New Ticket")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// ─── Phase 7: Leads ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('13. Leads — Maria Reyes exists', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/leads`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Maria').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('14. Leads — create new lead Rosa Gomez via UI', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/leads`);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
await page.locator('button:has-text("Add Lead")').click();
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
|
await page.getByLabel('First Name').fill('Rosa');
|
||||||
|
await page.getByLabel('Last Name').fill('Gomez');
|
||||||
|
await page.getByLabel('Phone').fill('09209998888');
|
||||||
|
await page.getByLabel('Address').fill('321 Luna St, Mallig').catch(() => {});
|
||||||
|
|
||||||
|
const areaSelect = page.locator('select').first();
|
||||||
|
if (await areaSelect.isVisible({ timeout: 1500 }).catch(() => false)) {
|
||||||
|
const opts = await areaSelect.locator('option').all();
|
||||||
|
if (opts.length > 1) await areaSelect.selectOption({ index: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.locator('button:has-text("Add Lead")').last().click();
|
||||||
|
await page.waitForTimeout(2500);
|
||||||
|
|
||||||
|
await page.goto(`${BASE}/leads`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Rosa').first()).toBeVisible({ timeout: 8000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Phase 8: Reports & Audit Log ────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('15. Reports — page renders', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/reports`);
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('16. Audit Log — page renders', async ({ page }) => {
|
||||||
|
await adminLogin(page);
|
||||||
|
await page.goto(`${BASE}/audit-log`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
94
e2e/clients.spec.ts
Normal file
94
e2e/clients.spec.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Clients', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/clients');
|
||||||
|
await page.waitForURL(/\/clients/, { timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clients list page loads with table', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Clients")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
await expect(page.locator('th:has-text("Name")')).toBeVisible();
|
||||||
|
await expect(page.locator('th:has-text("Account #")')).toBeVisible();
|
||||||
|
await expect(page.locator('th:has-text("Status")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('search/filter works without crash', async ({ page }) => {
|
||||||
|
const searchInput = page.locator('input[placeholder*="Search"]');
|
||||||
|
await expect(searchInput).toBeVisible();
|
||||||
|
await searchInput.fill('test');
|
||||||
|
// Wait for debounce/query
|
||||||
|
await page.waitForTimeout(600);
|
||||||
|
// Page should not crash
|
||||||
|
await expect(page.locator('h1:has-text("Clients")')).toBeVisible();
|
||||||
|
// Clear search
|
||||||
|
await searchInput.fill('');
|
||||||
|
await page.waitForTimeout(400);
|
||||||
|
await expect(page.locator('h1:has-text("Clients")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Add client button is clickable and opens modal', async ({ page }) => {
|
||||||
|
// Use testid if available, fall back to text
|
||||||
|
const btn = page.locator('[data-testid="add-client-btn"], button:has-text("Add Client")').first();
|
||||||
|
await expect(btn).toBeVisible();
|
||||||
|
await btn.click();
|
||||||
|
// Modal should open
|
||||||
|
await expect(page.locator('text=Add New Client')).toBeVisible({ timeout: 5000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking a client row navigates to detail page', async ({ page }) => {
|
||||||
|
// Wait for data to load (skeleton rows disappear)
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
const rows = page.locator('tr.cursor-pointer');
|
||||||
|
const count = await rows.count();
|
||||||
|
if (count === 0) {
|
||||||
|
// No clients — verify empty state renders gracefully
|
||||||
|
await expect(page.locator('text=No clients found')).toBeVisible();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await rows.first().click();
|
||||||
|
await expect(page).toHaveURL(/\/clients\/[a-zA-Z0-9-]+/, { timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('client detail page tabs render', async ({ page }) => {
|
||||||
|
// Wait for data
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
const rows = page.locator('tr.cursor-pointer');
|
||||||
|
const count = await rows.count();
|
||||||
|
if (count === 0) {
|
||||||
|
test.skip(true, 'No clients to test detail page');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await rows.first().click();
|
||||||
|
await expect(page).toHaveURL(/\/clients\/[a-zA-Z0-9-]+/, { timeout: 10000 });
|
||||||
|
|
||||||
|
// All 5 tabs must be visible
|
||||||
|
for (const tabLabel of ['Profile', 'Subscriptions', 'Invoices', 'Payments', 'Tickets']) {
|
||||||
|
await expect(page.locator(`button:has-text("${tabLabel}")`)).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click each tab and verify no crash (no "map is not a function" errors)
|
||||||
|
await page.click('button:has-text("Subscriptions")');
|
||||||
|
await page.waitForTimeout(800);
|
||||||
|
await expect(page.locator('button:has-text("Subscriptions")')).toBeVisible();
|
||||||
|
|
||||||
|
await page.click('button:has-text("Invoices")');
|
||||||
|
await page.waitForTimeout(800);
|
||||||
|
await expect(page.locator('button:has-text("Invoices")')).toBeVisible();
|
||||||
|
|
||||||
|
await page.click('button:has-text("Payments")');
|
||||||
|
await page.waitForTimeout(800);
|
||||||
|
await expect(page.locator('button:has-text("Payments")')).toBeVisible();
|
||||||
|
|
||||||
|
await page.click('button:has-text("Tickets")');
|
||||||
|
await page.waitForTimeout(800);
|
||||||
|
await expect(page.locator('button:has-text("Tickets")')).toBeVisible();
|
||||||
|
|
||||||
|
// Back to Profile
|
||||||
|
await page.click('button:has-text("Profile")');
|
||||||
|
await expect(page.locator('text=Client Profile')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
57
e2e/dashboard.spec.ts
Normal file
57
e2e/dashboard.spec.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Dashboard', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dashboard page loads with correct title', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Dashboard")')).toBeVisible();
|
||||||
|
await expect(page.locator('text=Overview of your ISP operations')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('KPI cards render after loading', async ({ page }) => {
|
||||||
|
// Wait for skeletons to disappear
|
||||||
|
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||||
|
await expect(page.locator('text=Total Clients')).toBeVisible();
|
||||||
|
await expect(page.locator('text=Active Subscriptions')).toBeVisible();
|
||||||
|
await expect(page.locator('text=Overdue Invoices')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('revenue card and chart only visible to admin', async ({ page }) => {
|
||||||
|
// Admin login — revenue card should show
|
||||||
|
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||||
|
await expect(page.locator('text=Monthly Revenue')).toBeVisible();
|
||||||
|
await expect(page.locator('text=Revenue Overview')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('recent tickets section renders', async ({ page }) => {
|
||||||
|
await expect(page.locator('text=Recent Tickets')).toBeVisible();
|
||||||
|
await expect(page.locator('text=View all →')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refresh button works without crash', async ({ page }) => {
|
||||||
|
await page.click('button:has-text("Refresh")');
|
||||||
|
// Should not crash — page still has dashboard title
|
||||||
|
await expect(page.locator('h1:has-text("Dashboard")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('New Client button navigates to clients', async ({ page }) => {
|
||||||
|
// Wait for dashboard to fully render before interacting
|
||||||
|
await expect(page.locator('h1:has-text("Dashboard")')).toBeVisible();
|
||||||
|
// Use data-testid if available (post-deploy), fall back to text selector
|
||||||
|
const btn = page.locator('[data-testid="new-client-btn"], button:has-text("+ New Client")').first();
|
||||||
|
await expect(btn).toBeVisible({ timeout: 10000 });
|
||||||
|
await btn.click();
|
||||||
|
await expect(page).toHaveURL(/\/clients/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('KPI card click navigates correctly', async ({ page }) => {
|
||||||
|
await page.waitForSelector('.skeleton', { state: 'detached', timeout: 15000 }).catch(() => {});
|
||||||
|
// Click Total Clients card
|
||||||
|
const clientsCard = page.locator('text=Total Clients').first();
|
||||||
|
await clientsCard.click();
|
||||||
|
await expect(page).toHaveURL(/\/clients/);
|
||||||
|
});
|
||||||
|
});
|
||||||
74
e2e/helpers/auth.ts
Normal file
74
e2e/helpers/auth.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { Page, request as playwrightRequest } from '@playwright/test';
|
||||||
|
|
||||||
|
export const DEMO = {
|
||||||
|
tenant: 'demo-isp',
|
||||||
|
email: 'admin@demo-isp.com',
|
||||||
|
password: 'Admin123!',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Use the public API URL — Node.js requests bypass browser CORS
|
||||||
|
const API_URL = 'https://fiberops-api.juankibin.space';
|
||||||
|
|
||||||
|
// Cache token across tests to avoid rate-limiting
|
||||||
|
let cachedAuth: { accessToken: string; user: any; expiresAt: number } | null = null;
|
||||||
|
|
||||||
|
export async function loginViaAPI(creds = DEMO) {
|
||||||
|
// Return cached token if still fresh (within 4 minutes)
|
||||||
|
if (cachedAuth && Date.now() < cachedAuth.expiresAt) {
|
||||||
|
return { accessToken: cachedAuth.accessToken, user: cachedAuth.user };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retry up to 3 times with backoff
|
||||||
|
for (let attempt = 0; attempt < 3; attempt++) {
|
||||||
|
const ctx = await playwrightRequest.newContext({ baseURL: API_URL });
|
||||||
|
try {
|
||||||
|
const resp = await ctx.post('/api/v1/auth/login', {
|
||||||
|
data: { tenantSlug: creds.tenant, email: creds.email, password: creds.password },
|
||||||
|
headers: { 'Content-Type': 'application/json', 'x-tenant-slug': creds.tenant },
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.accessToken) {
|
||||||
|
// Cache for 4 minutes
|
||||||
|
cachedAuth = {
|
||||||
|
accessToken: data.accessToken,
|
||||||
|
user: data.user,
|
||||||
|
expiresAt: Date.now() + 4 * 60 * 1000,
|
||||||
|
};
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
console.warn(`Login attempt ${attempt + 1} returned no token:`, JSON.stringify(data).slice(0, 200));
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`Login attempt ${attempt + 1} failed:`, err);
|
||||||
|
} finally {
|
||||||
|
await ctx.dispose();
|
||||||
|
}
|
||||||
|
// Backoff
|
||||||
|
if (attempt < 2) await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
|
||||||
|
}
|
||||||
|
throw new Error('loginViaAPI: Failed to obtain token after 3 attempts');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function login(page: Page, creds = DEMO) {
|
||||||
|
// Step 1: Get token via Node.js HTTP — bypasses browser CORS entirely
|
||||||
|
const { accessToken, user } = await loginViaAPI(creds);
|
||||||
|
|
||||||
|
// Step 2: Inject zustand persist state into localStorage before navigation
|
||||||
|
await page.goto('/login');
|
||||||
|
await page.evaluate(
|
||||||
|
({ token, tenant, u }) => {
|
||||||
|
// Zustand persist format: { state: {...}, version: 0 }
|
||||||
|
localStorage.setItem('fiberops_auth', JSON.stringify({
|
||||||
|
state: { accessToken: token, tenantSlug: tenant, user: u },
|
||||||
|
version: 0,
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
{ token: accessToken, tenant: creds.tenant, u: user }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Step 3: Navigate to dashboard — auth guard reads localStorage and passes
|
||||||
|
await page.goto('/dashboard');
|
||||||
|
await page.waitForURL(/\/(dashboard|clients|settings)/, { timeout: 15000 });
|
||||||
|
|
||||||
|
// Step 4: Verify we're actually on the dashboard (not redirected to login)
|
||||||
|
await page.waitForSelector('h1:has-text("Dashboard")', { timeout: 10000 });
|
||||||
|
}
|
||||||
42
e2e/invoices.spec.ts
Normal file
42
e2e/invoices.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Invoices', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/invoices');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invoices page renders', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Invoices")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invoice rows load', async ({ page }) => {
|
||||||
|
await page.waitForSelector('tbody tr', { timeout: 15000 });
|
||||||
|
const rows = page.locator('tbody tr');
|
||||||
|
const count = await rows.count();
|
||||||
|
expect(count).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status filter chips work', async ({ page }) => {
|
||||||
|
await page.waitForSelector('tbody tr', { timeout: 10000 });
|
||||||
|
// Status filter buttons should exist
|
||||||
|
const filterBtn = page.locator('button:has-text("OVERDUE"), button:has-text("Overdue")').first();
|
||||||
|
if (await filterBtn.isVisible()) {
|
||||||
|
await filterBtn.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
// Should filter without crashing
|
||||||
|
await expect(page.locator('h1:has-text("Invoices")')).toBeVisible();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking invoice row opens detail modal', async ({ page }) => {
|
||||||
|
await page.waitForSelector('tbody tr', { timeout: 15000 });
|
||||||
|
await page.locator('tbody tr').first().click();
|
||||||
|
// Modal or detail should open
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
// Should show some invoice details
|
||||||
|
await expect(page.locator('text=Invoice')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
31
e2e/leads.spec.ts
Normal file
31
e2e/leads.spec.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Leads', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/leads');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('leads page renders with pipeline summary', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Leads")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('leads list loads', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
// Either shows rows or empty state
|
||||||
|
const hasRows = await page.locator('tbody tr').count();
|
||||||
|
const hasEmpty = await page.locator('text=No leads').isVisible().catch(() => false);
|
||||||
|
expect(hasRows > 0 || hasEmpty).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Add Lead modal opens and closes', async ({ page }) => {
|
||||||
|
const addBtn = page.locator('button:has-text("Add Lead")');
|
||||||
|
if (await addBtn.isVisible()) {
|
||||||
|
await addBtn.click();
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await expect(page.locator('text=Add Lead, text=New Lead').first()).toBeVisible();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
46
e2e/payments.spec.ts
Normal file
46
e2e/payments.spec.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Payments', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/payments');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('page renders with header and table', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Payments")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('payments list loads rows from API', async ({ page }) => {
|
||||||
|
await expect(page.locator('[data-testid="payment-row"]').first()).toBeVisible({ timeout: 15000 });
|
||||||
|
const count = await page.locator('[data-testid="payment-row"]').count();
|
||||||
|
expect(count).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('channel filter buttons exist and toggle active state', async ({ page }) => {
|
||||||
|
const cashBtn = page.locator('button:has-text("CASH")').first();
|
||||||
|
await expect(cashBtn).toBeVisible();
|
||||||
|
await cashBtn.click();
|
||||||
|
await expect(cashBtn).toHaveClass(/bg-blue-600/);
|
||||||
|
// Reset to All
|
||||||
|
await page.locator('button:has-text("All")').first().click();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking payment row opens detail modal', async ({ page }) => {
|
||||||
|
await expect(page.locator('[data-testid="payment-row"]').first()).toBeVisible({ timeout: 15000 });
|
||||||
|
await page.locator('[data-testid="payment-row"]').first().click();
|
||||||
|
await expect(page.locator('text=Payment Details')).toBeVisible({ timeout: 5000 });
|
||||||
|
// Check modal has key fields
|
||||||
|
await expect(page.locator('.fixed.inset-0 span:has-text("Amount")').first()).toBeVisible();
|
||||||
|
await expect(page.locator('.fixed.inset-0 span:has-text("Method")').first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('detail modal closes on close button', async ({ page }) => {
|
||||||
|
await expect(page.locator('[data-testid="payment-row"]').first()).toBeVisible({ timeout: 15000 });
|
||||||
|
await page.locator('[data-testid="payment-row"]').first().click();
|
||||||
|
await expect(page.locator('text=Payment Details')).toBeVisible({ timeout: 5000 });
|
||||||
|
await page.locator('button:has-text("Close")').click();
|
||||||
|
await expect(page.locator('text=Payment Details')).not.toBeVisible({ timeout: 5000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
95
e2e/plans.spec.ts
Normal file
95
e2e/plans.spec.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Plans', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/plans');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('plans page renders with header and table', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Plans")')).toBeVisible({ timeout: 10000 });
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
await expect(page.locator('[data-testid="btn-add-plan"]')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('plans list loads rows from API', async ({ page }) => {
|
||||||
|
// Wait for rows to appear (demo tenant has seeded plans)
|
||||||
|
await page.waitForSelector('[data-testid="plan-row"]', { timeout: 20000 });
|
||||||
|
const rows = page.locator('[data-testid="plan-row"]');
|
||||||
|
expect(await rows.count()).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('add plan modal opens and submits', async ({ page }) => {
|
||||||
|
// Wait for page to be ready
|
||||||
|
await page.waitForSelector('h1:has-text("Plans")', { timeout: 10000 });
|
||||||
|
|
||||||
|
await page.click('[data-testid="btn-add-plan"]');
|
||||||
|
|
||||||
|
// Modal should appear
|
||||||
|
await expect(page.locator('[data-testid="modal-create-plan"]')).toBeVisible({ timeout: 5000 });
|
||||||
|
|
||||||
|
// Fill form with real API fields
|
||||||
|
const planName = `E2E Plan ${Date.now()}`;
|
||||||
|
await page.fill('[data-testid="input-plan-name"]', planName);
|
||||||
|
await page.selectOption('[data-testid="select-plan-type"]', 'PREPAID');
|
||||||
|
await page.fill('[data-testid="input-plan-speed-down"]', '50');
|
||||||
|
await page.fill('[data-testid="input-plan-speed-up"]', '20');
|
||||||
|
await page.fill('[data-testid="input-plan-price"]', '1499');
|
||||||
|
await page.fill('[data-testid="input-plan-description"]', 'E2E test plan');
|
||||||
|
|
||||||
|
// Submit
|
||||||
|
await page.click('[data-testid="btn-submit-create"]');
|
||||||
|
|
||||||
|
// Modal should close (API call + state update)
|
||||||
|
await expect(page.locator('[data-testid="modal-create-plan"]')).not.toBeVisible({ timeout: 15000 });
|
||||||
|
|
||||||
|
// New plan should appear in the table
|
||||||
|
await expect(page.locator(`text=${planName}`)).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('edit plan modal opens and submits', async ({ page }) => {
|
||||||
|
// Wait for rows
|
||||||
|
await page.waitForSelector('[data-testid="plan-row"]', { timeout: 20000 });
|
||||||
|
|
||||||
|
const editBtns = page.locator('[data-testid="btn-edit-plan"]');
|
||||||
|
expect(await editBtns.count()).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Click first edit button
|
||||||
|
await editBtns.first().click();
|
||||||
|
|
||||||
|
// Edit modal should open
|
||||||
|
await expect(page.locator('[data-testid="modal-edit-plan"]')).toBeVisible({ timeout: 5000 });
|
||||||
|
await expect(page.locator('[data-testid="input-edit-name"]')).toBeVisible();
|
||||||
|
|
||||||
|
// Change download speed
|
||||||
|
await page.fill('[data-testid="input-edit-speed-down"]', '100');
|
||||||
|
|
||||||
|
// Submit
|
||||||
|
await page.click('[data-testid="btn-submit-edit"]');
|
||||||
|
|
||||||
|
// Modal should close
|
||||||
|
await expect(page.locator('[data-testid="modal-edit-plan"]')).not.toBeVisible({ timeout: 15000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('delete plan shows confirmation and cancels', async ({ page }) => {
|
||||||
|
// Wait for rows
|
||||||
|
await page.waitForSelector('[data-testid="plan-row"]', { timeout: 20000 });
|
||||||
|
|
||||||
|
const deleteBtns = page.locator('[data-testid="btn-delete-plan"]');
|
||||||
|
expect(await deleteBtns.count()).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Click last delete button
|
||||||
|
await deleteBtns.last().click();
|
||||||
|
|
||||||
|
// Confirmation modal should appear
|
||||||
|
await expect(page.locator('[data-testid="modal-delete-plan"]')).toBeVisible({ timeout: 5000 });
|
||||||
|
await expect(page.locator('[data-testid="btn-confirm-delete"]')).toBeVisible();
|
||||||
|
|
||||||
|
// Cancel the delete (don't actually delete seeded data)
|
||||||
|
await page.click('[data-testid="btn-cancel-delete"]');
|
||||||
|
|
||||||
|
// Modal should close
|
||||||
|
await expect(page.locator('[data-testid="modal-delete-plan"]')).not.toBeVisible({ timeout: 5000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
42
e2e/portal.spec.ts
Normal file
42
e2e/portal.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
|
test.describe('Subscriber Portal', () => {
|
||||||
|
test('portal login page loads', async ({ page }) => {
|
||||||
|
await page.goto('/portal/login');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('input[type="text"], input[placeholder*="account" i]').first()).toBeVisible({ timeout: 10000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('portal login page has password field', async ({ page }) => {
|
||||||
|
await page.goto('/portal/login');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('input[type="password"]')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('portal login page shows FiberOps branding', async ({ page }) => {
|
||||||
|
await page.goto('/portal/login');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=FiberOps').first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('portal login redirects to dashboard on wrong creds', async ({ page }) => {
|
||||||
|
await page.goto('/portal/login');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
// Fill and submit
|
||||||
|
const inputs = page.locator('input');
|
||||||
|
const count = await inputs.count();
|
||||||
|
if (count >= 3) {
|
||||||
|
await inputs.nth(0).fill('demo-isp');
|
||||||
|
await inputs.nth(1).fill('ACC-000001');
|
||||||
|
await inputs.nth(2).fill('wrongpassword');
|
||||||
|
}
|
||||||
|
// Should stay on login (not crash)
|
||||||
|
const btn = page.locator('button[type="submit"], button:has-text("Login"), button:has-text("Sign In")').first();
|
||||||
|
if (await btn.isVisible()) {
|
||||||
|
await btn.click();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
}
|
||||||
|
// Should not crash — still render something
|
||||||
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
49
e2e/remittances.spec.ts
Normal file
49
e2e/remittances.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Remittances', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/remittances');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('page renders with header and table', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Remittances")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submit remittance button exists', async ({ page }) => {
|
||||||
|
await expect(page.locator('[data-testid="btn-submit-remittance"]')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submit remittance modal opens', async ({ page }) => {
|
||||||
|
await page.click('[data-testid="btn-submit-remittance"]');
|
||||||
|
await expect(page.getByRole('heading', { name: 'Submit Remittance' })).toBeVisible({ timeout: 5000 });
|
||||||
|
// Close modal
|
||||||
|
await page.locator('button:has-text("Cancel")').click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Submit Remittance' })).not.toBeVisible({ timeout: 3000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty state or rows shown after load', async ({ page }) => {
|
||||||
|
// Wait for loading skeleton to disappear
|
||||||
|
await page.waitForFunction(() => !document.querySelector('.animate-pulse'), { timeout: 10000 });
|
||||||
|
const hasRows = await page.locator('[data-testid="remittance-row"]').count();
|
||||||
|
const hasEmpty = await page.locator('text=No remittances yet').count();
|
||||||
|
expect(hasRows > 0 || hasEmpty > 0).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking remittance row opens detail modal', async ({ page }) => {
|
||||||
|
const rows = page.locator('[data-testid="remittance-row"]');
|
||||||
|
const count = await rows.count();
|
||||||
|
if (count === 0) {
|
||||||
|
// No data — acceptable, skip
|
||||||
|
test.skip();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await rows.first().click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Remittance Details' })).toBeVisible({ timeout: 5000 });
|
||||||
|
await expect(page.locator('text=Total Amount')).toBeVisible();
|
||||||
|
await page.locator('button:has-text("Close")').click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Remittance Details' })).not.toBeVisible({ timeout: 3000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
27
e2e/reports.spec.ts
Normal file
27
e2e/reports.spec.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Reports', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/reports');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reports page renders with KPI cards', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Reports")')).toBeVisible();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
// At least one KPI card should be visible
|
||||||
|
await expect(page.locator('text=Total Collected, text=Collection, text=Report').first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('collection section renders', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
await expect(page.locator('text=Collection')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('page does not crash on load', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
// Page should still have the heading — no JS crash
|
||||||
|
await expect(page.locator('h1:has-text("Reports")')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
34
e2e/settings.spec.ts
Normal file
34
e2e/settings.spec.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Settings', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/settings');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('settings page renders', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Settings")')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant settings section visible', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
// Tenant tab in sidebar nav
|
||||||
|
await expect(page.locator('button:has-text("Tenant"), a:has-text("Tenant")').first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('billing settings section visible', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Billing').first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('users section visible to admin', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await expect(page.locator('text=Users')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('settings page does not crash', async ({ page }) => {
|
||||||
|
await page.waitForTimeout(4000);
|
||||||
|
await expect(page.locator('h1:has-text("Settings")')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
46
e2e/tickets.spec.ts
Normal file
46
e2e/tickets.spec.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { login } from './helpers/auth';
|
||||||
|
|
||||||
|
test.describe('Tickets', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/tickets');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tickets page renders', async ({ page }) => {
|
||||||
|
await expect(page.locator('h1:has-text("Tickets")')).toBeVisible();
|
||||||
|
await expect(page.locator('table')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tickets load', async ({ page }) => {
|
||||||
|
await page.waitForSelector('tbody tr', { timeout: 15000 });
|
||||||
|
const count = await page.locator('tbody tr').count();
|
||||||
|
expect(count).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('type filter chips work', async ({ page }) => {
|
||||||
|
const chip = page.locator('button:has-text("SUPPORT"), button:has-text("Support")').first();
|
||||||
|
if (await chip.isVisible()) {
|
||||||
|
await chip.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('h1:has-text("Tickets")')).toBeVisible();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking ticket row opens detail modal', async ({ page }) => {
|
||||||
|
await page.waitForSelector('tbody tr', { timeout: 15000 });
|
||||||
|
await page.locator('tbody tr').first().click();
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
// Detail modal should appear
|
||||||
|
await expect(page.locator('text=Ticket Detail, text=Subject, text=Status').first()).toBeVisible({ timeout: 5000 }).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('New Ticket button opens modal', async ({ page }) => {
|
||||||
|
const newBtn = page.locator('button:has-text("New Ticket")');
|
||||||
|
if (await newBtn.isVisible()) {
|
||||||
|
await newBtn.click();
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await expect(page.locator('text=New Ticket, text=Create Ticket').first()).toBeVisible();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
115
package-lock.json
generated
115
package-lock.json
generated
@@ -32,12 +32,12 @@
|
|||||||
"shadcn": "^4.1.0",
|
"shadcn": "^4.1.0",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"zod": "^4.3.6",
|
"zod": "^4.3.6",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^18",
|
"@types/react": "^18",
|
||||||
"@types/react-dom": "^18",
|
"@types/react-dom": "^18",
|
||||||
@@ -52,6 +52,7 @@
|
|||||||
"version": "5.2.0",
|
"version": "5.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
|
||||||
"integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",
|
"integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
@@ -1547,6 +1548,22 @@
|
|||||||
"node": ">=14"
|
"node": ">=14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/number": {
|
"node_modules/@radix-ui/number": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
|
||||||
@@ -3377,12 +3394,14 @@
|
|||||||
"version": "1.3.0",
|
"version": "1.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
|
||||||
"integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
|
"integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/anymatch": {
|
"node_modules/anymatch": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
|
||||||
"integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
|
"integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
|
||||||
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"normalize-path": "^3.0.0",
|
"normalize-path": "^3.0.0",
|
||||||
@@ -3396,6 +3415,7 @@
|
|||||||
"version": "5.0.2",
|
"version": "5.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
|
||||||
"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
|
"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/argparse": {
|
"node_modules/argparse": {
|
||||||
@@ -3691,6 +3711,7 @@
|
|||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
||||||
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
|
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
@@ -3875,6 +3896,7 @@
|
|||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
|
||||||
"integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",
|
"integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
@@ -3921,6 +3943,7 @@
|
|||||||
"version": "3.6.0",
|
"version": "3.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"anymatch": "~3.1.2",
|
"anymatch": "~3.1.2",
|
||||||
@@ -3945,6 +3968,7 @@
|
|||||||
"version": "5.1.2",
|
"version": "5.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||||
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||||
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"is-glob": "^4.0.1"
|
"is-glob": "^4.0.1"
|
||||||
@@ -4107,6 +4131,7 @@
|
|||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
|
||||||
"integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
|
"integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
@@ -4599,6 +4624,7 @@
|
|||||||
"version": "1.2.2",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
|
||||||
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
|
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
|
||||||
|
"dev": true,
|
||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
},
|
},
|
||||||
"node_modules/diff": {
|
"node_modules/diff": {
|
||||||
@@ -4614,6 +4640,7 @@
|
|||||||
"version": "1.1.3",
|
"version": "1.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
|
||||||
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
|
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/doctrine": {
|
"node_modules/doctrine": {
|
||||||
@@ -5872,6 +5899,7 @@
|
|||||||
"version": "2.3.3",
|
"version": "2.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||||
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
@@ -6101,6 +6129,7 @@
|
|||||||
"version": "6.0.2",
|
"version": "6.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
|
||||||
"integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
|
"integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
|
||||||
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"is-glob": "^4.0.3"
|
"is-glob": "^4.0.3"
|
||||||
@@ -6535,6 +6564,7 @@
|
|||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
|
||||||
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
|
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"binary-extensions": "^2.0.0"
|
"binary-extensions": "^2.0.0"
|
||||||
@@ -6587,6 +6617,7 @@
|
|||||||
"version": "2.16.1",
|
"version": "2.16.1",
|
||||||
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
|
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
|
||||||
"integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
|
"integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"hasown": "^2.0.2"
|
"hasown": "^2.0.2"
|
||||||
@@ -7104,6 +7135,7 @@
|
|||||||
"version": "1.21.7",
|
"version": "1.21.7",
|
||||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",
|
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",
|
||||||
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
|
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"bin": {
|
"bin": {
|
||||||
"jiti": "bin/jiti.js"
|
"jiti": "bin/jiti.js"
|
||||||
@@ -7279,6 +7311,7 @@
|
|||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
|
||||||
"integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
|
"integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14"
|
"node": ">=14"
|
||||||
@@ -7607,6 +7640,7 @@
|
|||||||
"version": "2.7.0",
|
"version": "2.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
|
||||||
"integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
|
"integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"any-promise": "^1.0.0",
|
"any-promise": "^1.0.0",
|
||||||
@@ -7829,6 +7863,7 @@
|
|||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||||
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
@@ -7875,6 +7910,7 @@
|
|||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
|
||||||
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
|
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
@@ -8306,6 +8342,7 @@
|
|||||||
"version": "1.0.7",
|
"version": "1.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
||||||
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
|
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/path-scurry": {
|
"node_modules/path-scurry": {
|
||||||
@@ -8353,6 +8390,7 @@
|
|||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
|
||||||
"integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
|
"integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
@@ -8362,6 +8400,7 @@
|
|||||||
"version": "4.0.7",
|
"version": "4.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
|
||||||
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
@@ -8376,6 +8415,53 @@
|
|||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright/node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/possible-typed-array-names": {
|
"node_modules/possible-typed-array-names": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||||
@@ -8418,6 +8504,7 @@
|
|||||||
"version": "15.1.0",
|
"version": "15.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz",
|
||||||
"integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",
|
"integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"postcss-value-parser": "^4.0.0",
|
"postcss-value-parser": "^4.0.0",
|
||||||
@@ -8435,6 +8522,7 @@
|
|||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz",
|
||||||
"integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",
|
"integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",
|
||||||
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -8460,6 +8548,7 @@
|
|||||||
"version": "6.0.1",
|
"version": "6.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
|
||||||
"integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
|
"integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
|
||||||
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -8502,6 +8591,7 @@
|
|||||||
"version": "6.2.0",
|
"version": "6.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",
|
||||||
"integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",
|
"integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",
|
||||||
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -8527,6 +8617,7 @@
|
|||||||
"version": "6.1.2",
|
"version": "6.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
|
||||||
"integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
|
"integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"cssesc": "^3.0.0",
|
"cssesc": "^3.0.0",
|
||||||
@@ -8540,6 +8631,7 @@
|
|||||||
"version": "4.2.0",
|
"version": "4.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
|
||||||
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
|
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/powershell-utils": {
|
"node_modules/powershell-utils": {
|
||||||
@@ -8844,6 +8936,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
|
||||||
"integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",
|
"integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"pify": "^2.3.0"
|
"pify": "^2.3.0"
|
||||||
@@ -8853,6 +8946,7 @@
|
|||||||
"version": "3.6.0",
|
"version": "3.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
|
||||||
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
|
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"picomatch": "^2.2.1"
|
"picomatch": "^2.2.1"
|
||||||
@@ -8994,6 +9088,7 @@
|
|||||||
"version": "1.22.11",
|
"version": "1.22.11",
|
||||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
|
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
|
||||||
"integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",
|
"integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"is-core-module": "^2.16.1",
|
"is-core-module": "^2.16.1",
|
||||||
@@ -9953,6 +10048,7 @@
|
|||||||
"version": "3.35.1",
|
"version": "3.35.1",
|
||||||
"resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
|
"resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
|
||||||
"integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
|
"integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jridgewell/gen-mapping": "^0.3.2",
|
"@jridgewell/gen-mapping": "^0.3.2",
|
||||||
@@ -9988,6 +10084,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
|
||||||
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
|
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.4"
|
"node": ">= 0.4"
|
||||||
@@ -10028,6 +10125,7 @@
|
|||||||
"version": "3.4.19",
|
"version": "3.4.19",
|
||||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",
|
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",
|
||||||
"integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==",
|
"integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@alloc/quick-lru": "^5.2.0",
|
"@alloc/quick-lru": "^5.2.0",
|
||||||
@@ -10061,15 +10159,6 @@
|
|||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tailwindcss-animate": {
|
|
||||||
"version": "1.0.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/tailwindcss-animate/-/tailwindcss-animate-1.0.7.tgz",
|
|
||||||
"integrity": "sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"peerDependencies": {
|
|
||||||
"tailwindcss": ">=3.0.0 || insiders"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/text-table": {
|
"node_modules/text-table": {
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
|
||||||
@@ -10081,6 +10170,7 @@
|
|||||||
"version": "3.3.1",
|
"version": "3.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
|
||||||
"integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
|
"integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"any-promise": "^1.0.0"
|
"any-promise": "^1.0.0"
|
||||||
@@ -10090,6 +10180,7 @@
|
|||||||
"version": "1.6.0",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
|
||||||
"integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
|
"integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"thenify": ">= 3.1.0 < 4"
|
"thenify": ">= 3.1.0 < 4"
|
||||||
@@ -10108,6 +10199,7 @@
|
|||||||
"version": "0.2.15",
|
"version": "0.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fdir": "^6.5.0",
|
"fdir": "^6.5.0",
|
||||||
@@ -10124,6 +10216,7 @@
|
|||||||
"version": "6.5.0",
|
"version": "6.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
@@ -10141,6 +10234,7 @@
|
|||||||
"version": "4.0.4",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||||
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
@@ -10217,6 +10311,7 @@
|
|||||||
"version": "0.1.13",
|
"version": "0.1.13",
|
||||||
"resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
|
"resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
|
||||||
"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
|
"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
|
||||||
|
"dev": true,
|
||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
},
|
},
|
||||||
"node_modules/ts-morph": {
|
"node_modules/ts-morph": {
|
||||||
|
|||||||
@@ -33,12 +33,12 @@
|
|||||||
"shadcn": "^4.1.0",
|
"shadcn": "^4.1.0",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"zod": "^4.3.6",
|
"zod": "^4.3.6",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^18",
|
"@types/react": "^18",
|
||||||
"@types/react-dom": "^18",
|
"@types/react-dom": "^18",
|
||||||
|
|||||||
12
pages/_document.tsx
Normal file
12
pages/_document.tsx
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Html, Head, Main, NextScript } from 'next/document';
|
||||||
|
export default function Document() {
|
||||||
|
return (
|
||||||
|
<Html lang="en">
|
||||||
|
<Head />
|
||||||
|
<body>
|
||||||
|
<Main />
|
||||||
|
<NextScript />
|
||||||
|
</body>
|
||||||
|
</Html>
|
||||||
|
);
|
||||||
|
}
|
||||||
14
pages/_error.tsx
Normal file
14
pages/_error.tsx
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// Custom error page — prevents Html import issue in Next.js pages router
|
||||||
|
export default function Error({ statusCode }: { statusCode?: number }) {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: '2rem', fontFamily: 'sans-serif' }}>
|
||||||
|
<h1>{statusCode || 'Error'}</h1>
|
||||||
|
<p>{statusCode === 404 ? 'Page not found' : 'An error occurred'}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Error.getInitialProps = ({ res, err }: any) => {
|
||||||
|
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
|
||||||
|
return { statusCode };
|
||||||
|
};
|
||||||
22
playwright.config.ts
Normal file
22
playwright.config.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './e2e',
|
||||||
|
timeout: 60000, // 60s per test — accounts for ~2s API latency via CF tunnel
|
||||||
|
fullyParallel: false,
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
retries: 1,
|
||||||
|
workers: 1,
|
||||||
|
reporter: [['html', { outputFolder: 'playwright-report' }], ['line']],
|
||||||
|
use: {
|
||||||
|
baseURL: process.env.E2E_BASE_URL || 'http://192.168.1.167:3002',
|
||||||
|
trace: 'on-first-retry',
|
||||||
|
screenshot: 'only-on-failure',
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: 'chromium',
|
||||||
|
use: { ...devices['Desktop Chrome'], headless: true },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
0
public/.gitkeep
Normal file
0
public/.gitkeep
Normal file
41
src/components/accounting/AccountingNav.tsx
Normal file
41
src/components/accounting/AccountingNav.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { BookOpen, BookText, Receipt, Building2, BarChart3 } from "lucide-react";
|
||||||
|
|
||||||
|
const NAV_ITEMS = [
|
||||||
|
{ href: "/accounting", label: "Chart of Accounts", icon: BookOpen, exact: true },
|
||||||
|
{ href: "/accounting/journal-entries", label: "Journal Entries", icon: BookText },
|
||||||
|
{ href: "/accounting/expenses", label: "Expenses", icon: Receipt },
|
||||||
|
{ href: "/accounting/company-accounts", label: "Company Accounts", icon: Building2 },
|
||||||
|
{ href: "/accounting/reports", label: "Reports", icon: BarChart3 },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AccountingNav() {
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav className="flex gap-1 border-b border-gray-200 mb-6 overflow-x-auto">
|
||||||
|
{NAV_ITEMS.map(({ href, label, icon: Icon, exact }) => {
|
||||||
|
const isActive = exact ? pathname === href : pathname === href || pathname.startsWith(href + "/");
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={href}
|
||||||
|
href={href}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px whitespace-nowrap transition-colors",
|
||||||
|
isActive
|
||||||
|
? "border-blue-600 text-blue-700"
|
||||||
|
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="h-4 w-4" />
|
||||||
|
{label}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
Wifi,
|
Wifi,
|
||||||
Briefcase,
|
Briefcase,
|
||||||
BarChart2,
|
BarChart2,
|
||||||
|
BookOpen,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ const navItems = [
|
|||||||
{ href: "/users", label: "Users", icon: UserCog },
|
{ href: "/users", label: "Users", icon: UserCog },
|
||||||
{ href: "/audit-log", label: "Audit Log", icon: ClipboardList },
|
{ href: "/audit-log", label: "Audit Log", icon: ClipboardList },
|
||||||
{ href: "/reports", label: "Reports", icon: BarChart2 },
|
{ href: "/reports", label: "Reports", icon: BarChart2 },
|
||||||
|
{ href: "/accounting", label: "Accounting", icon: BookOpen },
|
||||||
{ href: "/settings", label: "Settings", icon: Settings },
|
{ href: "/settings", label: "Settings", icon: Settings },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { HTMLAttributes, TdHTMLAttributes, ThHTMLAttributes } from "react";
|
||||||
|
|
||||||
interface TableProps {
|
interface TableProps {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -23,23 +24,26 @@ export function TableBody({ children }: TableProps) {
|
|||||||
return <tbody className="divide-y divide-gray-100">{children}</tbody>;
|
return <tbody className="divide-y divide-gray-100">{children}</tbody>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TableRow({ children, className, onClick }: TableProps & { onClick?: () => void }) {
|
export function TableRow({
|
||||||
|
children, className, onClick, ...rest
|
||||||
|
}: TableProps & { onClick?: () => void } & HTMLAttributes<HTMLTableRowElement>) {
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
className={cn("transition-colors", onClick && "cursor-pointer hover:bg-blue-50", className)}
|
className={cn("transition-colors", onClick && "cursor-pointer hover:bg-blue-50", className)}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
|
{...rest}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</tr>
|
</tr>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Th({ children, className }: TableProps) {
|
export function Th({ children, className, ...rest }: TableProps & ThHTMLAttributes<HTMLTableCellElement>) {
|
||||||
return <th className={cn("px-4 py-3 text-left font-medium", className)}>{children}</th>;
|
return <th className={cn("px-4 py-3 text-left font-medium", className)} {...rest}>{children}</th>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Td({ children, className }: TableProps) {
|
export function Td({ children, className, ...rest }: TableProps & TdHTMLAttributes<HTMLTableCellElement>) {
|
||||||
return <td className={cn("px-4 py-3 text-gray-700", className)}>{children}</td>;
|
return <td className={cn("px-4 py-3 text-gray-700", className)} {...rest}>{children}</td>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function EmptyState({ message = "No data yet" }: { message?: string }) {
|
export function EmptyState({ message = "No data yet" }: { message?: string }) {
|
||||||
|
|||||||
@@ -46,10 +46,13 @@ export interface Client {
|
|||||||
phone: string;
|
phone: string;
|
||||||
address?: string;
|
address?: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
|
lat?: number | null;
|
||||||
|
lng?: number | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
area?: { id: string; name: string };
|
area?: { id: string; name: string };
|
||||||
subscriptions?: Subscription[];
|
subscriptions?: Subscription[];
|
||||||
|
portalAccessEnabled?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Subscription {
|
export interface Subscription {
|
||||||
@@ -63,6 +66,7 @@ export interface Subscription {
|
|||||||
endDate?: string;
|
endDate?: string;
|
||||||
monthlyRate?: number;
|
monthlyRate?: number;
|
||||||
mrc?: number;
|
mrc?: number;
|
||||||
|
monthlyPrice?: number | string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,6 +212,110 @@ export interface LegacyPaginatedResponse<T> {
|
|||||||
limit: number;
|
limit: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Accounting ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type AccountType = 'ASSET' | 'LIABILITY' | 'EQUITY' | 'REVENUE' | 'EXPENSE';
|
||||||
|
|
||||||
|
export interface Account {
|
||||||
|
id: string;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
type: AccountType;
|
||||||
|
isActive: boolean;
|
||||||
|
balance?: number;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JournalEntryLine {
|
||||||
|
id?: string;
|
||||||
|
accountId: string;
|
||||||
|
account?: Account;
|
||||||
|
debit: number;
|
||||||
|
credit: number;
|
||||||
|
memo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JournalEntry {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
reference?: string;
|
||||||
|
description: string;
|
||||||
|
sourceType?: string;
|
||||||
|
lines: JournalEntryLine[];
|
||||||
|
totalDebit?: number;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Expense {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
vendor?: string;
|
||||||
|
accountId: string;
|
||||||
|
account?: Account;
|
||||||
|
amount: number;
|
||||||
|
description?: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CompanyAccountType = 'CASH' | 'BANK' | 'EWALLET';
|
||||||
|
|
||||||
|
export interface CompanyAccount {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: CompanyAccountType;
|
||||||
|
bankName?: string;
|
||||||
|
accountNumber?: string;
|
||||||
|
balance: number;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Transfer {
|
||||||
|
id: string;
|
||||||
|
fromAccountId: string;
|
||||||
|
fromAccount?: CompanyAccount;
|
||||||
|
toAccountId: string;
|
||||||
|
toAccount?: CompanyAccount;
|
||||||
|
amount: number;
|
||||||
|
date: string;
|
||||||
|
note?: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrialBalanceLine {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
debit: number;
|
||||||
|
credit: number;
|
||||||
|
balance: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProfitLossReport {
|
||||||
|
revenue: Array<{ name: string; amount: number }>;
|
||||||
|
expenses: Array<{ name: string; amount: number }>;
|
||||||
|
totalRevenue: number;
|
||||||
|
totalExpenses: number;
|
||||||
|
netIncome: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BalanceSheetReport {
|
||||||
|
assets: Array<{ name: string; amount: number }>;
|
||||||
|
liabilities: Array<{ name: string; amount: number }>;
|
||||||
|
equity: Array<{ name: string; amount: number }>;
|
||||||
|
totalAssets: number;
|
||||||
|
totalLiabilities: number;
|
||||||
|
totalEquity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CashFlowReport {
|
||||||
|
operating: Array<{ name: string; amount: number }>;
|
||||||
|
investing: Array<{ name: string; amount: number }>;
|
||||||
|
financing: Array<{ name: string; amount: number }>;
|
||||||
|
netOperating: number;
|
||||||
|
netInvesting: number;
|
||||||
|
netFinancing: number;
|
||||||
|
netCashFlow: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Lead {
|
export interface Lead {
|
||||||
id: string;
|
id: string;
|
||||||
firstName: string;
|
firstName: string;
|
||||||
|
|||||||
@@ -1,78 +1,45 @@
|
|||||||
import type { Config } from "tailwindcss";
|
import type { Config } from "tailwindcss";
|
||||||
|
|
||||||
const config: Config = {
|
const config: Config = {
|
||||||
darkMode: ["class"],
|
|
||||||
content: [
|
content: [
|
||||||
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
|
"./src/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
],
|
],
|
||||||
theme: {
|
theme: {
|
||||||
container: {
|
|
||||||
center: true,
|
|
||||||
padding: "2rem",
|
|
||||||
screens: {
|
|
||||||
"2xl": "1400px",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
extend: {
|
extend: {
|
||||||
colors: {
|
colors: {
|
||||||
border: "hsl(var(--border))",
|
// FiberOps design tokens
|
||||||
input: "hsl(var(--input))",
|
fiberops: {
|
||||||
ring: "hsl(var(--ring))",
|
primary: '#0891B2',
|
||||||
background: "hsl(var(--background))",
|
'primary-dark': '#0E7490',
|
||||||
foreground: "hsl(var(--foreground))",
|
secondary: '#22D3EE',
|
||||||
primary: {
|
cta: '#059669',
|
||||||
DEFAULT: "hsl(var(--primary))",
|
'cta-hover': '#047857',
|
||||||
foreground: "hsl(var(--primary-foreground))",
|
bg: '#F8FAFC',
|
||||||
},
|
surface: '#FFFFFF',
|
||||||
secondary: {
|
text: '#0F172A',
|
||||||
DEFAULT: "hsl(var(--secondary))",
|
muted: '#64748B',
|
||||||
foreground: "hsl(var(--secondary-foreground))",
|
border: '#E2E8F0',
|
||||||
},
|
danger: '#EF4444',
|
||||||
destructive: {
|
warning: '#F59E0B',
|
||||||
DEFAULT: "hsl(var(--destructive))",
|
success: '#059669',
|
||||||
foreground: "hsl(var(--destructive-foreground))",
|
|
||||||
},
|
|
||||||
muted: {
|
|
||||||
DEFAULT: "hsl(var(--muted))",
|
|
||||||
foreground: "hsl(var(--muted-foreground))",
|
|
||||||
},
|
|
||||||
accent: {
|
|
||||||
DEFAULT: "hsl(var(--accent))",
|
|
||||||
foreground: "hsl(var(--accent-foreground))",
|
|
||||||
},
|
|
||||||
popover: {
|
|
||||||
DEFAULT: "hsl(var(--popover))",
|
|
||||||
foreground: "hsl(var(--popover-foreground))",
|
|
||||||
},
|
|
||||||
card: {
|
|
||||||
DEFAULT: "hsl(var(--card))",
|
|
||||||
foreground: "hsl(var(--card-foreground))",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['var(--font-fira-sans)', 'Inter', 'system-ui', 'sans-serif'],
|
||||||
|
mono: ['var(--font-fira-code)', 'JetBrains Mono', 'monospace'],
|
||||||
|
},
|
||||||
borderRadius: {
|
borderRadius: {
|
||||||
lg: "var(--radius)",
|
sm: '6px',
|
||||||
md: "calc(var(--radius) - 2px)",
|
DEFAULT: '10px',
|
||||||
sm: "calc(var(--radius) - 4px)",
|
lg: '14px',
|
||||||
},
|
xl: '20px',
|
||||||
keyframes: {
|
|
||||||
"accordion-down": {
|
|
||||||
from: { height: "0" },
|
|
||||||
to: { height: "var(--radix-accordion-content-height)" },
|
|
||||||
},
|
|
||||||
"accordion-up": {
|
|
||||||
from: { height: "var(--radix-accordion-content-height)" },
|
|
||||||
to: { height: "0" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
animation: {
|
|
||||||
"accordion-down": "accordion-down 0.2s ease-out",
|
|
||||||
"accordion-up": "accordion-up 0.2s ease-out",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [require("tailwindcss-animate")],
|
plugins: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
|
|||||||
Reference in New Issue
Block a user