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 InvestmentTable = () => { const [investments, setInvestments] = 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 [selectedInvestmentId, setSelectedInvestmentId] = useState(null); const fetchInvestments = async () => { const token = localStorage.getItem('token'); try { setLoading(true); const response = await axios.get(`${BASE_URL}/investment/`, { headers: { 'Authorization': `Bearer ${token}` } }); const sortedInvestments = response.data.data.sort((a, b) => new Date(b.transactionDate) - new Date(a.transactionDate) ); setInvestments(sortedInvestments); setError(null); } catch (error) { console.error("Error fetching investments:", error); setError("Yatırımlar 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(() => { fetchInvestments(); fetchRefs(); fetchUsers(); const interval = setInterval(() => { fetchInvestments(); }, 15000); return () => clearInterval(interval); }, []); const handleTakeOwnership = async (investmentId) => { const token = localStorage.getItem('token'); try { setUpdateLoading(investmentId); await axios.post(`${BASE_URL}/investment/${investmentId}/take-ownership`, null, { headers: { 'Authorization': `Bearer ${token}` } }); await fetchInvestments(); setShowModal(false); } catch (error) { console.error("Error taking ownership:", error); setError("Yatırım sahiplenirken bir hata oluştu."); } finally { setUpdateLoading(null); } }; const handleStatusUpdate = async (investmentId, newStatus) => { const token = localStorage.getItem('token'); setUpdateLoading(investmentId); try { const investment = investments.find(inv => inv.id === investmentId); if (!investment.userID) { await handleTakeOwnership(investmentId); } // First update the investment status await axios.patch(`${BASE_URL}/investment/${investmentId}`, { investmentStatus: newStatus, note: newStatus === 'Onaylandı' ? 'Yatırım onaylandı' : newStatus === 'İptal' ? 'Yatırım iptal edildi' : 'Yatırım beklemede', }, { headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` } }); // If the status is approved, add the balance to 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 === investment.accountNumber ); if (account) { // Add the investment balance to the account await axios.patch( `${BASE_URL}/bank/add_balance/${account.accountId}`, { accountBalance: investment.balance, accountExplanation: `Yatırım onaylandı - Yatırım ID: ${investment.id}` }, { headers: { 'Authorization': `Bearer ${token}` } } ); } else { console.error("Account not found for the investment"); setError("Yatırım hesabı bulunamadı."); } } catch (balanceError) { console.error("Error updating account balance:", balanceError); setError("Hesap bakiyesi güncellenirken bir hata oluştu."); } } await fetchInvestments(); } catch (error) { console.error("Error updating status:", error); setError("Bu Yatırımı 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); setSelectedInvestmentId(null); }; const handleCloseShowModal2 = () => { setShowModal2(false); setSelectedInvestmentId(null); }; const handleCloseShowModal3 = () => { setShowModal3(false); setSelectedInvestmentId(null); }; const filteredInvestments = investments.filter(investment => { const searchLower = searchTerm.toLowerCase(); const matchesSearch = ( investment.id.toString().includes(searchLower) || (refs[investment.refId] || '').toLowerCase().includes(searchLower) || investment.fullName.toLowerCase().includes(searchLower) || investment.username.toLowerCase().includes(searchLower) || investment.accountNumber.includes(searchLower) ); const matchesStatus = statusFilter === 'all' || investment.investmentStatus === statusFilter; return matchesSearch && matchesStatus; }); if (loading) { return (
); } return (
{/* Search and filters */}
setSearchTerm(e.target.value)} />
{error && (

Hata!

{error}

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