user.js 3.2 KB

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