f8ee1ca168
Move both invoice views onto a shared invoices dictionary — statuses, filters, payment/line-item/transaction labels, manual status controls and toasts — with locale-aware Link, dates and RTL-aware table/search layout. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
295 lines
14 KiB
TypeScript
295 lines
14 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { useSearchParams } from 'next/navigation';
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { CreditCard, FileText, Wallet, XCircle, CheckCircle, Clock, Download } from 'lucide-react';
|
|
import { toast } from 'react-toastify';
|
|
import api from '@/lib/api';
|
|
import { useT, useLocale } from '@/i18n/I18nProvider';
|
|
import type { Invoice, InvoiceStatus } from '@/types';
|
|
|
|
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 InvoicesPage() {
|
|
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 searchParams = useSearchParams();
|
|
const [statusFilter, setStatusFilter] = useState<'all' | 'unpaid' | InvoiceStatus>('all');
|
|
const [selectedId, setSelectedId] = useState<string | null>(searchParams.get('invoice'));
|
|
|
|
useEffect(() => {
|
|
const invoiceId = searchParams.get('invoice');
|
|
if (invoiceId) setSelectedId(invoiceId);
|
|
}, [searchParams]);
|
|
|
|
const { data: walletData } = useQuery<{ balance: number }>({
|
|
queryKey: ['wallet-balance'],
|
|
queryFn: () => api.get('/billing/wallet').then((r) => r.data),
|
|
});
|
|
|
|
const { data: invoices = [], isLoading } = useQuery<Invoice[]>({
|
|
queryKey: ['invoices', statusFilter],
|
|
queryFn: () => {
|
|
const params: Record<string, string> = {};
|
|
if (statusFilter !== 'all' && statusFilter !== 'unpaid') params.status = statusFilter;
|
|
return api.get('/billing/invoices', { params }).then((r) => r.data);
|
|
},
|
|
});
|
|
|
|
const visibleInvoices = invoices.filter((invoice) => {
|
|
if (statusFilter === 'unpaid') return invoice.status === 'issued' || invoice.status === 'partially_paid';
|
|
return true;
|
|
});
|
|
|
|
const { data: selectedInvoice } = useQuery<Invoice>({
|
|
queryKey: ['invoice', selectedId],
|
|
queryFn: () => api.get(`/billing/invoices/${selectedId}`).then((r) => r.data),
|
|
enabled: !!selectedId,
|
|
});
|
|
|
|
const refresh = () => {
|
|
queryClient.invalidateQueries({ queryKey: ['invoices'] });
|
|
queryClient.invalidateQueries({ queryKey: ['invoice', selectedId] });
|
|
queryClient.invalidateQueries({ queryKey: ['wallet-balance'] });
|
|
queryClient.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
|
};
|
|
|
|
const verifyGatewayMutation = useMutation({
|
|
mutationFn: ({ invoiceId, trackingCode, amount }: { invoiceId: string; trackingCode: string; amount: number }) =>
|
|
api.post(`/billing/invoices/${invoiceId}/gateway/verify`, { trackingCode, amount }).then((r) => r.data),
|
|
onSuccess: (data) => {
|
|
toast.success(data.effect ? inv.paymentCompleteUpdated : inv.paymentComplete);
|
|
refresh();
|
|
window.history.replaceState({}, '', window.location.pathname);
|
|
},
|
|
onError: (err: any) => toast.error(err.response?.data?.message || inv.gatewayFailed),
|
|
});
|
|
|
|
useEffect(() => {
|
|
const invoiceId = searchParams.get('invoiceId');
|
|
const trackingCode = searchParams.get('trackingCode');
|
|
const amount = Number(searchParams.get('amount') || 0);
|
|
const status = searchParams.get('status');
|
|
if (invoiceId && trackingCode && amount > 0 && status === 'success' && !verifyGatewayMutation.isPending) {
|
|
setSelectedId(invoiceId);
|
|
verifyGatewayMutation.mutate({ invoiceId, trackingCode, amount });
|
|
}
|
|
}, [searchParams, verifyGatewayMutation]);
|
|
|
|
const payMutation = useMutation({
|
|
mutationFn: async (invoiceId: string) => {
|
|
const callbackUrl = `${window.location.origin}/dashboard/invoices`;
|
|
const { data } = await api.post(`/billing/invoices/${invoiceId}/pay/mixed`, { callbackUrl });
|
|
if (data.gatewayUrl && data.gatewayAmount > 0) {
|
|
window.location.href = data.gatewayUrl;
|
|
return data;
|
|
}
|
|
return data;
|
|
},
|
|
onSuccess: (data) => {
|
|
if (data.gatewayUrl && data.gatewayAmount > 0) return;
|
|
toast.success(data.effect ? inv.invoicePaidUpdated : inv.invoicePaid);
|
|
refresh();
|
|
},
|
|
onError: (err: any) => toast.error(err.response?.data?.message || inv.paymentFailed),
|
|
});
|
|
|
|
const downloadPdfMutation = useMutation({
|
|
mutationFn: async (invoice: Invoice) => {
|
|
const { data } = await api.get(`/billing/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: () => toast.error(inv.downloadFailed),
|
|
});
|
|
|
|
const formatPrice = (amount: number) => Number(amount || 0).toLocaleString('en-US');
|
|
const formatDate = (value?: string) => value ? new Date(value).toLocaleString(locale) : '-';
|
|
const dueAmount = Number(selectedInvoice?.dueAmount || 0);
|
|
const walletBalance = Number(walletData?.balance || 0);
|
|
const isPayable = selectedInvoice?.status === 'issued' || selectedInvoice?.status === 'partially_paid';
|
|
|
|
return (
|
|
<div className="max-w-6xl mx-auto space-y-6 animate-fade-in">
|
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
|
<div>
|
|
<h1 className="page-title flex items-center gap-2">
|
|
<FileText className="w-6 h-6" /> {inv.title}
|
|
</h1>
|
|
<p className="page-subtitle">{inv.subtitle}</p>
|
|
</div>
|
|
<div className="card py-3 px-4 flex items-center gap-3">
|
|
<Wallet className="w-5 h-5 text-primary-600" />
|
|
<div>
|
|
<p className="text-xs text-gray-500">{inv.walletBalance}</p>
|
|
<p className="font-bold text-gray-900">{formatPrice(walletBalance)} {inv.toman}</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-2">
|
|
{(['all', 'unpaid', 'paid', 'failed', 'void'] as const).map((status) => (
|
|
<button
|
|
key={status}
|
|
type="button"
|
|
onClick={() => setStatusFilter(status)}
|
|
className={`px-3 py-1.5 rounded-lg text-sm font-medium border ${
|
|
statusFilter === status
|
|
? 'bg-primary-600 text-white border-primary-600'
|
|
: 'bg-white text-gray-700 border-gray-200 hover:bg-gray-50'
|
|
}`}
|
|
>
|
|
{status === 'all' ? inv.filterAll : status === 'unpaid' ? inv.filterUnpaid : statusLabel(status)}
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
|
|
<div className="lg:col-span-3 card p-0 overflow-hidden">
|
|
{isLoading ? (
|
|
<div className="p-8 text-center text-gray-400">{inv.loadingInvoices}</div>
|
|
) : visibleInvoices.length === 0 ? (
|
|
<div className="p-8 text-center text-gray-400">{inv.noInvoices}</div>
|
|
) : (
|
|
<div className="divide-y divide-gray-100">
|
|
{visibleInvoices.map((invoice) => (
|
|
<button
|
|
key={invoice.id}
|
|
type="button"
|
|
onClick={() => setSelectedId(invoice.id)}
|
|
className={`w-full text-left rtl:text-right p-4 hover:bg-gray-50 transition-colors ${
|
|
selectedId === invoice.id ? 'bg-primary-50' : 'bg-white'
|
|
}`}
|
|
>
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div>
|
|
<p className="font-semibold text-gray-900">{invoice.invoiceNumber}</p>
|
|
<p className="text-sm text-gray-500">
|
|
{invoice.application?.name || invoice.reason} · {formatDate(invoice.createdAt)}
|
|
</p>
|
|
</div>
|
|
<span className={statusClasses[invoice.status]}>{statusLabel(invoice.status)}</span>
|
|
</div>
|
|
<div className="mt-3 flex items-center justify-between text-sm">
|
|
<span className="text-gray-500">{inv.total} {formatPrice(invoice.total)} {inv.toman}</span>
|
|
<span className="font-semibold text-gray-900">{inv.due} {formatPrice(invoice.dueAmount)} {inv.toman}</span>
|
|
</div>
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="lg:col-span-2 card">
|
|
{!selectedInvoice ? (
|
|
<div className="text-center py-12 text-gray-400">
|
|
<FileText className="w-10 h-10 mx-auto mb-3" />
|
|
{inv.selectInvoice}
|
|
</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="bg-gray-50 rounded-xl p-4 space-y-2 text-sm">
|
|
<div className="flex justify-between"><span className="text-gray-500">{inv.total}</span><span className="font-semibold">{formatPrice(selectedInvoice.total)} {inv.toman}</span></div>
|
|
<div className="flex justify-between"><span className="text-gray-500">{inv.paidLabel}</span><span className="font-semibold text-green-600">{formatPrice(selectedInvoice.paidAmount)} {inv.toman}</span></div>
|
|
<div className="flex justify-between"><span className="text-gray-500">{inv.due}</span><span className="font-semibold text-primary-700">{formatPrice(selectedInvoice.dueAmount)} {inv.toman}</span></div>
|
|
<div className="flex justify-between"><span className="text-gray-500">{inv.method}</span><span>{selectedInvoice.paymentMethod || '-'}</span></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">
|
|
<div className="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 text-gray-900">{formatPrice(line.amount)} {t.common.currencyShort}</span>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{isPayable && (
|
|
<div className="space-y-3 border-t border-gray-100 pt-4">
|
|
<h3 className="text-sm font-semibold text-gray-900">{inv.payment}</h3>
|
|
{walletBalance < dueAmount && (
|
|
<p className="text-xs text-amber-700 bg-amber-50 border border-amber-100 rounded-lg p-2">
|
|
{inv.walletCoversNote
|
|
.replace('{wallet}', formatPrice(walletBalance))
|
|
.replace('{rest}', formatPrice(dueAmount - walletBalance))}
|
|
</p>
|
|
)}
|
|
<button
|
|
type="button"
|
|
onClick={() => payMutation.mutate(selectedInvoice.id)}
|
|
disabled={payMutation.isPending || verifyGatewayMutation.isPending}
|
|
className="w-full btn-primary flex items-center justify-center gap-2 disabled:opacity-50"
|
|
>
|
|
<CreditCard className="w-4 h-4" />
|
|
{payMutation.isPending || verifyGatewayMutation.isPending ? inv.processing : inv.pay}
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
{selectedInvoice.status === 'paid' && (
|
|
<div className="flex items-center gap-2 text-sm text-green-700 bg-green-50 border border-green-100 rounded-xl p-3">
|
|
<CheckCircle className="w-4 h-4" /> {inv.paidOn.replace('{date}', formatDate(selectedInvoice.paidAt))}
|
|
</div>
|
|
)}
|
|
{selectedInvoice.status === 'failed' && (
|
|
<div className="flex items-center gap-2 text-sm text-red-700 bg-red-50 border border-red-100 rounded-xl p-3">
|
|
<XCircle className="w-4 h-4" /> {selectedInvoice.statusReason || inv.paymentFailed}
|
|
</div>
|
|
)}
|
|
{selectedInvoice.status === 'partially_paid' && (
|
|
<div className="flex items-center gap-2 text-sm text-blue-700 bg-blue-50 border border-blue-100 rounded-xl p-3">
|
|
<Clock className="w-4 h-4" /> {inv.waitingRemaining}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|