diff --git a/.env b/.env index 2dd239f..cc2aa69 100644 --- a/.env +++ b/.env @@ -1,2 +1,6 @@ REACT_APP_AUTH0_DOMAIN=dev-lrsnvgepbp6l4a8d.us.auth0.com -REACT_APP_AUTH0_CLIENT_ID=w6GzmHDSuiU6cOu1NrDR4Av6P9aHXbty \ No newline at end of file +REACT_APP_AUTH0_CLIENT_ID=w6GzmHDSuiU6cOu1NrDR4Av6P9aHXbty + +# REACT_APP_API_URL= https://api.nodecraft.me +REACT_APP_API_URL= http://localhost:4000 +FRONTEND_URL= https://web.nodecraft.me \ No newline at end of file diff --git a/src/App.js b/src/App.jsx similarity index 57% rename from src/App.js rename to src/App.jsx index d890f35..6067899 100644 --- a/src/App.js +++ b/src/App.jsx @@ -2,7 +2,15 @@ import './App.css'; import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { useAuth0 } from '@auth0/auth0-react'; -import { generateInvoice } from './services/invoiceService.js'; +import {redirect, useNavigate} from 'react-router-dom'; +import { + fetchUser, + fetchFixtures, + signUpUser, + logInUser, + addMoneyToWallet as addMoneyService, + viewMyBonuses as viewMyBonusesService, +} from './services/apiService.jsx'; function App() { const { loginWithRedirect, logout, isAuthenticated, user, getAccessTokenSilently } = useAuth0(); @@ -19,146 +27,13 @@ function App() { const [result, setResult] = useState('home'); const [quantity, setQuantity] = useState(1); const [showAddMoneyModal, setShowAddMoneyModal] = useState(false); - const [authAction, setAuthAction] = useState(null); - const fixturesPerPage = 12; - - const removeDuplicateFixtures = (fixtures) => { - const uniqueFixtures = []; - const fixtureIds = new Set(); - - for (const fixture of fixtures) { - if (!fixtureIds.has(fixture.fixture_id)) { - fixtureIds.add(fixture.fixture_id); - uniqueFixtures.push(fixture); - } - } + const [authAction, setAuthAction] = useState(() => { + return localStorage.getItem('authAction') || null; + }); + const navigate = useNavigate(); + const apiUrl = process.env.REACT_APP_API_URL; - return uniqueFixtures; - }; -// eslint-disable-next-line - const fetchUser = async () => { - try { - const encodedUserId = localStorage.getItem('userId'); - const token = await getAccessTokenSilently(); - const response = await axios.get(`https://api.nodecraft.me/users/${encodedUserId}`, - { - headers: { - Authorization: `Bearer ${token}` - } - }); - setWalletBalance(response.data.wallet); - } catch (error) { - console.error('Error fetching wallet balance:', error); - } - }; -// eslint-disable-next-line - const fetchFixtures = async () => { - try { - const token = await getAccessTokenSilently(); - const response = await axios.get('https://api.nodecraft.me/fixtures', - { - headers: { - Authorization: `Bearer ${token}` - } - }); - const uniqueFixtures = removeDuplicateFixtures(response.data.data); - setFixtures(uniqueFixtures); - setFilteredFixtures(uniqueFixtures); - } catch (error) { - console.error('Error fetching fixtures:', error); - } - }; - - const generateLongUserId = () => { - const timestamp = Date.now(); - const highPrecision = Math.floor(performance.now() * 1000000); - const randomPart = Math.floor(Math.random() * 1000000000); - return `${timestamp}-${highPrecision}-${randomPart}`; - }; - // eslint-disable-next-line - const signUpUser = async () => { - try { - const token = await getAccessTokenSilently(); - const newUserId = generateLongUserId(); - - await axios.post('https://api.nodecraft.me/users', { - id: newUserId, - username: user.nickname, - email: user.email, - password: "Nohaypassword", - wallet: 0.0 - }, - { - headers: { - Authorization: `Bearer ${token}` - }, - } - ); - localStorage.setItem('userId', newUserId); - fetchUser(); - fetchFixtures(); - } catch (error) { - console.error('Error signing up user:', error); - } - }; - - const logInUser = async () => { - try { - let userId = localStorage.getItem('userId'); - if (!userId) { - const token = await getAccessTokenSilently(); - const response = await axios.get('https://api.nodecraft.me/users', { - headers: { - Authorization: `Bearer ${token}`, - }, - }); - - const users = response.data.users; - const existingUser = users.find((u) => u.email === user.email); - - if (existingUser) { - userId = existingUser.id; - localStorage.setItem('userId', userId); - fetchUser(); - fetchFixtures(); - } else { - console.error('User not found.'); - alert('User not found. Please sign up.'); - } - } - } catch (error) { - console.error('Error logging in user:', error); - } - }; - - const addMoneyToWallet = async () => { - const amount = prompt('Enter the amount to add to your wallet:'); - const parsedAmount = parseInt(amount, 10); - - if (!isNaN(parsedAmount) && parsedAmount > 0) { - try { - const userId = localStorage.getItem('userId'); - - const token = await getAccessTokenSilently(); - const response = await axios.patch( - `https://api.nodecraft.me/users/${userId}/wallet`, - { amount: parsedAmount }, - { - headers: { - Authorization: `Bearer ${token}` - } - } - ); - setWalletBalance(response.data.wallet); - alert(`Added $${parsedAmount} to your wallet.`); - } catch (error) { - console.error('Error adding money to wallet:', error); - alert('Failed to add money to wallet.'); - } - } else { - alert('Invalid amount entered. Please enter a valid integer.'); - } -}; + const fixturesPerPage = 12; const handleBuyBonusClick = (fixture) => { if (walletBalance >= 1000) { @@ -170,104 +45,90 @@ function App() { }; const buyBonus = async (fixture, result, quantity) => { - const cost = 1000 * quantity; const encodedUserId = localStorage.getItem('userId'); - - if (walletBalance >= cost && fixture.bonos >= quantity) { - setShowBuyModal(false); - setShowProcessingModal(true); - - try { - const token = await getAccessTokenSilently(); - const response = await axios.post( - `https://api.nodecraft.me/fixtures/${fixture.fixture_id}/compra`, - { - userId: encodedUserId, - result: result, - quantity: quantity - }, - { - headers: { - Authorization: `Bearer ${token}` - } - } - ); - - setShowProcessingModal(false); - - if (response.data.error) { - alert(response.data.error); - } else { - - // Agregado generación de boleta post compra - const userData = { - name: user.nickname, - email: user.email - }; - - const matchData = { - teams: fixture.teams, - date: fixture.date, - amount: cost // El valor depende de la cantidad - }; - - // Se genera el URL de la boleta y además se informa la ubicación - try { - const pdfUrl = await generateInvoice(userData, matchData); - alert(`Compra exitosa. Descarga tu boleta aquí: ${pdfUrl}. Ubicación: ${response.data.location.city}`); - fetchUser(); - fetchFixtures(); - } catch (error) { - alert('Error generando la boleta.'); - } - } - } catch (error) { - setShowProcessingModal(false); - alert('Hubo un error al procesar la compra.'); - } - } else { - alert('Fondos insuficientes o bonos no disponibles.'); - } - }; - const viewMyBonuses = async () => { - const userId = localStorage.getItem('userId'); - - if (!userId) { - alert('No se pudo encontrar el ID del usuario.'); + if (!encodedUserId) { + alert('Usuario no encontrado.'); return; } try { const token = await getAccessTokenSilently(); - const response = await axios.get(`https://api.nodecraft.me/requests/${userId}`, { - headers: { - Authorization: `Bearer ${token}` + console.log("mira tu") + const response = await axios.post( + `${apiUrl}/fixtures/${fixture.fixture_id}/compra`, + { + userId: encodedUserId, + result: result, + quantity: quantity + }, + { + headers: { + Authorization: `Bearer ${token}` + } + } + ) + + // del post me debería llegar un message: "Compra iniciada con éxito", un url y un token + console.log("obtuvimos el token") + console.log("url:", response.data.url) + console.log('token:', response.data.token) + + if (response.data.url && response.data.token) { + navigate('/confirm-purchase', { + state: { + url: response.data.url, + token: response.data.token, + amount: quantity, + fixture: fixture, + result: result, + locationInfo: response.data.location, + request_id: response.data.request_id + } + }); + + if (response.data.error) { + alert(response.data.error); } - }); - - if (response.data && response.data.requests) { - setBonuses(response.data.requests); - setShowModal(true); } else { - alert('No se encontraron bonuses para este usuario.'); + alert('Error al iniciar la transacción.'); } } catch (error) { - console.error('Error al obtener los bonuses:', error); - alert('Error al obtener los bonuses.'); + console.error('Error al realizar la compra:', error); + alert('Hubo un error al procesar la compra.'); } }; // eslint-disable-next-line useEffect(() => { const initializeUser = async () => { - if (isAuthenticated && authAction) { + if (isAuthenticated) { try { - if (authAction === 'signup') { - await signUpUser(); - } else if (authAction === 'login') { - await logInUser(); + let userId = localStorage.getItem('userId'); + if (!userId) { + // Si no hay userId en el localStorage, buscarlo del backend + const token = await getAccessTokenSilently(); + const apiUrl = process.env.REACT_APP_API_URL; + const response = await axios.get(`${apiUrl}/users`, { + headers: { + Authorization: `Bearer ${token}` + } + }); + const users = response.data.users; + const existingUser = users.find(user => user.email === user.email); + if (existingUser) { + userId = existingUser.id; + localStorage.setItem('userId', userId); + } else { + // Si el usuario no existe en la base de datos, crearlo + userId = await signUpUser(user, getAccessTokenSilently); + } } + const wallet = await fetchUser(userId, getAccessTokenSilently); + setWalletBalance(wallet); + const uniqueFixtures = await fetchFixtures(getAccessTokenSilently); + setFixtures(uniqueFixtures); + setFilteredFixtures(uniqueFixtures); } catch (error) { console.error('Error initializing user:', error); } @@ -290,7 +151,7 @@ function App() { }); }; - + // UseEffect para aplicar los filtros useEffect(() => { const applyFilters = () => { let filtered = fixtures; @@ -324,22 +185,74 @@ function App() { const paginate = (pageNumber) => setCurrentPage(pageNumber); + // Función para añadir dinero a la wallet + const handleAddMoneyToWallet = async () => { + const amount = prompt('Enter the amount to add to your wallet:'); + const parsedAmount = parseInt(amount, 10); + + if (!isNaN(parsedAmount) && parsedAmount > 0) { + try { + const newBalance = await addMoneyService(parsedAmount, getAccessTokenSilently); + setWalletBalance(newBalance); + alert(`Added $${parsedAmount} to your wallet.`); + } catch (error) { + alert('Failed to add money to wallet.'); + } + } else { + alert('Invalid amount entered. Please enter a valid integer.'); + } + }; + + // Función para ver mis bonos + const handleViewBonuses = async () => { + const userId = localStorage.getItem('userId'); + + if (!userId) { + alert('No se pudo encontrar el ID del usuario.'); + return; + } + + try { + const fetchedBonuses = await viewMyBonusesService(userId, getAccessTokenSilently); + setBonuses(fetchedBonuses); + setShowModal(true); + } catch (error) { + alert('Error al obtener los bonuses.'); + } + }; + + const handleLogout = () => { + // Eliminar userId del localStorage + localStorage.removeItem('userId'); + + // Llamar a la función logout + logout({ returnTo: window.location.origin }); + // logout({ returnTo: 'http://localhost:3000/' }); // debugging + + }; + + const redirectToMyRequests = () => { + navigate('/my-requests'); + } + + console.log("isAuthenticated", isAuthenticated) + return (
Welcome,
-League: {bonus.league_name}
-Round: {bonus.round}
-Date: {new Date(bonus.date).toLocaleDateString()}
-Result: {bonus.result}
-Quantity: {bonus.quantity}
-Processed: {bonus.processed ? 'Yes' : 'No'}
-Odd: {bonus.odd}
-No bonuses found.
- )} -League: {bonus.league_name}
+Round: {bonus.round}
+Date: {new Date(bonus.date).toLocaleDateString()}
+Result: {bonus.result}
+Quantity: {bonus.quantity}
+Processed: {bonus.processed ? 'Yes' : 'No'}
+Odd: {bonus.odd}
+No bonuses found.
+ )} +No hay datos de compra disponibles.
; + } + + const { fixture, amount, result, url, token, locationInfo, request_id} = data; + + //Set fixture id in local storage + localStorage.setItem('request_id', request_id); + + return ( +Liga: {fixture.league_name}
+Fecha: {new Date(fixture.date).toLocaleDateString()}
+Hora: {new Date(fixture.date).toLocaleTimeString()}
+Cantidad de Bonos: {amount}
+Resultado Apostado: {result}
+Liga | +Jornada | +Fecha | +Resultado | +Cantidad | +¿Has acertado? | +Odd | +Estado | +|
---|---|---|---|---|---|---|---|---|
{req.league_name} | +{req.round} | +{new Date(req.date).toLocaleDateString()} | +{req.result} | +{req.quantity} | +{req.processed ? 'Sí' : 'No'} | +{req.odd} | ++ {req.valid === true && 'Válida'} + {req.valid === false && 'No Válida'} + {req.valid === null && 'Pendiente'} + | +
+ {req.valid === true && (
+ |
+
No se encontraron solicitudes para mostrar.
+ )} + + {/* Botón para regresar a la página principal */} +Por favor, espera...
} + {isSuccess &&Gracias por tu compra. ¡Disfruta de tus bonos!
} + {(isSuccess === false)&&(isAborted === false) && ( ++ Hubo un problema con tu compra. Por favor, intenta de nuevo o contacta al soporte. +
+ )} + {isAborted &&Decidiste anular tu compra, ¡Quizás te convezca otro partido!
} +