Add invoice payment management.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
keyhan
2026-05-18 21:34:47 +03:30
parent 880521c576
commit 8b197e69bc
15 changed files with 1616 additions and 58 deletions
@@ -0,0 +1,269 @@
'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { FileText, Search, User, Wallet, CreditCard, XCircle } from 'lucide-react';
import { toast } from 'react-toastify';
import api from '@/lib/api';
import type { Invoice, InvoiceStatus, PaymentMethod } from '@/types';
const statusLabels: Record<InvoiceStatus, string> = {
draft: 'Draft',
issued: 'Unpaid',
partially_paid: 'Partially paid',
paid: 'Paid',
void: 'Void',
failed: 'Failed',
};
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 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: () => {
toast.success('Invoice status updated');
setStatusReason('');
queryClient.invalidateQueries({ queryKey: ['admin-invoices'] });
queryClient.invalidateQueries({ queryKey: ['admin-invoice', selectedId] });
},
onError: (err: any) => toast.error(err.response?.data?.message || 'Failed to update invoice status'),
});
const formatPrice = (amount: number) => Number(amount || 0).toLocaleString('en-US');
const formatDate = (value?: string) => value ? new Date(value).toLocaleString('en-US') : '-';
const handleStatusUpdate = (nextStatus: InvoiceStatus) => {
if (!selectedInvoice) return;
if (!statusReason.trim()) {
toast.error('Reason is required for manual status changes');
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" /> Invoice Management
</h1>
<p className="page-subtitle">Track all user invoices, payments, gateway refs, and wallet transactions.</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 top-1/2 -translate-y-1/2" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search invoice, email, or application"
className="input-field pl-9 w-full"
/>
</div>
<select value={status} onChange={(e) => setStatus(e.target.value as any)} className="input-field">
<option value="all">All statuses</option>
{Object.entries(statusLabels).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value as any)} className="input-field">
<option value="all">All methods</option>
<option value="wallet">Wallet</option>
<option value="gateway">Gateway</option>
<option value="mixed">Mixed</option>
</select>
</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 text-xs font-semibold text-gray-500 uppercase">Invoice</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">User</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Status</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Method</th>
<th className="px-4 py-3 text-right text-xs font-semibold text-gray-500 uppercase">Due</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">Loading...</td></tr>
) : invoices.length === 0 ? (
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400">No invoices found</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]}>{statusLabels[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">
<p className="text-sm font-bold text-gray-900">{formatPrice(invoice.dueAmount)} T</p>
<p className="text-xs text-gray-400">Total {formatPrice(invoice.total)} T</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" />
Select an invoice
</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>
<span className={statusClasses[selectedInvoice.status]}>{statusLabels[selectedInvoice.status]}</span>
</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">Total</p>
<p className="font-bold text-gray-900">{formatPrice(selectedInvoice.total)} T</p>
</div>
<div className="bg-gray-50 rounded-xl p-3">
<p className="text-xs text-gray-500">Due</p>
<p className="font-bold text-primary-700">{formatPrice(selectedInvoice.dueAmount)} T</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" />
Tracking: {selectedInvoice.gatewayTrackingCode || '-'}
</div>
<div className="flex items-center gap-2 text-gray-700">
<Wallet className="w-4 h-4 text-gray-400" />
Method: {selectedInvoice.paymentMethod || '-'}
</div>
</div>
<div>
<h3 className="text-sm font-semibold text-gray-900 mb-2">Line items</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</span>
</div>
))}
</div>
</div>
<div>
<h3 className="text-sm font-semibold text-gray-900 mb-2">Transactions</h3>
{(selectedInvoice.transactions || []).length === 0 ? (
<p className="text-sm text-gray-400">No linked transactions yet</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</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">Manual status change</h3>
<textarea
value={statusReason}
onChange={(e) => setStatusReason(e.target.value)}
className="input-field w-full min-h-[80px]"
placeholder="Reason is required for audit visibility"
/>
<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" /> Failed
</button>
<button
type="button"
onClick={() => handleStatusUpdate('void')}
disabled={updateStatusMutation.isPending}
className="btn-secondary disabled:opacity-50"
>
Void
</button>
</div>
</div>
</div>
)}
</div>
</div>
</div>
);
}