import React, { useState, useEffect } from 'react'; import axios from 'axios'; import ProgressBox from './ConfirmBox'; import ConfirmBox from './ConfirmBox'; const BASE_URL = "http://localhost:8000"; const WithdrawalTable = () => { const [withdrawals, setWithdrawals] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const [statusFilter, setStatusFilter] = useState('all'); const [refs, setRefs] = useState({}); const [users, setUsers] = useState({}); const [updateLoading, setUpdateLoading] = useState(null); const [showModal, setShowModal] = useState(false); const [showModal2, setShowModal2] = useState(false); const [showModal3, setShowModal3] = useState(false); const [selectedWithdrawalId, setSelectedWithdrawalId] = useState(null); const fetchWithdrawals = async () => { const token = localStorage.getItem('token'); try { setLoading(true); const response = await axios.get(`${BASE_URL}/withdrawal/`, { headers: { 'Authorization': `Bearer ${token}` } }); const sortedWithdrawals = response.data.data.sort((a, b) => new Date(b.transactionDate) - new Date(a.transactionDate) ); setWithdrawals(sortedWithdrawals); setError(null); } catch (error) { console.error("Error fetching withdrawals:", error); setError("Çekimler yüklenirken bir hata oluştu. Lütfen tekrar deneyin."); } finally { setLoading(false); } }; const fetchRefs = async () => { const token = localStorage.getItem('token'); try { const response = await axios.get(`${BASE_URL}/refs/`, { headers: { 'Authorization': `Bearer ${token}` } }); const refsMap = {}; response.data.forEach(ref => { refsMap[ref.refId] = ref.refName; }); setRefs(refsMap); } catch (error) { console.error("Error fetching refs:", error); } }; const fetchUsers = async () => { const token = localStorage.getItem('token'); try { const response = await axios.get(`${BASE_URL}/users`, { headers: { 'Authorization': `Bearer ${token}` } }); const usersMap = {}; response.data.data.forEach(user => { usersMap[user.id] = user.username; }); setUsers(usersMap); } catch (error) { console.error("Error fetching users:", error); } }; useEffect(() => { fetchWithdrawals(); fetchRefs(); fetchUsers(); const interval = setInterval(() => { fetchWithdrawals(); }, 10000); return () => clearInterval(interval); }, []); const handleTakeOwnership = async (withdrawalId) => { const token = localStorage.getItem('token'); try { setUpdateLoading(withdrawalId); await axios.post(`${BASE_URL}/withdrawal/${withdrawalId}/take-ownership`, null, { headers: { 'Authorization': `Bearer ${token}` } }); await fetchWithdrawals(); setShowModal(false); } catch (error) { console.error("Error taking ownership:", error); setError("Çekim sahiplenirken bir hata oluştu."); } finally { setUpdateLoading(null); } }; const handleStatusUpdate = async (withdrawalId, newStatus) => { const token = localStorage.getItem('token'); setUpdateLoading(withdrawalId); try { const withdrawal = withdrawals.find(w => w.id === withdrawalId); if (!withdrawal.userID) { await handleTakeOwnership(withdrawalId); } // First update the withdrawal status await axios.patch(`${BASE_URL}/withdrawal/${withdrawalId}`, { withdrawalStatus: newStatus, note: newStatus === 'Onaylandı' ? 'Çekim onaylandı' : newStatus === 'İptal' ? 'Çekim iptal edildi' : 'Çekim beklemede', }, { headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` } }); // If the status is approved, subtract the balance from the account if (newStatus === 'Onaylandı') { try { // First get the account details const accountsResponse = await axios.get(`${BASE_URL}/bank/accounts`, { headers: { 'Authorization': `Bearer ${token}` } }); // Find the matching account const account = accountsResponse.data.data.find( acc => acc.accountNumber === withdrawal.accountNumber ); if (account) { // Subtract the withdrawal balance from the account await axios.patch( `${BASE_URL}/bank/sub_balance/${account.accountId}`, { accountBalance: withdrawal.balance, accountExplanation: `Çekim onaylandı - Çekim ID: ${withdrawal.id}` }, { headers: { 'Authorization': `Bearer ${token}` } } ); } else { console.error("Account not found for the withdrawal"); setError("Çekim hesabı bulunamadı."); } } catch (balanceError) { console.error("Error updating account balance:", balanceError); setError("Hesap bakiyesi güncellenirken bir hata oluştu."); } } await fetchWithdrawals(); } catch (error) { console.error("Error updating status:", error); setError("Bu Çekimi Onaylamaya Yetkiniz Yok."); } finally { setUpdateLoading(null); } }; const getStatusBadgeClass = (status) => { switch (status) { case 'Onaylandı': return 'bg-emerald-600 text-slate-200'; case 'İptal': return 'bg-red-600 text-slate-200'; case 'Beklemede': default: return 'bg-yellow-600 text-slate-100'; } }; const getStatusTableClass = (status) => { switch (status) { case 'Onaylandı': return 'bg-emerald-200 text-white'; case 'İptal': return 'bg-red-200 text-white'; case 'Beklemede': return 'bg-amber-100 text-white'; default: return 'bg-gray-100 text-slate-100'; } }; const handleCloseShowModal = () => { setShowModal(false); setSelectedWithdrawalId(null); }; const handleCloseShowModal2 = () => { setShowModal2(false); setSelectedWithdrawalId(null); }; const handleCloseShowModal3 = () => { setShowModal3(false); setSelectedWithdrawalId(null); }; const filteredWithdrawals = withdrawals.filter(withdrawal => { const searchLower = searchTerm.toLowerCase(); const matchesSearch = ( withdrawal.id.toString().includes(searchLower) || (refs[withdrawal.refId] || '').toLowerCase().includes(searchLower) || withdrawal.fullName.toLowerCase().includes(searchLower) || withdrawal.username.toLowerCase().includes(searchLower) || withdrawal.accountNumber.includes(searchLower) || withdrawal.targetAccountNumber.includes(searchLower) ); const matchesStatus = statusFilter === 'all' || withdrawal.withdrawalStatus === statusFilter; return matchesSearch && matchesStatus; }); if (loading) { return (
); } return (
{/* Search and filters */}
setSearchTerm(e.target.value)} />
{error && (

Hata!

{error}

)}
{filteredWithdrawals.map((withdrawal) => ( ))}
ID Site Adı Soyadı Miktar Kullanıcı Adı Yöntem Kaynak Hesap Kaynak No Hedef Hesap Hedef No İşlem Tarihi Sonuç Tarihi İşlemi Yapan Durum İşlemler
{withdrawal.id} {refs[withdrawal.refId] || '-'} {withdrawal.fullName} {withdrawal.balance.toLocaleString()} ₺ {withdrawal.username} {withdrawal.method} {withdrawal.accountName} {withdrawal.accountNumber} {withdrawal.targetAccountNumber} {new Date(withdrawal.transactionDate).toLocaleString("tr-TR")} {(withdrawal.withdrawalStatus === 'Onaylandı' || withdrawal.withdrawalStatus === 'İptal') && ( withdrawal.resultDate && new Date(withdrawal.resultDate).toLocaleString("tr-TR") )} {users[withdrawal.userID] || 'Seçilmedi'} {withdrawal.withdrawalStatus}
{withdrawal.withdrawalStatus === 'Beklemede' && ( <> {!withdrawal.userID && ( )} {withdrawal.userID && (
)} )}
{showModal && ( handleTakeOwnership(selectedWithdrawalId)} onClose={handleCloseShowModal} /> )} {showModal2 && ( { handleStatusUpdate(selectedWithdrawalId, 'Onaylandı'); setShowModal2(false); }} onClose={handleCloseShowModal2} /> )} {showModal3 && ( { handleStatusUpdate(selectedWithdrawalId, 'İptal'); setShowModal3(false); }} onClose={handleCloseShowModal3} /> )} {filteredWithdrawals.length === 0 && (
Çekim Bulunamadı.
)}
); }; export default WithdrawalTable;