91a66d5645
Replace the default react-toastify look with project-styled toast cards (icon chip, rounded shell, RTL-aware container, type-colored progress bar) via a new notify helper and globals.css overrides. Add a central error layer (src/lib/errors.ts): classify any caught error by HTTP status / network condition, log the full technical detail (including the raw backend message) to the console only, and surface a friendly, localized message to the user. Raw backend messages are no longer shown. All ~190 toast call sites across 22 files move to notify, routing backend errors through notify.error(err, fallback); dead apiErrorMessage/formatApiError helpers removed. Adds an `errors` section to the fa/en dictionaries. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
306 lines
14 KiB
TypeScript
306 lines
14 KiB
TypeScript
'use client';
|
|
|
|
import { useState } from 'react';
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { FileText, Search, User, Wallet, CreditCard, XCircle, Download } from 'lucide-react';
|
|
import { notify } from '@/lib/notify';
|
|
import api from '@/lib/api';
|
|
import { useT, useLocale } from '@/i18n/I18nProvider';
|
|
import type { Invoice, InvoiceStatus, PaymentMethod } from '@/types';
|
|
import { Select } from '@/components/ui/select';
|
|
|
|
const statusClasses: Record<InvoiceStatus, string> = {
|
|
draft: 'badge-gray',
|
|
issued: 'badge-yellow',
|
|
partially_paid: 'badge-blue',
|
|
paid: 'badge-green',
|
|
void: 'badge-gray',
|
|
failed: 'badge-red',
|
|
};
|
|
|
|
export default function AdminInvoicesPage() {
|
|
const t = useT();
|
|
const inv = t.dashboard.invoices;
|
|
const locale = useLocale();
|
|
const statusLabel = (s: InvoiceStatus) => (inv.status as Record<string, string>)[s] ?? s;
|
|
const queryClient = useQueryClient();
|
|
const [status, setStatus] = useState<'all' | InvoiceStatus>('all');
|
|
const [paymentMethod, setPaymentMethod] = useState<'all' | PaymentMethod>('all');
|
|
const [search, setSearch] = useState('');
|
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
|
const [statusReason, setStatusReason] = useState('');
|
|
|
|
const { data: invoices = [], isLoading } = useQuery<Invoice[]>({
|
|
queryKey: ['admin-invoices', status, paymentMethod, search],
|
|
queryFn: () => {
|
|
const params: Record<string, string> = { limit: '200' };
|
|
if (status !== 'all') params.status = status;
|
|
if (paymentMethod !== 'all') params.paymentMethod = paymentMethod;
|
|
if (search.trim()) params.search = search.trim();
|
|
return api.get('/billing/admin/invoices', { params }).then((r) => r.data);
|
|
},
|
|
});
|
|
|
|
const { data: selectedInvoice } = useQuery<Invoice>({
|
|
queryKey: ['admin-invoice', selectedId],
|
|
queryFn: () => api.get(`/billing/admin/invoices/${selectedId}`).then((r) => r.data),
|
|
enabled: !!selectedId,
|
|
});
|
|
|
|
const updateStatusMutation = useMutation({
|
|
mutationFn: ({ invoiceId, nextStatus, reason }: { invoiceId: string; nextStatus: InvoiceStatus; reason: string }) =>
|
|
api.patch(`/billing/admin/invoices/${invoiceId}/status`, { status: nextStatus, reason }).then((r) => r.data),
|
|
onSuccess: () => {
|
|
notify.success(inv.statusUpdated);
|
|
setStatusReason('');
|
|
queryClient.invalidateQueries({ queryKey: ['admin-invoices'] });
|
|
queryClient.invalidateQueries({ queryKey: ['admin-invoice', selectedId] });
|
|
},
|
|
onError: (err: any) => notify.error(err, inv.statusUpdateFailed),
|
|
});
|
|
|
|
const downloadPdfMutation = useMutation({
|
|
mutationFn: async (invoice: Invoice) => {
|
|
const { data } = await api.get(`/billing/admin/invoices/${invoice.id}/pdf`, { responseType: 'blob' });
|
|
const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }));
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = `${invoice.invoiceNumber}.pdf`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
link.remove();
|
|
window.URL.revokeObjectURL(url);
|
|
},
|
|
onError: () => notify.error(inv.downloadFailed),
|
|
});
|
|
|
|
const formatPrice = (amount: number) => Number(amount || 0).toLocaleString('en-US');
|
|
const formatDate = (value?: string) => value ? new Date(value).toLocaleString(locale) : '-';
|
|
|
|
const handleStatusUpdate = (nextStatus: InvoiceStatus) => {
|
|
if (!selectedInvoice) return;
|
|
if (!statusReason.trim()) {
|
|
notify.error(inv.reasonRequired);
|
|
return;
|
|
}
|
|
updateStatusMutation.mutate({
|
|
invoiceId: selectedInvoice.id,
|
|
nextStatus,
|
|
reason: statusReason.trim(),
|
|
});
|
|
};
|
|
|
|
return (
|
|
<div className="max-w-7xl mx-auto space-y-6 animate-fade-in">
|
|
<div>
|
|
<h1 className="page-title flex items-center gap-2">
|
|
<FileText className="w-6 h-6" /> {inv.adminTitle}
|
|
</h1>
|
|
<p className="page-subtitle">{inv.adminSubtitle}</p>
|
|
</div>
|
|
|
|
<div className="card grid grid-cols-1 md:grid-cols-4 gap-3">
|
|
<div className="relative md:col-span-2">
|
|
<Search className="w-4 h-4 text-gray-400 absolute left-3 rtl:left-auto rtl:right-3 top-1/2 -translate-y-1/2" />
|
|
<input
|
|
value={search}
|
|
onChange={(e) => setSearch(e.target.value)}
|
|
placeholder={inv.searchPlaceholder}
|
|
className="input-field pl-9 rtl:pl-3 rtl:pr-9 w-full"
|
|
/>
|
|
</div>
|
|
<Select
|
|
size="md"
|
|
ariaLabel={inv.allStatuses}
|
|
value={status}
|
|
onChange={(v) => setStatus(v as any)}
|
|
options={[
|
|
{ value: 'all', label: inv.allStatuses },
|
|
...(Object.keys(inv.status) as InvoiceStatus[]).map((value) => ({
|
|
value,
|
|
label: statusLabel(value),
|
|
})),
|
|
]}
|
|
/>
|
|
<Select
|
|
size="md"
|
|
ariaLabel={inv.allMethods}
|
|
value={paymentMethod}
|
|
onChange={(v) => setPaymentMethod(v as any)}
|
|
options={[
|
|
{ value: 'all', label: inv.allMethods },
|
|
{ value: 'wallet', label: inv.methodWallet },
|
|
{ value: 'gateway', label: inv.methodGateway },
|
|
{ value: 'mixed', label: inv.methodMixed },
|
|
]}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
|
<div className="xl:col-span-2 card p-0 overflow-hidden">
|
|
<div className="overflow-x-auto">
|
|
<table className="min-w-full divide-y divide-gray-100">
|
|
<thead className="bg-gray-50">
|
|
<tr>
|
|
<th className="px-4 py-3 text-left rtl:text-right text-xs font-semibold text-gray-500 uppercase">{inv.colInvoice}</th>
|
|
<th className="px-4 py-3 text-left rtl:text-right text-xs font-semibold text-gray-500 uppercase">{inv.colUser}</th>
|
|
<th className="px-4 py-3 text-left rtl:text-right text-xs font-semibold text-gray-500 uppercase">{inv.colStatus}</th>
|
|
<th className="px-4 py-3 text-left rtl:text-right text-xs font-semibold text-gray-500 uppercase">{inv.colMethod}</th>
|
|
<th className="px-4 py-3 text-right rtl:text-left text-xs font-semibold text-gray-500 uppercase">{inv.colDue}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-gray-100 bg-white">
|
|
{isLoading ? (
|
|
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400">{t.common.loading}</td></tr>
|
|
) : invoices.length === 0 ? (
|
|
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400">{inv.noInvoices}</td></tr>
|
|
) : invoices.map((invoice) => (
|
|
<tr
|
|
key={invoice.id}
|
|
onClick={() => setSelectedId(invoice.id)}
|
|
className={`cursor-pointer hover:bg-gray-50 ${selectedId === invoice.id ? 'bg-primary-50' : ''}`}
|
|
>
|
|
<td className="px-4 py-3">
|
|
<p className="text-sm font-semibold text-gray-900">{invoice.invoiceNumber}</p>
|
|
<p className="text-xs text-gray-500">{invoice.application?.name || invoice.reason} · {formatDate(invoice.createdAt)}</p>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<p className="text-sm text-gray-900">{invoice.user?.email || invoice.userId}</p>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<span className={statusClasses[invoice.status]}>{statusLabel(invoice.status)}</span>
|
|
</td>
|
|
<td className="px-4 py-3 text-sm text-gray-600">{invoice.paymentMethod || '-'}</td>
|
|
<td className="px-4 py-3 text-right rtl:text-left">
|
|
<p className="text-sm font-bold text-gray-900">{formatPrice(invoice.dueAmount)} {t.common.currencyShort}</p>
|
|
<p className="text-xs text-gray-400">{inv.total} {formatPrice(invoice.total)} {t.common.currencyShort}</p>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="card">
|
|
{!selectedInvoice ? (
|
|
<div className="text-center py-12 text-gray-400">
|
|
<FileText className="w-10 h-10 mx-auto mb-3" />
|
|
{inv.selectInvoiceShort}
|
|
</div>
|
|
) : (
|
|
<div className="space-y-5">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div>
|
|
<h2 className="text-lg font-bold text-gray-900">{selectedInvoice.invoiceNumber}</h2>
|
|
<p className="text-sm text-gray-500">{selectedInvoice.application?.name || selectedInvoice.reason}</p>
|
|
</div>
|
|
<div className="flex flex-col items-end gap-2">
|
|
<span className={statusClasses[selectedInvoice.status]}>{statusLabel(selectedInvoice.status)}</span>
|
|
<button
|
|
type="button"
|
|
onClick={() => downloadPdfMutation.mutate(selectedInvoice)}
|
|
disabled={downloadPdfMutation.isPending}
|
|
className="btn-secondary text-xs inline-flex items-center gap-1 disabled:opacity-50"
|
|
>
|
|
<Download className="w-3.5 h-3.5" />
|
|
{inv.downloadPdf}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="bg-gray-50 rounded-xl p-3">
|
|
<p className="text-xs text-gray-500">{inv.total}</p>
|
|
<p className="font-bold text-gray-900">{formatPrice(selectedInvoice.total)} {t.common.currencyShort}</p>
|
|
</div>
|
|
<div className="bg-gray-50 rounded-xl p-3">
|
|
<p className="text-xs text-gray-500">{inv.due}</p>
|
|
<p className="font-bold text-primary-700">{formatPrice(selectedInvoice.dueAmount)} {t.common.currencyShort}</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2 text-sm">
|
|
<div className="flex items-center gap-2 text-gray-700">
|
|
<User className="w-4 h-4 text-gray-400" />
|
|
{selectedInvoice.user?.email || selectedInvoice.userId}
|
|
</div>
|
|
<div className="flex items-center gap-2 text-gray-700">
|
|
<CreditCard className="w-4 h-4 text-gray-400" />
|
|
{inv.tracking}: {selectedInvoice.gatewayTrackingCode || '-'}
|
|
</div>
|
|
<div className="flex items-center gap-2 text-gray-700">
|
|
<Wallet className="w-4 h-4 text-gray-400" />
|
|
{inv.method}: {selectedInvoice.paymentMethod || '-'}
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<h3 className="text-sm font-semibold text-gray-900 mb-2">{inv.lineItems}</h3>
|
|
<div className="space-y-2">
|
|
{(selectedInvoice.lines || []).map((line) => (
|
|
<div key={line.id} className="border border-gray-100 rounded-xl p-3 flex justify-between gap-3">
|
|
<div>
|
|
<p className="text-sm font-medium text-gray-900">{line.label}</p>
|
|
{line.description && <p className="text-xs text-gray-500">{line.description}</p>}
|
|
</div>
|
|
<span className="text-sm font-bold">{formatPrice(line.amount)} {t.common.currencyShort}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<h3 className="text-sm font-semibold text-gray-900 mb-2">{inv.transactions}</h3>
|
|
{(selectedInvoice.transactions || []).length === 0 ? (
|
|
<p className="text-sm text-gray-400">{inv.noTransactions}</p>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{(selectedInvoice.transactions || []).map((tx) => (
|
|
<div key={tx.id} className="border border-gray-100 rounded-xl p-3">
|
|
<div className="flex justify-between gap-3">
|
|
<span className="text-sm text-gray-700">{tx.description || tx.type}</span>
|
|
<span className="text-sm font-bold">{formatPrice(tx.amount)} {t.common.currencyShort}</span>
|
|
</div>
|
|
<p className="text-xs text-gray-400 mt-1">{tx.type} · {formatDate(tx.createdAt)}</p>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border-t border-gray-100 pt-4 space-y-3">
|
|
<h3 className="text-sm font-semibold text-gray-900">{inv.manualStatusChange}</h3>
|
|
<textarea
|
|
value={statusReason}
|
|
onChange={(e) => setStatusReason(e.target.value)}
|
|
className="input-field w-full min-h-[80px]"
|
|
placeholder={inv.reasonPlaceholder}
|
|
/>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => handleStatusUpdate('failed')}
|
|
disabled={updateStatusMutation.isPending}
|
|
className="btn-secondary text-red-600 flex items-center justify-center gap-2 disabled:opacity-50"
|
|
>
|
|
<XCircle className="w-4 h-4" /> {inv.failedBtn}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleStatusUpdate('void')}
|
|
disabled={updateStatusMutation.isPending}
|
|
className="btn-secondary disabled:opacity-50"
|
|
>
|
|
{inv.voidBtn}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|