user.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { showError } from "../utils/error.js";
  2. async function fetchUserSales(userId, token) {
  3. try {
  4. const response = await fetch(`/api/sales/user/${userId}`, {
  5. headers: {
  6. 'Content-Type': 'application/json',
  7. 'Authorization': `Bearer ${token}`
  8. }
  9. });
  10. if (response.status === 404) {
  11. showError("No se encontraron ventas para este usuario.");
  12. return [];
  13. } else if (response.status === 401) {
  14. showError("No autorizado. Verifica tu sesión.");
  15. throw new Error("Unauthorized access");
  16. } else if (response.status === 429) {
  17. showError("Demasiados intentos. Intenta más tarde.");
  18. throw new Error("Too many requests");
  19. } else if (response.status === 500) {
  20. showError("Error interno del servidor. Intenta más tarde.");
  21. throw new Error("Internal server error");
  22. } else if (response.status === 403) {
  23. showError("Acceso prohibido. Verifica tus permisos.");
  24. throw new Error("Forbidden access");
  25. }
  26. if (response.status !== 200) {
  27. showError(response.message);
  28. throw new Error(`Error fetching user sales: ${response.statusText}`);
  29. }
  30. const sales = await response.json();
  31. return sales.sales;
  32. } catch (error) {
  33. console.error('Error fetching user sales:', error);
  34. throw error;
  35. }
  36. }
  37. async function historyProducts(userId, token) {
  38. const sales = await fetchUserSales(userId, token);
  39. console.log("Ventas del usuario:", sales);
  40. if (!sales || sales.length === 0) {
  41. console.warn("No hay ventas para mostrar en el historial.");
  42. return [];
  43. }
  44. const products = sales.map(sale => (
  45. sale.products.map(product => ({
  46. quantity: product.quantity,
  47. productName: product.name,
  48. price: product.price.toFixed(0)
  49. }))
  50. ));
  51. console.log(products);
  52. return products.flat(2);
  53. }
  54. export { fetchUserSales, historyProducts };