import { Activity, CheckCircle2, Clock, Copy, CreditCard, DollarSign, Eye, Printer, Receipt, RotateCcw, Search, ShieldCheck, TrendingUp, Undo2, Wallet, XCircle, } from 'lucide-react'; import { useCallback,useEffect,useState } from 'react'; import { toast } from 'react-hot-toast'; import TransactionReceiptModal,{ type TransactionReceiptData } from '../components/TransactionReceiptModal'; import Badge from '../components/ui/Badge'; import Button from '../components/ui/Button'; import Modal from '../components/ui/Modal'; import Pagination from '../components/ui/Pagination'; import Spinner from '../components/ui/Spinner'; import ThSort from '../components/ui/ThSort'; import api from '../services/api'; import { useTableParams } from '../utils/useTableParams'; interface Transaction { id: string; userId: string; orderId?: string | null; amount: number | string; amountRials?: string | number | null; gateway: string; trackId?: string | null; refNumber?: string | null; cardNumber?: string | null; status: string; resultCode?: number | null; message?: string | null; description?: string | null; type: string; ipAddress?: string | null; userAgent?: string | null; rawRequest?: any; rawResponse?: any; paidAt?: string | null; createdAt: string; user?: { id: string; firstName: string; lastName: string; mobile: string; email?: string; } | null; order?: { orderNumber: string; id: string; trackingNumber?: string; totalAmount: number | string; status: string; paymentMethod?: string; } | null; } interface Stats { totalCount: number; verifiedCount: number; pendingCount: number; failedCount: number; totalVolume: number; todayVolume: number; successRate: number; } interface GatewayHealth { gatewayName: string; status: 'ONLINE' | 'DEGRADED' | 'OFFLINE'; latencyMs: number; merchantConfigured?: boolean; activeMerchant?: string; message?: string; checkedAt?: string; lastChecked?: string; } export default function Transactions() { const { searchParams, search, status: statusFilter, gateway: gatewayFilter, type: typeFilter, sortBy, sortOrder, page, setParam, setMultipleParams, handleSort, clearFilters, } = useTableParams({ defaultSortBy: 'createdAt', defaultSortOrder: 'desc', defaultPage: 1, defaultLimit: 15, }); const [transactions, setTransactions] = useState([]); const [stats, setStats] = useState(null); const [health, setHealth] = useState(null); const [healthLoading, setHealthLoading] = useState(false); const [isReconciling, setIsReconciling] = useState(false); const [isLoading, setIsLoading] = useState(true); const [totalPages, setTotalPages] = useState(1); const [totalCount, setTotalCount] = useState(0); // Details Modal const [selectedTx, setSelectedTx] = useState(null); const [liveInquiryLoading, setLiveInquiryLoading] = useState(false); const [liveInquiryData, setLiveInquiryData] = useState(null); const [, setShowRawLogs] = useState(false); // Receipt Modal State const [receiptModalOpen, setReceiptModalOpen] = useState(false); const [receiptData, setReceiptData] = useState(null); // Refund Modal State & Confirmation (Supports Wallet and Zibal Gateway) const [refundModalTx, setRefundModalTx] = useState(null); const [refundTarget, setRefundTarget] = useState<'wallet' | 'zibal'>('wallet'); const [refundAmount, setRefundAmount] = useState(''); const [refundReason, setRefundReason] = useState(''); const [tryReverse, setTryReverse] = useState(true); const [isSubmittingRefund, setIsSubmittingRefund] = useState(false); const openReceiptModal = (tx: Transaction) => { setMultipleParams({ modal: 'receipt', txId: tx.id }, false); setReceiptData({ trackId: tx.trackId || '-', refNumber: tx.refNumber || '-', amountTomans: tx.amount, amountRials: tx.amountRials || Number(tx.amount) * 10, statusText: tx.status === 'VERIFIED' ? 'پرداخت موفق' : tx.status === 'PENDING' ? 'در انتظار پرداخت' : 'ناموفق', orderNumber: tx.order?.orderNumber || (tx.orderId ? `سفارش ${tx.orderId.slice(0, 8)}` : '-'), orderId: tx.orderId || undefined, cardNumber: tx.cardNumber || '-', paidAt: tx.paidAt ? new Date(tx.paidAt).toLocaleDateString('fa-IR') : undefined, createdAt: new Date(tx.createdAt).toLocaleDateString('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', }), fee: 0, mobile: tx.user?.mobile || '-', description: tx.description || 'پرداخت سفارش آنلاین کنینا', psp: tx.gateway === 'zibal' ? 'زیبال / به‌پرداخت ملت' : tx.gateway, ip: tx.ipAddress || '-', }); setReceiptModalOpen(true); }; const closeReceiptModal = () => { setReceiptModalOpen(false); setReceiptData(null); setMultipleParams({ modal: null, txId: null }, false); }; const openDetailsModal = (tx: Transaction) => { setMultipleParams({ modal: 'details', txId: tx.id }, false); setSelectedTx(tx); setLiveInquiryData(null); setShowRawLogs(false); }; const closeDetailsModal = () => { setSelectedTx(null); setLiveInquiryData(null); setShowRawLogs(false); setMultipleParams({ modal: null, txId: null }, false); }; const handleCopy = (text: string, label: string) => { navigator.clipboard.writeText(text); toast.success(`${label} با موفقیت کپی شد`); }; const handleLiveInquiry = async (trackId: string) => { try { setLiveInquiryLoading(true); const res = await api.post('/payment/admin/inquiry', { trackId }); if (res.data) { setLiveInquiryData(res.data); toast.success('استعلام تراکنش با موفقیت دریافت شد'); } } catch (e: any) { toast.error(e?.response?.data?.message || 'خطا در دریافت استعلام تراکنش'); } finally { setLiveInquiryLoading(false); } }; const openRefundModal = (tx: Transaction) => { setMultipleParams({ modal: 'refund', txId: tx.id }, false); setRefundModalTx(tx); setRefundTarget(tx.type === 'WALLET_TOPUP' || !tx.trackId ? 'wallet' : 'wallet'); setRefundAmount(String(tx.amount || '')); setRefundReason(`استرداد تراکنش #${tx.trackId || tx.id.slice(0, 8)}`); setTryReverse(true); }; const closeRefundModal = () => { setRefundModalTx(null); setMultipleParams({ modal: null, txId: null }, false); }; const handleExecuteRefund = async () => { if (!refundModalTx) return; try { setIsSubmittingRefund(true); const parsedAmount = refundAmount ? Number(refundAmount) : Number(refundModalTx.amount); if (refundTarget === 'wallet') { const userId = refundModalTx.userId || refundModalTx.user?.id; if (!userId) { toast.error('کاربر مرتبط با این تراکنش یافت نشد'); return; } await api.post(`/admin/users/${userId}/wallet-adjust`, { amount: parsedAmount, type: 'refund', description: refundReason || `استرداد وجه تراکنش #${refundModalTx.trackId || refundModalTx.id.slice(0, 8)}`, }); toast.success('مبلغ با موفقیت به کیف پول کاربر عودت داده شد'); } else { if (!refundModalTx.trackId) { toast.error('شناسه تراکنش زیبال (Track ID) برای این پرداخت موجود نیست'); return; } const res = await api.post('/payment/admin/refund', { trackId: refundModalTx.trackId, amount: parsedAmount ? parsedAmount * 10 : undefined, // Rial tryReverse: tryReverse, cardNumber: refundModalTx.cardNumber || undefined, description: refundReason || undefined, }); if (res.data?.result === 1 || res.data?.status === 1 || res.data?.success) { toast.success(res.data?.message || 'درخواست استرداد وجه با موفقیت به زیبال ارسال شد.'); } else { toast.error(res.data?.message || 'خطا در استرداد آنلاین از زیبال'); } } setRefundModalTx(null); fetchTransactions(); fetchStats(); } catch (e: any) { toast.error(e?.response?.data?.message || 'خطا در انجام عملیات استرداد'); } finally { setIsSubmittingRefund(false); } }; const fetchStats = async () => { try { const res = await api.get('/payment/admin/stats'); if (res.data) { setStats(res.data); } } catch (e) { console.error('Failed to fetch stats', e); } }; const fetchHealth = async (silent = false) => { try { if (!silent) setHealthLoading(true); const res = await api.get('/payment/admin/health'); if (res.data) { setHealth(res.data); if (!silent) toast.success(`وضعیت درگاه زیبال: ${res.data.status} (${res.data.latencyMs}ms)`); } } catch (e) { console.error('Failed to fetch gateway health', e); if (!silent) toast.error('عدم دسترسی به سرویس Health Check درگاه'); } finally { if (!silent) setHealthLoading(false); } }; const fetchTransactions = useCallback(async () => { try { setIsLoading(true); const params = new URLSearchParams(); params.append('page', String(page)); params.append('limit', '15'); if (search) params.append('search', search); if (statusFilter) params.append('status', statusFilter); if (gatewayFilter) params.append('gateway', gatewayFilter); if (typeFilter) params.append('type', typeFilter); if (sortBy) params.append('sortBy', sortBy); if (sortOrder) params.append('sortOrder', sortOrder); const res = await api.get(`/payment/admin/transactions?${params.toString()}`); if (res.data) { const txList = res.data.transactions || res.data.data || []; setTransactions(txList); setTotalPages(res.data.totalPages || res.data.meta?.lastPage || 1); setTotalCount(res.data.totalCount || res.data.meta?.total || 0); // Auto-open modal if URL specifies modal and txId const modalType = searchParams.get('modal'); const txIdParam = searchParams.get('txId'); if (modalType && txIdParam) { const foundTx = txList.find((t: Transaction) => t.id === txIdParam); if (foundTx) { if (modalType === 'details') openDetailsModal(foundTx); else if (modalType === 'receipt') openReceiptModal(foundTx); else if (modalType === 'refund') openRefundModal(foundTx); } } } } catch (e) { console.error('Failed to fetch transactions', e); toast.error('خطا در دریافت لیست تراکنش‌ها'); } finally { setIsLoading(false); } }, [page, search, statusFilter, gatewayFilter, typeFilter, sortBy, sortOrder, searchParams]); useEffect(() => { fetchTransactions(); fetchStats(); fetchHealth(true); }, [fetchTransactions]); const handleReconcile = async () => { try { setIsReconciling(true); const res = await api.post('/payment/admin/reconcile'); toast.success( `انطباق انجام شد: ${res.data.verified} تایید شده، ${res.data.failed} ناموفق`, ); fetchTransactions(); fetchStats(); } catch (e) { console.error('Reconcile error', e); toast.error('خطا در اجرای استعلام خودکار'); } finally { setIsReconciling(false); } }; const handleManualVerify = async (txId: string) => { if (!window.confirm('آیا از تایید دستی این تراکنش (افزایش موجودی کیف پول یا تایید سفارش) اطمینان دارید؟')) return; try { const res = await api.post(`/payment/admin/manual-verify/${txId}`, { adminNote: 'تایید دستی فیش واریزی توسط مدیر سیستم', }); toast.success(res.data?.message || 'تراکنش با موفقیت تایید شد'); fetchTransactions(); fetchStats(); if (selectedTx) setSelectedTx(null); } catch (e: any) { toast.error(e.response?.data?.message || 'خطا در تایید دستی تراکنش'); } }; const handleManualReject = async (txId: string) => { const reason = window.prompt('لطفاً دلیل رد تراکنش را وارد کنید:', 'فیش واریزی نامعتبر است'); if (reason === null) return; try { const res = await api.post(`/payment/admin/manual-reject/${txId}`, { reason }); toast.success(res.data?.message || 'تراکنش رد شد'); fetchTransactions(); fetchStats(); if (selectedTx) setSelectedTx(null); } catch (e: any) { toast.error(e.response?.data?.message || 'خطا در رد تراکنش'); } }; return (
{/* Header */}

لاگ‌ها و مدیریت تراکنش‌های مالی

رهگیری لحظه‌ای پرداخت‌های آنلاین زیبال، بررسی لاگ‌های خام و عیب‌یابی تراکنش‌ها

{/* Gateway Health Monitor Banner */} {health && (
{health.gatewayName} {health.status}
Latency: {health.latencyMs}ms • Updated: {health.checkedAt || health.lastChecked ? new Date((health.checkedAt || health.lastChecked) ?? '').toLocaleTimeString('fa-IR') : 'الان'}
)} {/* Summary Stat Cards - 2 cols on mobile (2 rows), 4 cols on desktop */} {stats && (

حجم کل تراکنش‌های موفق

{(Number(stats.totalVolume) || 0).toLocaleString('fa-IR')}{' '} تومان

پرداخت‌های موفق امروز

{(Number(stats.todayVolume) || 0).toLocaleString('fa-IR')}{' '} تومان

نرخ موفقیت پرداخت‌ها

٪{(Number(stats.successRate) || 0).toLocaleString('fa-IR')}

وضعیت تراکنش‌ها

✓ {stats.verifiedCount || 0} ⏳ {stats.pendingCount || 0} ✗ {stats.failedCount || 0}
)} {/* Filter and Search Bar */}
{/* Search Input */}
setParam('search', e.target.value)} placeholder="جستجو بر اساس نام، موبایل، Track ID، شماره مرجع..." className="w-full pl-3 pr-10 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500" />
{/* Status Filter */}
{/* Gateway Filter */}
{/* Type Filter */}
{/* Total records found */}
مجموع {totalCount.toLocaleString('fa-IR')} تراکنش ثبت شده
{/* Transactions Table */}
{isLoading ? (
) : transactions.length === 0 ? (
هیچ تراکنشی با فیلترهای مشخص شده یافت نشد.
) : (
{transactions.map((tx) => { const isVerified = tx.status === 'VERIFIED'; const isPending = tx.status === 'PENDING'; const isFailed = tx.status === 'FAILED'; return ( {/* User Info */} {/* Order / Type */} {/* Amount */} {/* Gateway */} {/* Tracking Numbers */} {/* Status */} {/* Date & Time */} {/* Actions */} ); })}
کاربر خریدار سفارش / نوع درگاه شناسه‌های پرداخت عملیات
{tx.user ? (

{tx.user.firstName} {tx.user.lastName}

{tx.user.mobile}

) : ( کاربر مهمان )}
{tx.type === 'WALLET_TOPUP' ? ( شارژ کیف پول ) : (
{tx.order?.trackingNumber || 'سفارش آنلاین'} خرید محصول
)}
{Number(tx.amount).toLocaleString('fa-IR')} تومان {tx.gateway === 'zibal' ? 'زیبال (Zibal)' : tx.gateway} {tx.trackId && (
Track: {tx.trackId}
)} {tx.refNumber && (
Ref: {tx.refNumber}
)}
{isVerified && ( }> پرداخت تایید شده )} {isPending && ( }> در انتظار تایید )} {isFailed && ( }> ناموفق / لغو شده )} {new Date(tx.createdAt).toLocaleDateString('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', })}
{isVerified && ( )}
)} {/* Pagination */} {totalPages > 1 && (
setParam('page', p, false)} />
)}
{/* Transaction Details Modal */} {selectedTx && (
{selectedTx.status === 'VERIFIED' && ( )} {selectedTx.status === 'PENDING' && ( <> )}
} >
{/* Quick Overview Badges */}

مبلغ تراکنش:

{Number(selectedTx.amount).toLocaleString('fa-IR')} تومان

درگاه پرداخت:

{selectedTx.gateway}

وضعیت:

{selectedTx.status === 'VERIFIED' ? ( موفق ) : ( {selectedTx.status} )}

نوع عملیات:

{selectedTx.type === 'WALLET_TOPUP' ? 'شارژ کیف پول' : 'خرید محصول'}

{/* Technical Identifiers */}
Transaction ID: {selectedTx.id}
{selectedTx.trackId && (
Zibal TrackID: {selectedTx.trackId}
)} {selectedTx.refNumber && (
Shaparak RRN: {selectedTx.refNumber}
)} {selectedTx.cardNumber && (
Card Mask: {selectedTx.cardNumber}
)}
{/* Live Shaparak Inquiry Section */} {selectedTx.trackId && (
استعلام برخط و زنده از درگاه پرداخت زیبال
{liveInquiryData && (
                    {JSON.stringify(liveInquiryData, null, 2)}
                  
)}
)}
)} {/* Parity Refund Modal (Supports Wallet and Zibal Gateway) */} {refundModalTx && ( } >
{/* Destination selector */}
setRefundAmount(e.target.value)} placeholder="مبلغ استرداد" className="w-full border border-gray-200 rounded-xl p-3 font-mono outline-none focus:ring-2 focus:ring-purple-500 font-bold font-vazir" dir="ltr" />