user.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { showError } from "../utils/error.js";
  2. export async function getUserData(token) {
  3. try {
  4. const response = await fetch('/api/users/user', {
  5. headers: {
  6. 'Content-Type': 'application/json',
  7. 'Authorization': `Bearer ${token}`
  8. }
  9. });
  10. if (response.status === 401) {
  11. showError("No autorizado. Verifica tu sesión.");
  12. throw new Error("Unauthorized access");
  13. }
  14. if (response.status === 429) {
  15. showError("Demasiados intentos. Intenta más tarde.");
  16. throw new Error("Too many requests");
  17. }
  18. if (response.status === 500) {
  19. showError("Error interno del servidor. Intenta más tarde.");
  20. throw new Error("Internal server error");
  21. }
  22. 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 data: ${response.statusText}`);
  29. }
  30. const userData = await response.json();
  31. return userData;
  32. } catch (error) {
  33. console.error('Error fetching user data:', error);
  34. throw error;
  35. }
  36. }
  37. async function fetchUserSales(userId, token) {
  38. try {
  39. const response = await fetch(`/api/sales/user/${userId}`, {
  40. headers: {
  41. 'Content-Type': 'application/json',
  42. 'Authorization': `Bearer ${token}`
  43. }
  44. });
  45. if (response.status === 404) {
  46. showError("No se encontraron ventas para este usuario.");
  47. return [];
  48. } else if (response.status === 401) {
  49. showError("No autorizado. Verifica tu sesión.");
  50. throw new Error("Unauthorized access");
  51. } else if (response.status === 429) {
  52. showError("Demasiados intentos. Intenta más tarde.");
  53. throw new Error("Too many requests");
  54. } else if (response.status === 500) {
  55. showError("Error interno del servidor. Intenta más tarde.");
  56. throw new Error("Internal server error");
  57. } else if (response.status === 403) {
  58. showError("Acceso prohibido. Verifica tus permisos.");
  59. throw new Error("Forbidden access");
  60. }
  61. if (response.status !== 200) {
  62. showError(response.message);
  63. throw new Error(`Error fetching user sales: ${response.statusText}`);
  64. }
  65. const sales = await response.json();
  66. return sales.sales;
  67. } catch (error) {
  68. console.error('Error fetching user sales:', error);
  69. throw error;
  70. }
  71. }
  72. async function historyProducts(userId, token) {
  73. const sales = await fetchUserSales(userId, token);
  74. console.log("Ventas del usuario:", sales);
  75. if (!sales || sales.length === 0) {
  76. console.warn("No hay ventas para mostrar en el historial.");
  77. return [];
  78. }
  79. const products = sales.map(sale => (
  80. sale.products.map(product => ({
  81. quantity: product.quantity,
  82. productName: product.name,
  83. price: product.price.toFixed(0)
  84. }))
  85. ));
  86. console.log(products);
  87. return products.flat(2);
  88. }
  89. export { fetchUserSales, historyProducts };