import { beforeUnloadHandler } from "../app.js"; import { showError } from "../utils/error.js"; export async function getUserData(token) { try { const response = await fetch('/api/users/user', { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }); if (response.status === 420) { window.removeEventListener("beforeunload", beforeUnloadHandler); window.location.replace("/"); } if (response.status === 401) { showError("No autorizado. Verifica tu sesión."); throw new Error("Unauthorized access"); } if (response.status === 429) { showError("Demasiados intentos. Intenta más tarde."); throw new Error("Too many requests"); } if (response.status === 500) { showError("Error interno del servidor. Intenta más tarde."); throw new Error("Internal server error"); } if (response.status === 403) { showError("Acceso prohibido. Verifica tus permisos."); throw new Error("Forbidden access"); } if (response.status !== 200) { showError(response.message); throw new Error(`Error fetching user data: ${response.statusText}`); } const userData = await response.json(); return userData.data; } catch (error) { console.error('Error fetching user data:', error); throw error; } } async function fetchUserSales(userId, token) { try { const response = await fetch(`/api/sales/user/${userId}`, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }); if (response.status === 420) { window.removeEventListener("beforeunload", beforeUnloadHandler); window.location.replace("/"); } if (response.status === 404) { showError("No se encontraron ventas para este usuario."); return []; } else if (response.status === 401) { showError("No autorizado. Verifica tu sesión."); throw new Error("Unauthorized access"); } else if (response.status === 429) { showError("Demasiados intentos. Intenta más tarde."); throw new Error("Too many requests"); } else if (response.status === 500) { showError("Error interno del servidor. Intenta más tarde."); throw new Error("Internal server error"); } else if (response.status === 403) { showError("Acceso prohibido. Verifica tus permisos."); throw new Error("Forbidden access"); } if (response.status !== 200) { showError(response.message); throw new Error(`Error fetching user sales: ${response.statusText}`); } const sales = await response.json(); return sales.data; } catch (error) { console.error('Error fetching user sales:', error); throw error; } } async function historyProducts(userId, token) { const sales = await fetchUserSales(userId, token); if (!sales || sales.length === 0) { console.warn("No hay ventas para mostrar en el historial."); return []; } const products = sales.map(sale => ( sale.products.map(product => ({ quantity: product.quantity, productName: product.name, price: product.price.toFixed(0) })) )); return products.flat(2); } export { fetchUserSales, historyProducts };