import { useState, useEffect } from 'react'; import '../index.css'; import axios from 'axios'; import { AiOutlineLoading3Quarters } from "react-icons/ai"; import { FaCopy } from "react-icons/fa"; import { AiFillCheckSquare } from "react-icons/ai"; import { MdError } from "react-icons/md"; const BASE_URL = "http://localhost:8000"; function ParavanForm() { const [loading, setLoading] = useState(false); const [submissionStatus, setSubmissionStatus] = useState(null); // null | 'pending' | 'approved' | 'cancelled' | 'error' const [activeAccount, setActiveAccount] = useState(null); const [error, setError] = useState(null); const [accounts, setAccounts] = useState([]); const [investment, setInvestment] = useState([]); const [currentInvestmentId, setCurrentInvestmentId] = useState(null); const [formData, setFormData] = useState({ refId: 'b99d6f4a-ee37-4336-8870-44b25c1a9837', fullName: '', balance: '', username: 'bahsegel.user', accountName: '', accountNumber: '', method: 'Iframe', note: '' }); // Poll investment status useEffect(() => { let intervalId; const checkInvestmentStatus = async () => { if (!currentInvestmentId) return; try { const token = localStorage.getItem('token'); const response = await axios.get(`${BASE_URL}/investment/${currentInvestmentId}`, { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } }); const status = response.data.investmentStatus; if (status === 'Onaylandı') { setSubmissionStatus('approved'); clearInterval(intervalId); } else if (status === 'İptal') { setSubmissionStatus('cancelled'); clearInterval(intervalId); } } catch (error) { console.error('Error checking investment status:', error); setSubmissionStatus('error'); clearInterval(intervalId); } }; if (submissionStatus === 'pending') { intervalId = setInterval(checkInvestmentStatus, 5000); // Poll every 5 seconds } return () => { if (intervalId) clearInterval(intervalId); }; }, [currentInvestmentId, submissionStatus]); const fetchData = async () => { try { setLoading(true); const response = await axios.get(`${BASE_URL}/bank/accounts`); const sortedAccounts = response.data.data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); setAccounts(sortedAccounts); setError(null); } catch (error) { console.error("Error fetching bank accounts:", error); setError("Failed to load bank accounts. Please try again later."); } finally { setLoading(false); } }; const formatIBAN = (accountNumber) => { return accountNumber.replace(/\s+/g, '').match(/.{1,4}/g)?.join(' ') || ''; }; const getRandomActiveAccount = () => { const activeAccounts = accounts.filter(account => account.isInvest); if (activeAccounts.length === 0) return null; const randomIndex = Math.floor(Math.random() * activeAccounts.length); return activeAccounts[randomIndex]; }; const handleNextStep = () => { setLoading(true); setTimeout(() => { const randomAccount = getRandomActiveAccount(); setActiveAccount(randomAccount); setLoading(false); }, 3500); }; useEffect(() => { fetchData(); }, []); const handleSubmit = async (e) => { e.preventDefault(); setLoading(false); setSubmissionStatus('pending'); const validationErrors = validateForm(); if (validationErrors.length > 0) { setError(validationErrors.join(', ')); setSubmissionStatus(null); return; } setError(''); const params = new URLSearchParams(); Object.entries({ refId: formData.refId.trim(), fullName: formData.fullName.trim(), balance: parseFloat(formData.balance), username: formData.username.trim(), accountName: activeAccount.accountName, accountNumber: activeAccount.accountNumber, method: formData.method.trim(), note: formData.note.trim() || '' }).forEach(([key, value]) => { params.append(key, value); }); try { const token = localStorage.getItem('token'); const response = await axios.post(`${BASE_URL}/investment/?${params.toString()}`, {}, { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } }); setInvestment([...investment, response.data]); setCurrentInvestmentId(response.data.id); } catch (error) { let errorMessage = 'Yatırım oluşturulurken bir hata oluştu.'; if (error.response?.data?.detail) { if (Array.isArray(error.response.data.detail)) { const fieldErrors = error.response.data.detail.map(err => `${err.loc[1]}: ${err.msg}` ).join(', '); errorMessage += ` Hatalı alanlar: ${fieldErrors}`; } else { errorMessage += ` Detay: ${error.response.data.detail}`; } } setError(errorMessage); setSubmissionStatus('error'); } }; const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: name === 'balance' ? value.replace(/[^\d.]/g, '') : value })); }; const validateForm = () => { const errors = []; if (!formData.fullName.trim()) errors.push("Ad Soyad alanı zorunludur"); if (!formData.balance || isNaN(formData.balance) || parseFloat(formData.balance) <= 0) errors.push("Geçerli bir miktar giriniz"); return errors; }; const renderStatusScreen = () => { switch (submissionStatus) { case 'pending': return (
İŞLEMİNİZ KONTROL EDİLİYOR
Yatırımınız Onaylanmıştır
Yatırımınız İptal Edilmiştir
Bir Hata Oluştu
LÜTFEN BEKLEYİNİZ.
{formData.fullName}
{activeAccount.accountName}
TR {formatIBAN(activeAccount.accountNumber)}