| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import { showError } from "../utils/error.js";
- 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 === 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.sales;
- } 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 };
|