acupedia-web-ui/src/components/payments/PaymentsTab.tsx

462 lines
20 KiB
TypeScript

import React, { useState, useMemo } from 'react';
import { Receipt, Download, Mail, RefreshCw, Search, ArrowUpDown, ArrowDown, ArrowUp, X, Calendar, ChevronDown } from 'lucide-react';
import { Pagination } from '../common/Pagination';
interface PaymentsTabProps {
payments: any[];
currentPage: number;
perPage: number;
downloadingId: string | null;
sharingId: string | null;
onPageChange: (p: number) => void;
onPerPageChange: (pp: number) => void;
onDownloadInvoice: (id: string) => void;
onShareInvoice: (id: string) => void;
}
const MONTH_OPTIONS = [
{ value: '01', label: 'January' },
{ value: '02', label: 'February' },
{ value: '03', label: 'March' },
{ value: '04', label: 'April' },
{ value: '05', label: 'May' },
{ value: '06', label: 'June' },
{ value: '07', label: 'July' },
{ value: '08', label: 'August' },
{ value: '09', label: 'September' },
{ value: '10', label: 'October' },
{ value: '11', label: 'November' },
{ value: '12', label: 'December' },
];
export const PaymentsTab: React.FC<PaymentsTabProps> = ({
payments,
currentPage,
perPage,
downloadingId,
sharingId,
onPageChange,
onPerPageChange,
onDownloadInvoice,
onShareInvoice,
}) => {
const [searchQuery, setSearchQuery] = useState('');
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
const [selectedYear, setSelectedYear] = useState<string>('all');
const [selectedMonth, setSelectedMonth] = useState<string>('all');
const [isCustomYear, setIsCustomYear] = useState<boolean>(false);
const [customYearInput, setCustomYearInput] = useState<string>('');
// Dynamically extract all available years from payments (with fallback to current year)
const availableYears = useMemo(() => {
const currentYear = new Date().getFullYear();
const yearsSet = new Set<number>([currentYear]);
for (const p of payments) {
if (!p?.created_at) continue;
const d = typeof p.created_at === 'number'
? new Date(p.created_at * 1000)
: new Date(p.created_at);
if (!isNaN(d.getTime())) {
yearsSet.add(d.getFullYear());
}
}
return Array.from(yearsSet).sort((a, b) => b - a);
}, [payments]);
// Filter and Sort payments
const processedPayments = useMemo(() => {
let result = [...payments];
// Filter by Year
if (selectedYear !== 'all') {
result = result.filter((p: any) => {
if (!p?.created_at) return false;
const d = typeof p.created_at === 'number'
? new Date(p.created_at * 1000)
: new Date(p.created_at);
if (isNaN(d.getTime())) return false;
return d.getFullYear().toString() === selectedYear;
});
}
// Filter by Month
if (selectedMonth !== 'all') {
result = result.filter((p: any) => {
if (!p?.created_at) return false;
const d = typeof p.created_at === 'number'
? new Date(p.created_at * 1000)
: new Date(p.created_at);
if (isNaN(d.getTime())) return false;
const m = String(d.getMonth() + 1).padStart(2, '0');
return m === selectedMonth;
});
}
// Filter by Search Query
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase().trim();
result = result.filter((p: any) => {
const id = (p.id || '').toLowerCase();
const email = (p.email || '').toLowerCase();
const orderId = (p.order_id || '').toLowerCase();
const contact = (p.contact || '').toLowerCase();
const method = (p.method || '').toLowerCase();
const invoiceNum = (p.invoice_number || '').toLowerCase();
const status = (p.status || '').toLowerCase();
return (
id.includes(q) ||
email.includes(q) ||
orderId.includes(q) ||
contact.includes(q) ||
method.includes(q) ||
invoiceNum.includes(q) ||
status.includes(q)
);
});
}
// Sort by created_at (default newest first)
result.sort((a: any, b: any) => {
const timeA = typeof a.created_at === 'number' ? a.created_at * 1000 : new Date(a.created_at || 0).getTime();
const timeB = typeof b.created_at === 'number' ? b.created_at * 1000 : new Date(b.created_at || 0).getTime();
return sortOrder === 'desc' ? timeB - timeA : timeA - timeB;
});
return result;
}, [payments, searchQuery, sortOrder, selectedYear, selectedMonth]);
const hasDateFilter = selectedYear !== 'all' || selectedMonth !== 'all';
const handleClearDateFilters = () => {
setSelectedYear('all');
setSelectedMonth('all');
setIsCustomYear(false);
setCustomYearInput('');
onPageChange(1);
};
const totalFiltered = processedPayments.length;
const totalPages = Math.max(1, Math.ceil(totalFiltered / perPage));
const safePage = Math.min(currentPage, totalPages);
const startIndex = (safePage - 1) * perPage;
const paginatedPayments = processedPayments.slice(startIndex, startIndex + perPage);
return (
<div className="space-y-4">
{/* Search & Sort Controls Header */}
<div className="bg-slate-50 border border-slate-200/80 rounded-2xl p-4 flex flex-col xl:flex-row justify-between items-stretch xl:items-center gap-3">
{/* Left Side: Search & Date Filters */}
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1">
{/* Search Input */}
<div className="flex-1 max-w-md relative">
<input
type="text"
placeholder="Search payment ID, order ID, email, method, invoice..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
onPageChange(1);
}}
className="w-full bg-white border border-slate-200 rounded-xl pl-9 pr-8 py-2 text-xs text-slate-800 font-semibold focus:outline-none focus:border-indigo-500 placeholder:text-slate-400 shadow-sm"
/>
<Search className="h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
{searchQuery && (
<button
onClick={() => {
setSearchQuery('');
onPageChange(1);
}}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5 cursor-pointer"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
{/* Date Filter Controls: Year & Month */}
<div className="flex items-center gap-2 shrink-0">
{/* Year Selector (Dynamic with Custom Year support) */}
{!isCustomYear ? (
<div className="relative">
<Calendar className="h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
<select
value={selectedYear}
onChange={(e) => {
const val = e.target.value;
if (val === 'custom') {
setIsCustomYear(true);
setCustomYearInput('');
} else {
setSelectedYear(val);
onPageChange(1);
}
}}
className="appearance-none bg-white border border-slate-200 rounded-xl pl-8.5 pr-8 py-2 text-xs font-bold text-slate-700 hover:border-slate-300 focus:outline-none focus:border-indigo-500 shadow-2xs cursor-pointer transition-colors"
title="Filter payments by year"
>
<option value="all">All Years</option>
{availableYears.map((yr) => (
<option key={yr} value={String(yr)}>
{yr}
</option>
))}
<option value="custom">Custom Year...</option>
</select>
<ChevronDown className="h-3.5 w-3.5 absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
</div>
) : (
<div className="relative flex items-center">
<Calendar className="h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-indigo-500 pointer-events-none" />
<input
type="text"
autoFocus
maxLength={4}
placeholder="Year (e.g. 2002)"
value={customYearInput}
onChange={(e) => {
const val = e.target.value.replace(/\D/g, '').slice(0, 4);
setCustomYearInput(val);
if (val.length === 4) {
setSelectedYear(val);
onPageChange(1);
} else {
setSelectedYear('all');
onPageChange(1);
}
}}
className="w-34 bg-white border border-indigo-400 rounded-xl pl-8.5 pr-7 py-2 text-xs font-bold text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-1 focus:ring-indigo-500 shadow-2xs transition-colors"
title="Enter any custom year"
/>
<button
type="button"
onClick={() => {
setIsCustomYear(false);
setCustomYearInput('');
setSelectedYear('all');
onPageChange(1);
}}
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5 cursor-pointer"
title="Back to year dropdown"
>
<X className="h-3 w-3" />
</button>
</div>
)}
{/* Month Selector */}
<div className="relative">
<select
value={selectedMonth}
onChange={(e) => {
setSelectedMonth(e.target.value);
onPageChange(1);
}}
className="appearance-none bg-white border border-slate-200 rounded-xl pl-3.5 pr-8 py-2 text-xs font-bold text-slate-700 hover:border-slate-300 focus:outline-none focus:border-indigo-500 shadow-2xs cursor-pointer transition-colors"
title="Filter payments by month"
>
<option value="all">All Months</option>
{MONTH_OPTIONS.map((m) => (
<option key={m.value} value={m.value}>
{m.label}
</option>
))}
</select>
<ChevronDown className="h-3.5 w-3.5 absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
</div>
{hasDateFilter && (
<button
type="button"
onClick={handleClearDateFilters}
className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-200/60 rounded-lg transition-colors cursor-pointer"
title="Reset year and month filters"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* Right Side: Sort & Count Controls */}
<div className="flex items-center gap-3 justify-between sm:justify-end shrink-0">
<button
type="button"
onClick={() => setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc')}
className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-bold bg-white border border-slate-200 text-slate-700 hover:bg-slate-100 hover:border-slate-300 transition-colors shadow-2xs cursor-pointer"
title={`Toggle sort order (current: ${sortOrder === 'desc' ? 'Latest first' : 'Oldest first'})`}
>
<ArrowUpDown className="h-3.5 w-3.5 text-indigo-600" />
<span>Sort: {sortOrder === 'desc' ? 'Newest First' : 'Oldest First'}</span>
{sortOrder === 'desc' ? (
<ArrowDown className="h-3 w-3 text-slate-400" />
) : (
<ArrowUp className="h-3 w-3 text-slate-400" />
)}
</button>
<div className="text-xs font-bold text-slate-500 whitespace-nowrap">
Showing <span className="text-slate-800">{totalFiltered}</span> of{' '}
<span className="text-slate-800">{payments.length}</span>
</div>
</div>
</div>
{payments.length === 0 ? (
<p className="text-sm text-slate-400 italic text-center py-10 font-semibold">
No payments captured on Razorpay gateway yet.
</p>
) : processedPayments.length === 0 ? (
<div className="border border-slate-200 rounded-2xl p-10 bg-white text-center space-y-2">
<p className="text-sm font-bold text-slate-700">No matching payments found</p>
<p className="text-xs text-slate-400">
No payments match your
{hasDateFilter && (
<span>
{' '}selected period (
<strong className="text-slate-600">
{selectedMonth !== 'all' ? MONTH_OPTIONS.find((m) => m.value === selectedMonth)?.label : ''}
{selectedMonth !== 'all' && selectedYear !== 'all' ? ' ' : ''}
{selectedYear !== 'all' ? selectedYear : ''}
</strong>
)
</span>
)}
{searchQuery ? ` and search query "${searchQuery}"` : ''}.
</p>
<button
onClick={() => {
setSearchQuery('');
handleClearDateFilters();
}}
className="text-xs text-indigo-600 font-bold hover:underline mt-2 inline-block cursor-pointer"
>
Reset all filters
</button>
</div>
) : (
<div className="border border-slate-200 rounded-2xl overflow-hidden shadow-xs p-4 bg-white">
<div className="overflow-x-auto">
<table className="w-full text-xs min-w-[760px]">
<thead>
<tr className="border-b border-slate-200 bg-slate-50/80 text-[10px] uppercase font-bold text-slate-400 tracking-wider">
<th className="text-left py-3 px-3">Payment ID</th>
<th className="text-left py-3 px-3">Date</th>
<th className="text-left py-3 px-3">Amount</th>
<th className="text-left py-3 px-3">Status</th>
<th className="text-left py-3 px-3">Method</th>
<th className="text-left py-3 px-3">Email</th>
<th className="text-left py-3 px-3">Order ID</th>
<th className="text-left py-3 px-3">Invoice</th>
<th className="text-center py-3 px-3">Actions</th>
</tr>
</thead>
<tbody>
{paginatedPayments.map((p: any, i: number) => {
const paymentDate = p.created_at
? typeof p.created_at === 'number'
? new Date(p.created_at * 1000).toLocaleDateString(undefined, { dateStyle: 'medium' })
: new Date(p.created_at).toLocaleDateString(undefined, { dateStyle: 'medium' })
: '—';
return (
<tr key={p.id || i} className="border-b border-slate-100 hover:bg-slate-50 transition-colors">
<td className="py-2.5 px-3 font-mono text-indigo-600 font-bold">{p.id}</td>
<td className="py-2.5 px-3 text-slate-500 whitespace-nowrap">{paymentDate}</td>
<td className="py-2.5 px-3 font-bold text-slate-800 whitespace-nowrap">
{p.currency === 'USD' ? '$' : p.currency === 'EUR' ? '€' : '₹'}
{p.amount ? (p.amount / 100).toFixed(2) : '—'}
</td>
<td className="py-2.5 px-3">
<span
className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${
p.status === 'captured'
? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
: p.status === 'authorized'
? 'bg-blue-50 text-blue-700 border border-blue-200'
: p.status === 'failed'
? 'bg-rose-50 text-rose-700 border border-rose-200'
: 'bg-slate-100 text-slate-600 border border-slate-200'
}`}
>
{p.status}
</span>
</td>
<td className="py-2.5 px-3 text-slate-600 capitalize">{p.method || '—'}</td>
<td className="py-2.5 px-3 text-slate-600 truncate max-w-[160px]">{p.email || '—'}</td>
<td className="py-2.5 px-3 font-mono text-slate-500 text-[10px]">{p.order_id || '—'}</td>
<td className="py-2.5 px-3">
{p.invoice_number ? (
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] font-black font-mono shadow-xs ${
p.invoice_number.startsWith('inv_')
? 'bg-indigo-50/70 border border-indigo-200 text-indigo-700'
: 'bg-amber-50/70 border border-amber-200 text-amber-700'
}`}
>
<Receipt
className={`h-3 w-3 ${
p.invoice_number.startsWith('inv_') ? 'text-indigo-500' : 'text-amber-500'
}`}
/>
{p.invoice_number}
</span>
) : (
<span className="text-slate-300 italic text-[10px]">Not generated</span>
)}
</td>
<td className="py-2.5 px-3">
{p.status === 'captured' && (
<div className="flex items-center justify-center gap-1.5">
<button
type="button"
onClick={() => onDownloadInvoice(p.id)}
disabled={downloadingId === p.id}
className="h-7 w-7 flex items-center justify-center bg-indigo-50 hover:bg-indigo-100 disabled:bg-slate-100 disabled:text-slate-400 border border-indigo-200 text-indigo-700 rounded-lg cursor-pointer transition-colors shadow-xs"
title="Download Invoice PDF"
>
{downloadingId === p.id ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
</button>
<button
type="button"
onClick={() => onShareInvoice(p.id)}
disabled={sharingId === p.id}
className="h-7 w-7 flex items-center justify-center bg-slate-900 hover:bg-slate-800 disabled:bg-slate-100 disabled:text-slate-400 border border-slate-800 text-white rounded-lg cursor-pointer transition-colors shadow-xs"
title="Share Invoice via Email"
>
{sharingId === p.id ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin text-indigo-400" />
) : (
<Mail className="h-3.5 w-3.5 text-indigo-400" />
)}
</button>
</div>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<Pagination
currentPage={safePage}
totalItems={totalFiltered}
itemsPerPage={perPage}
onPageChange={onPageChange}
onItemsPerPageChange={onPerPageChange}
/>
</div>
)}
</div>
);
};