Add invoice PDF download and unified payment.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { FileText, Search, User, Wallet, CreditCard, XCircle } from 'lucide-react';
|
||||
import { FileText, Search, User, Wallet, CreditCard, XCircle, Download } from 'lucide-react';
|
||||
import { toast } from 'react-toastify';
|
||||
import api from '@/lib/api';
|
||||
import type { Invoice, InvoiceStatus, PaymentMethod } from '@/types';
|
||||
@@ -62,6 +62,21 @@ export default function AdminInvoicesPage() {
|
||||
onError: (err: any) => toast.error(err.response?.data?.message || 'Failed to update invoice status'),
|
||||
});
|
||||
|
||||
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: () => toast.error('Failed to download invoice PDF'),
|
||||
});
|
||||
|
||||
const formatPrice = (amount: number) => Number(amount || 0).toLocaleString('en-US');
|
||||
const formatDate = (value?: string) => value ? new Date(value).toLocaleString('en-US') : '-';
|
||||
|
||||
@@ -170,7 +185,18 @@ export default function AdminInvoicesPage() {
|
||||
<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 className="flex flex-col items-end gap-2">
|
||||
<span className={statusClasses[selectedInvoice.status]}>{statusLabels[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" />
|
||||
Download PDF
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
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, ExternalLink } from 'lucide-react';
|
||||
import { CreditCard, FileText, Wallet, XCircle, CheckCircle, Clock, Download } from 'lucide-react';
|
||||
import { toast } from 'react-toastify';
|
||||
import api from '@/lib/api';
|
||||
import type { Invoice, InvoiceStatus } from '@/types';
|
||||
@@ -69,39 +69,61 @@ export default function InvoicesPage() {
|
||||
queryClient.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
};
|
||||
|
||||
const walletPayMutation = useMutation({
|
||||
mutationFn: (invoiceId: string) => api.post(`/billing/invoices/${invoiceId}/pay/wallet`).then((r) => r.data),
|
||||
onSuccess: (data) => {
|
||||
toast.success(data.effect ? 'Invoice paid and service updated' : 'Invoice paid');
|
||||
refresh();
|
||||
},
|
||||
onError: (err: any) => toast.error(err.response?.data?.message || 'Wallet payment failed'),
|
||||
});
|
||||
|
||||
const gatewayPayMutation = useMutation({
|
||||
mutationFn: async ({ invoiceId, mixed }: { invoiceId: string; mixed: boolean }) => {
|
||||
const callbackUrl = `${window.location.origin}/dashboard/invoices`;
|
||||
const { data } = await api.post(
|
||||
`/billing/invoices/${invoiceId}/pay/${mixed ? 'mixed' : 'gateway'}`,
|
||||
{ callbackUrl },
|
||||
);
|
||||
if (data.gatewayAmount === 0) return data;
|
||||
const amount = data.gatewayAmount ?? data.amount;
|
||||
const trackingCode = data.trackingCode;
|
||||
if (!trackingCode || !amount) return data;
|
||||
const verified = await api.post(`/billing/invoices/${invoiceId}/gateway/verify`, {
|
||||
trackingCode,
|
||||
amount,
|
||||
});
|
||||
return verified.data;
|
||||
},
|
||||
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 ? 'Payment complete and service updated' : 'Payment complete');
|
||||
refresh();
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
},
|
||||
onError: (err: any) => toast.error(err.response?.data?.message || 'Gateway payment failed'),
|
||||
});
|
||||
|
||||
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 ? 'Invoice paid and service updated' : 'Invoice paid');
|
||||
refresh();
|
||||
},
|
||||
onError: (err: any) => toast.error(err.response?.data?.message || 'Payment failed'),
|
||||
});
|
||||
|
||||
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('Failed to download invoice PDF'),
|
||||
});
|
||||
|
||||
const formatPrice = (amount: number) => Number(amount || 0).toLocaleString('en-US');
|
||||
const formatDate = (value?: string) => value ? new Date(value).toLocaleString('en-US') : '-';
|
||||
const dueAmount = Number(selectedInvoice?.dueAmount || 0);
|
||||
@@ -192,7 +214,18 @@ export default function InvoicesPage() {
|
||||
<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 className="flex flex-col items-end gap-2">
|
||||
<span className={statusClasses[selectedInvoice.status]}>{statusLabels[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" />
|
||||
Download PDF
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-xl p-4 space-y-2 text-sm">
|
||||
@@ -221,38 +254,20 @@ export default function InvoicesPage() {
|
||||
|
||||
{isPayable && (
|
||||
<div className="space-y-3 border-t border-gray-100 pt-4">
|
||||
<h3 className="text-sm font-semibold text-gray-900">Payment options</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => walletPayMutation.mutate(selectedInvoice.id)}
|
||||
disabled={walletPayMutation.isPending || walletBalance < dueAmount}
|
||||
className="w-full btn-primary flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
<Wallet className="w-4 h-4" />
|
||||
Pay from wallet
|
||||
</button>
|
||||
<h3 className="text-sm font-semibold text-gray-900">Payment</h3>
|
||||
{walletBalance < dueAmount && (
|
||||
<p className="text-xs text-amber-700 bg-amber-50 border border-amber-100 rounded-lg p-2">
|
||||
Wallet is short by {formatPrice(dueAmount - walletBalance)} Toman. Use mixed payment to cover the delta by gateway.
|
||||
Wallet balance covers {formatPrice(walletBalance)} Toman. The remaining {formatPrice(dueAmount - walletBalance)} Toman will be paid through the gateway.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => gatewayPayMutation.mutate({ invoiceId: selectedInvoice.id, mixed: false })}
|
||||
disabled={gatewayPayMutation.isPending}
|
||||
className="w-full btn-secondary flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
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" />
|
||||
Pay directly by gateway
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => gatewayPayMutation.mutate({ invoiceId: selectedInvoice.id, mixed: true })}
|
||||
disabled={gatewayPayMutation.isPending}
|
||||
className="w-full btn-secondary flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
Use wallet + gateway delta
|
||||
{payMutation.isPending || verifyGatewayMutation.isPending ? 'در حال پردازش...' : 'پرداخت'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user