import React, { useState, useEffect } from 'react'; import axios from 'axios'; const BASE_URL = "http://localhost:8000"; const InvestmentForm = ({ show, onClose, title }) => { const [refs, setRefs] = useState([]); const [investment, setInvestment] = useState([]); const [formData, setFormData] = useState({ refId: '', fullName: '', balance: '', username: '', accountName: '', accountNumber: '', method: '', note: '' }); const [isLoading, setIsLoading] = useState(false); const [showModal, setShowModal] = useState(false); const [error, setError] = useState(''); const [successMessage, setSuccessMessage] = useState(''); useEffect(() => { const fetchRefs = async () => { const token = localStorage.getItem('token'); try { const response = await axios.get(`${BASE_URL}/refs/`, { headers: { 'Authorization': `Bearer ${token}` } }); setRefs(response.data); } catch (error) { console.error("Error fetching refs:", error); setError(error.response?.data?.detail || "Failed to load references"); } }; if (show) { fetchRefs(); } }, [show]); const handleChange = (e) => { const { name, value } = e.target; let processedValue = value; if (name === 'balance') { // Remove any non-numeric characters except decimal point const numericValue = value.replace(/[^\d.]/g, ''); // Ensure only one decimal point const parts = numericValue.split('.'); if (parts.length > 2) { processedValue = parts[0] + '.' + parts.slice(1).join(''); } else { processedValue = numericValue; } // Convert to number if valid if (processedValue) { processedValue = parseFloat(processedValue); } } setFormData(prev => ({ ...prev, [name]: processedValue })); }; const validateForm = () => { const errors = []; if (!formData.refId || formData.refId.trim() === '') errors.push("Referans seçimi zorunludur"); if (!formData.fullName || formData.fullName.trim() === '') errors.push("Ad Soyad alanı zorunludur"); if (!formData.balance || isNaN(formData.balance) || formData.balance <= 0) errors.push("Geçerli bir miktar giriniz"); if (!formData.username || formData.username.trim() === '') errors.push("Kullanıcı adı zorunludur"); if (!formData.accountName || formData.accountName.trim() === '') errors.push("Hesap adı zorunludur"); if (!formData.accountNumber || formData.accountNumber.trim() === '') errors.push("Hesap numarası zorunludur"); if (!formData.method || formData.method.trim() === '') errors.push("Ödeme yöntemi zorunludur"); return errors; }; const resetForm = () => { setFormData({ refId: '', fullName: '', balance: '', username: '', accountName: '', accountNumber: '', method: '', note: '' }); setError(''); setSuccessMessage(''); }; const handleSubmit = async (e) => { e.preventDefault(); const validationErrors = validateForm(); if (validationErrors.length > 0) { setError(validationErrors.join(', ')); return; } setIsLoading(true); setError(''); setSuccessMessage(''); const token = localStorage.getItem('token'); // Build URL with query parameters const params = new URLSearchParams(); Object.entries({ refId: formData.refId.trim(), fullName: formData.fullName.trim(), balance: parseFloat(formData.balance), username: formData.username.trim(), accountName: formData.accountName.trim(), accountNumber: formData.accountNumber.trim(), method: formData.method.trim(), note: formData.note.trim() || '' }).forEach(([key, value]) => { params.append(key, value); }); try { const response = await axios({ method: 'post', url: `${BASE_URL}/investment/?${params.toString()}`, headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } }); console.log('Success response:', response.data); setSuccessMessage('Yatırım başarıyla oluşturuldu'); setInvestment([...investment, response.data]); setShowModal(true); resetForm(); } catch (error) { console.error('Error details:', { error: error.response?.data, status: error.response?.status, headers: error.response?.headers }); 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); } finally { setIsLoading(false); } }; const handleCloseModal = () => { setShowModal(false); onClose(); window.location.reload(); }; if (!show) return null; return (

{title || 'Yeni Yatırım'}

{error && (
{error}
)} {successMessage && (
{successMessage}
)}