shoppingCart.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 class="no-data"><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. if (table.querySelector(".no-data")) {
  19. table.querySelector(".no-data").remove(); // Remove no-data row if it exists
  20. }
  21. newRow.querySelector('.list-element-quantity').textContent = sale.quantity;
  22. newRow.querySelector('.list-element-name').textContent = sale.productName;
  23. newRow.querySelector('.list-element-price').textContent = `$${sale.price * sale.quantity}`;
  24. addCartHistoryTotal(sale.price * sale.quantity);
  25. table.querySelector('tbody').appendChild(newRow);
  26. }
  27. function addCartHistoryTotal(price) {
  28. const currentTotal = getHistoryTotal();
  29. const newTotal = currentTotal + Number(price);
  30. updateCartHistoryTotal(newTotal);
  31. }
  32. function updateCartHistoryTotal(total) {
  33. cartHistoryTotal.textContent = `$${total.toFixed(0)}`;
  34. }
  35. function getHistoryTotal() {
  36. return Number(cartHistoryTotal.textContent.replace(/[$,]/g, ''));
  37. }
  38. async function setupShoppingCart(userID, userToken, userName) {
  39. const name = document.querySelector('#usernameTable');
  40. if (name) {
  41. name.textContent = `Pedidos de: ${userName}`;
  42. }else{
  43. console.warn("No se encontró el elemento de nombre en la tabla de historial.");
  44. }
  45. const sales = await historyProducts(userID, userToken);
  46. if (sales){
  47. setHistoryTable(sales);
  48. }
  49. }
  50. export { setupShoppingCart, setHistoryTable, addHistoryRow, updateCartHistoryTotal, getHistoryTotal };