user.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. if (!sales || sales.length === 0) {
  40. console.warn("No hay ventas para mostrar en el historial.");
  41. return [];
  42. }
  43. const products = sales.map(sale => ([
  44. sale.products.map(product => ({
  45. quantity: product.quantity,
  46. productName: product.name,
  47. price: product.price.toFixed(0)
  48. }))
  49. ]));
  50. return products.flat(2);
  51. }
  52. export { fetchUserSales, historyProducts };