shoppingCart.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { fetchUserSales, historyProducts } from "../service/user.js";
  2. const table = document.getElementById('historyTable');
  3. const rowTemplate = document.getElementById('historyRowTemplate');
  4. const cartHistoryTotal = document.getElementById('cartHistoryTotal');
  5. function setHistoryTable(tableData) {
  6. if (!tableData || tableData.length === 0) {
  7. console.warn("No hay datos para mostrar en el historial de compras.");
  8. table.querySelector('tbody').innerHTML = '<tr><td colspan="3" class="text-center text-gray-500">No hay historial de compras.</td></tr>';
  9. return;
  10. }
  11. table.querySelector('tbody').innerHTML = ''; // Clear existing rows
  12. tableData.forEach(item => {
  13. addHistoryRow(item);
  14. });
  15. }
  16. function addHistoryRow(sale) {
  17. const newRow = rowTemplate.content.cloneNode(true);
  18. newRow.querySelector('.list-element-quantity').textContent = sale.quantity;
  19. newRow.querySelector('.list-element-name').textContent = sale.productName;
  20. newRow.querySelector('.list-element-price').textContent = `$${sale.price}`;
  21. addCartHistoryTotal(sale.price);
  22. table.querySelector('tbody').appendChild(newRow);
  23. }
  24. function addCartHistoryTotal(price) {
  25. const currentTotal = getHistoryTotal();
  26. const newTotal = currentTotal + Number(price);
  27. updateCartHistoryTotal(newTotal);
  28. }
  29. function updateCartHistoryTotal(total) {
  30. cartHistoryTotal.textContent = `$${total.toFixed(0)}`;
  31. }
  32. function getHistoryTotal() {
  33. return Number(cartHistoryTotal.textContent.replace(/[$,]/g, ''));
  34. }
  35. async function setupShoppingCart(userID, userToken, userName) {
  36. const name = document.querySelector('#usernameTable');
  37. if (name) {
  38. name.textContent = `Pedidos de: ${userName}`;
  39. }else{
  40. console.warn("No se encontró el elemento de nombre en la tabla de historial.");
  41. }
  42. const sales = await historyProducts(userID, userToken);
  43. if (sales){
  44. setHistoryTable(sales);
  45. }
  46. }
  47. export { setupShoppingCart, setHistoryTable, addHistoryRow, updateCartHistoryTotal, getHistoryTotal };