ifixkart-admin/app/(admin)/razorpay-dashboard/page.tsx

325 lines
14 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
CheckCircle2,
Clock,
AlertTriangle,
ArrowDownToLine,
Search,
RefreshCw,
IndianRupee,
Loader2,
} from 'lucide-react';
import { apiFetch } from '@/services/api/client';
import { API_ENDPOINTS } from '@/services/api/config';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { CustomSelect } from '@/components/ui/CustomSelect';
interface RazorpayMetrics {
status: string;
gateway: string;
key_id: string;
environment: string;
total_net_ingested: number;
status_summary: {
CAPTURED: { count: number; amount: number };
PENDING: { count: number; amount: number };
FAILED: { count: number; amount: number };
REFUNDED: { count: number; amount: number };
};
provider_breakdown: Array<{
provider: string;
count: number;
amount: number;
}>;
is_enabled: boolean;
}
interface PaymentTransaction {
payment_id: string;
order_id: string;
order_no?: string;
amount: number;
currency: string;
provider: string;
status: string;
transaction_ref?: string;
razorpay_order_id?: string;
created_at: string;
}
function inr(amount: number) {
return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
function createdLabel(value?: string) {
if (!value) return '—';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '—';
return format(date, 'dd-MMM-yyyy HH:mm');
}
function statusClass(status: string) {
const normalized = status.toUpperCase();
if (normalized === 'CAPTURED' || normalized === 'PAID') return 'bg-success/15 text-success';
if (normalized === 'PENDING') return 'bg-warning/15 text-warning';
if (normalized === 'FAILED' || normalized === 'REFUNDED') return 'bg-destructive/10 text-destructive';
return 'bg-muted text-muted-foreground';
}
export default function RazorpayDashboardPage() {
const [metrics, setMetrics] = useState<RazorpayMetrics | null>(null);
const [transactions, setTransactions] = useState<PaymentTransaction[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [searchQuery, setSearchQuery] = useState<string>('');
const [statusFilter, setStatusFilter] = useState<string>('ALL');
const fetchData = async () => {
try {
setLoading(true);
const [metricsRes, txRes] = await Promise.all([
apiFetch<RazorpayMetrics>(API_ENDPOINTS.PAYMENTS_DASHBOARD_METRICS),
apiFetch<{ status: string; total: number; data?: PaymentTransaction[]; transactions?: PaymentTransaction[] }>(
`${API_ENDPOINTS.PAYMENTS_TRANSACTIONS_LEDGER}?limit=100`
),
]);
if (metricsRes) setMetrics(metricsRes);
const list = txRes?.data || txRes?.transactions || [];
setTransactions(list);
} catch (err: unknown) {
console.error('Failed to load Razorpay dashboard data:', err);
toast.error('Failed to fetch payment ledger data');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
const exportCsv = () => {
if (!transactions.length) {
toast.error('No transactions available to export');
return;
}
const headers = ['Transaction Ref', 'Order Number', 'Amount (INR)', 'Currency', 'Provider', 'Status', 'Gateway Order ID', 'Date'];
const rows = filteredTransactions.map(t => [
t.transaction_ref || t.payment_id,
t.order_no || t.order_id,
t.amount.toFixed(2),
t.currency,
t.provider,
t.status,
t.razorpay_order_id || 'N/A',
new Date(t.created_at).toISOString()
]);
const csvContent = [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `ifixkart_razorpay_ledger_${Date.now()}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success('Transactions ledger CSV exported successfully');
};
const filteredTransactions = transactions.filter(t => {
const q = searchQuery.toLowerCase();
const matchQuery =
(t.transaction_ref || '').toLowerCase().includes(q) ||
(t.payment_id || '').toLowerCase().includes(q) ||
(t.order_no || '').toLowerCase().includes(q) ||
(t.order_id || '').toLowerCase().includes(q) ||
(t.razorpay_order_id || '').toLowerCase().includes(q);
const matchStatus = statusFilter === 'ALL' || t.status.toUpperCase() === statusFilter.toUpperCase();
return matchQuery && matchStatus;
});
const dataCardShell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const primaryButton =
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
const secondaryButton =
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
const captured = metrics?.status_summary?.CAPTURED;
const pending = metrics?.status_summary?.PENDING;
const failed = metrics?.status_summary?.FAILED;
const refunded = metrics?.status_summary?.REFUNDED;
const failedCount = (failed?.count ?? 0) + (refunded?.count ?? 0);
return (
<div className="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Razorpay</h1>
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
{filteredTransactions.length}
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<button type="button" onClick={fetchData} disabled={loading} className={secondaryButton}>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
Refresh
</button>
<button type="button" onClick={exportCsv} className={primaryButton}>
<ArrowDownToLine className="w-3.5 h-3.5" />
Export CSV
</button>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Net captured</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight truncate">
{loading ? '—' : inr(metrics?.total_net_ingested ?? 0)}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<IndianRupee className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Captured</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{loading ? '—' : captured?.count ?? 0}</p>
<p className="text-[12px] text-muted-foreground mt-2">{loading ? '—' : inr(captured?.amount ?? 0)}</p>
</div>
<span className="w-9 h-9 rounded-full bg-success/10 text-success flex items-center justify-center shrink-0">
<CheckCircle2 className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Pending</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{loading ? '—' : pending?.count ?? 0}</p>
<p className="text-[12px] text-muted-foreground mt-2">{loading ? '—' : inr(pending?.amount ?? 0)}</p>
</div>
<span className="w-9 h-9 rounded-full bg-warning/10 text-warning flex items-center justify-center shrink-0">
<Clock className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Failed and refunded</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">{loading ? '—' : failedCount}</p>
<p className="text-[12px] text-muted-foreground mt-2">
{loading ? '—' : `${failed?.count ?? 0} failed · ${refunded?.count ?? 0} refunded`}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-destructive/10 text-destructive flex items-center justify-center shrink-0">
<AlertTriangle className="w-4 h-4" />
</span>
</div>
</div>
</div>
<div className={dataCardShell}>
<div className="p-4 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-2.5">
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 min-w-0">
<div className="relative w-full sm:w-[240px]">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search"
className="w-full h-9 pl-8 pr-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary"
/>
</div>
<div className="w-full sm:w-[180px]">
<CustomSelect
value={statusFilter}
onChange={setStatusFilter}
aria-label="Status"
options={[
{ value: 'ALL', label: 'All statuses' },
{ value: 'CAPTURED', label: 'Captured' },
{ value: 'PENDING', label: 'Pending' },
{ value: 'FAILED', label: 'Failed' },
]}
/>
</div>
</div>
</div>
{loading ? (
<div className="py-16 flex justify-center border-t border-border">
<Loader2 className="w-6 h-6 animate-spin text-primary" />
</div>
) : (
<div className="overflow-x-auto border-t border-border">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Transaction</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Order</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Amount</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Provider</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Date</th>
</tr>
</thead>
<tbody>
{filteredTransactions.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">
{searchQuery || statusFilter !== 'ALL' ? 'No payments match your search' : 'No payments yet'}
</td>
</tr>
) : filteredTransactions.map((tx) => (
<tr key={tx.payment_id} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5">
<div className="text-[13px] font-semibold text-foreground">
{tx.transaction_ref && tx.transaction_ref !== 'N/A' ? tx.transaction_ref : tx.payment_id}
</div>
{tx.razorpay_order_id && tx.razorpay_order_id !== 'N/A' && (
<div className="text-[11px] text-muted-foreground">{tx.razorpay_order_id}</div>
)}
</td>
<td className="px-4 py-2.5">
<div className="text-[13px] font-semibold text-foreground">
{tx.order_no && tx.order_no !== 'N/A' ? tx.order_no : tx.order_id.slice(0, 16)}
</div>
<div className="text-[11px] text-muted-foreground">{tx.order_id}</div>
</td>
<td className="px-4 py-2.5 text-right text-[13px] font-semibold text-foreground">
{inr(tx.amount)}
</td>
<td className="px-4 py-2.5">
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge bg-muted text-foreground text-[11px] font-semibold">
{tx.provider}
</span>
</td>
<td className="px-4 py-2.5">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${statusClass(tx.status)}`}>
{tx.status}
</span>
</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{createdLabel(tx.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}