Advertisement
oscarviedma

Código JavaScript Catálogo Productos WA GS OV - Corregido

Apr 22nd, 2024
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let carrito = [];
  2. let carritoTotal = 0;
  3. let productosFiltrados = [];
  4.  
  5. const preloader = document.getElementById('preloader');
  6. preloader.style.display = 'block';
  7.  
  8. let datosProductos = [];
  9. const contenedorProductos = document.getElementById('contenedor-productos');
  10. const mensajeNoEncontrado = document.getElementById('mensaje-no-encontrado');
  11. contenedorProductos.style.opacity = '0';
  12.  
  13. function formatearPrecio(precio) {
  14.   return precio.toLocaleString('en-US');
  15.   // return precio.toLocaleString('es-ES', { style: 'currency', currency: 'EUR' });
  16.   // return precio.toLocaleString('es-MX', { style: 'currency', currency: 'MXN' });
  17.   // return precio.toLocaleString('es-CO', { style: 'currency', currency: 'COP' });
  18. }
  19.  
  20. // REEMPLAZAR URL APPSCRIPT GOOGLE SHEETS
  21. fetch('https://script.google.com/macros/s/AKfycbzxho78Qr07ADOpzdfF-acJxTztln4aZnQUoptrYHJcNNLMPS1Z_oIzrTfbQbC6Bwlc/exec')
  22.   .then(response => response.json())
  23.   .then(data => {
  24.     datosProductos = data;
  25.     productosFiltrados = data;
  26.     renderizarProductos(productosFiltrados);
  27.     preloader.style.display = 'none';
  28.     contenedorProductos.style.opacity = '1';
  29.     document.getElementById('contenedor-buscador').style.display = '';
  30.     generarCategorias(data);
  31.   })
  32.   .catch(error => {
  33.     console.error('Error al obtener el JSON:', error);
  34.     preloader.style.display = 'none';
  35.   });
  36.  
  37. function renderizarProductos(productos) {
  38.   contenedorProductos.innerHTML = '';
  39.   if (productos.length === 0) {
  40.     mensajeNoEncontrado.style.display = 'block';
  41.   } else {
  42.     mensajeNoEncontrado.style.display = 'none';
  43.     productos.forEach((producto, index) => {
  44.       var productoDiv = document.createElement('div');
  45.       productoDiv.className = 'producto';
  46.  
  47.       productoDiv.innerHTML = `
  48.           <div class="imagen">
  49.               <img src="${producto.imagen}" alt="Imagen del producto">
  50.           </div>
  51.           <div class="info">
  52.               <h4 class="titulo">${producto.titulo}</h4>
  53.               <h3 class="precio">$${formatearPrecio(producto.precio)} USD</h3>
  54.               <div class="metadatos" id="atributo${index}">
  55.                   ${producto.atributos && Object.keys(producto.atributos).length > 0 ?
  56.                     Object.entries(producto.atributos).map(([nombreAtributo, valores]) => {
  57.                       const nombreAtributoLowerCase = nombreAtributo.toLowerCase();
  58.                       if (valores.filter(Boolean).length > 0) {
  59.                         return `<div class="meta">
  60.                                     <label for="${nombreAtributoLowerCase}${index}">${nombreAtributo}:</label>
  61.                                     <select id="${nombreAtributoLowerCase}${index}">
  62.                                         <option value="" selected="selected" disabled="disabled">Seleccionar ${nombreAtributo}</option>
  63.                                         ${valores.map(valor => `<option value="${valor}">${valor}</option>`).join('')}
  64.                                     </select>
  65.                                 </div>`;
  66.                       } else {
  67.                         return '';
  68.                       }
  69.                     }).join('') : ''}
  70.               </div>
  71.               <button class="agregar" data-info='${JSON.stringify({ nombre: producto.titulo, precio: producto.precio, atributos: producto.atributos, index: index })}'>Agregar al carrito</button>
  72.           </div>
  73.       `;
  74.  
  75.       contenedorProductos.appendChild(productoDiv);
  76.     });
  77.   }
  78.  
  79.   inicializarFuncionalidad();
  80. }
  81.  
  82. function generarCategorias(productos) {
  83.   const categorias = new Set(['Todos']);
  84.   productos.forEach(producto => {
  85.     if (producto.categorias && producto.categorias.length > 0) {
  86.       producto.categorias.forEach(categoria => {
  87.         if (categoria) {
  88.           categorias.add(categoria);
  89.         }
  90.       });
  91.     }
  92.   });
  93.  
  94.   const contenedorCategorias = document.getElementById('categorias-contenedor');
  95.   contenedorCategorias.innerHTML = '';
  96.  
  97.   if (categorias.size === 1) {
  98.     contenedorCategorias.style.display = 'none';
  99.   } else {
  100.     contenedorCategorias.style.display = '';
  101.     categorias.forEach((categoria, index) => {
  102.       let botonCategoria = document.createElement('button');
  103.       botonCategoria.textContent = categoria;
  104.       if (categoria === 'Todos') {
  105.         botonCategoria.classList.add('active');
  106.       }
  107.       botonCategoria.onclick = () => filtrarPorCategoria(categoria, botonCategoria);
  108.       contenedorCategorias.appendChild(botonCategoria);
  109.     });
  110.   }
  111. }
  112.  
  113. document.getElementById('buscar-producto').addEventListener('input', function(e) {
  114.   const busqueda = e.target.value.toLowerCase();
  115.   productosFiltrados = datosProductos.filter(producto => producto.titulo.toLowerCase().includes(busqueda));
  116.   renderizarProductos(productosFiltrados);
  117.   document.getElementById('limpiar-busqueda').style.display = busqueda ? '' : 'none';
  118.   reinicializarFuncionalidad();
  119. });
  120.  
  121. document.getElementById('limpiar-busqueda').addEventListener('click', function() {
  122.   document.getElementById('buscar-producto').value = '';
  123.   this.style.display = 'none';
  124.   productosFiltrados = datosProductos;
  125.   renderizarProductos(productosFiltrados);
  126.   reinicializarFuncionalidad();
  127. });
  128.  
  129. function filtrarPorCategoria(categoriaSeleccionada, botonClickeado) {
  130.   if (categoriaSeleccionada === 'Todos') {
  131.     renderizarProductos(datosProductos);
  132.   } else {
  133.     const productosFiltrados = datosProductos.filter(producto => producto.categorias.includes(categoriaSeleccionada));
  134.     renderizarProductos(productosFiltrados);
  135.   }
  136.   actualizarBotonActivo(botonClickeado);
  137.   reinicializarFuncionalidad();
  138. }
  139.  
  140. function actualizarBotonActivo(botonClickeado) {
  141.   const botonesCategoria = document.querySelectorAll('#categorias-contenedor button');
  142.   botonesCategoria.forEach(boton => {
  143.     boton.classList.remove('active');
  144.   });
  145.   botonClickeado.classList.add('active');
  146. }
  147.  
  148. function reinicializarFuncionalidad() {
  149.   eliminarEventosAgregarAlCarrito();
  150.   inicializarFuncionalidad();
  151. }
  152.  
  153. function eliminarEventosAgregarAlCarrito() {
  154.   const productos = document.querySelectorAll('.producto');
  155.   productos.forEach(producto => {
  156.     const agregarButton = producto.querySelector('.agregar');
  157.     agregarButton.removeEventListener('click', agregarProductoAlCarrito);
  158.   });
  159. }
  160.  
  161. const carritoContainer = document.getElementById('carrito-container');
  162. const carritoIcon = document.getElementById('carrito-icon');
  163. const cerrarCarrito = document.getElementById('cerrar-carrito');
  164. const carritoVacioMensaje = document.getElementById('carrito-vacio-mensaje');
  165.  
  166. carritoIcon.addEventListener('click', function () {
  167.   const carritoVisible = carritoContainer.style.right === '0px';
  168.   carritoContainer.style.right = carritoVisible ? '-350px' : '0px';
  169.  
  170.   if (carritoVisible) {
  171.     carritoVacioMensaje.style.display = 'none';
  172.   }
  173. });
  174.  
  175. cerrarCarrito.addEventListener('click', function () {
  176.   carritoContainer.style.right = '-350px';
  177. });
  178.  
  179. function desplazarCarrito() {
  180.   const anchoPantalla = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  181.  
  182.   if (anchoPantalla > 768) {
  183.     carritoContainer.style.right = '0px';
  184.     carritoVacioMensaje.style.display = 'none';
  185.   }
  186. }
  187.  
  188. function inicializarFuncionalidad() {
  189.   const productos = document.querySelectorAll('.producto');
  190.   const carritoLista = document.getElementById('carrito-lista');
  191.   const total = document.getElementById('total');
  192.   const carritoContador = document.getElementById('carrito-contador');
  193.   const carritoVacioMensaje = document.getElementById('carrito-vacio-mensaje');
  194.   const vaciarCarritoButton = document.getElementById('vaciar-carrito');
  195.  
  196.   function mostrarMensajeCarritoVacio() {
  197.     carritoVacioMensaje.style.display = carrito.length === 0 ? 'block' : 'none';
  198.   }
  199.  
  200.   function agregarProductoAlCarrito(info) {
  201.     const { nombre, precio, atributos, index } = JSON.parse(info || '{}');
  202.  
  203.     if (!validarAtributosSeleccionados(index)) {
  204.       return;
  205.     }
  206.  
  207.     let nombreConVariantes = `${nombre}`;
  208.     for (const [nombreAtributo, valorSeleccionado] of Object.entries(atributos)) {
  209.       const selectElement = document.getElementById(`${nombreAtributo.toLowerCase()}${index}`);
  210.       const valorSeleccionado = selectElement ? selectElement.value : null;
  211.  
  212.       if (valorSeleccionado) {
  213.         nombreConVariantes += ` - ${nombreAtributo}: ${valorSeleccionado}`;
  214.       }
  215.     }
  216.  
  217.     const producto = { nombre: nombreConVariantes, precio };
  218.     carrito.push(producto);
  219.  
  220.     const listItem = document.createElement('li');
  221.     listItem.textContent = `${nombreConVariantes} - $${formatearPrecio(producto.precio)}`;
  222.     const eliminarButton = document.createElement('a');
  223.     eliminarButton.innerHTML = '&amp;#xe051;';
  224.     eliminarButton.classList.add('eliminar');
  225.     eliminarButton.addEventListener('click', () => eliminarProductoDelCarrito(producto, listItem));
  226.     listItem.appendChild(eliminarButton);
  227.     carritoLista.appendChild(listItem);
  228.  
  229.     carritoTotal += precio;
  230.     total.textContent = formatearPrecio(carritoTotal);
  231.     carritoContador.textContent = carrito.length;
  232.     desplazarCarrito();
  233.     mostrarMensajeCarritoVacio();
  234.  
  235.     carritoIcon.classList.add('shaking');
  236.  
  237.     setTimeout(() => {
  238.       carritoIcon.classList.remove('shaking');
  239.     }, 500);
  240.   }
  241.  
  242.   function eliminarProductoDelCarrito(producto, listItem) {
  243.     const index = carrito.indexOf(producto);
  244.     if (index !== -1) {
  245.       carrito.splice(index, 1);
  246.       carritoLista.removeChild(listItem);
  247.       carritoTotal -= producto.precio;
  248.       total.textContent = formatearPrecio(carritoTotal);
  249.       carritoContador.textContent = carrito.length;
  250.       mostrarMensajeCarritoVacio();
  251.     }
  252.   }
  253.  
  254.   productos.forEach((producto, index) => {
  255.     const agregarButton = producto.querySelector('.agregar');
  256.     const info = agregarButton.getAttribute('data-info');
  257.  
  258.     agregarButton.addEventListener('click', () => {
  259.       agregarProductoAlCarrito(info);
  260.     });
  261.   });
  262.  
  263.   mostrarMensajeCarritoVacio();
  264. }
  265.  
  266. document.addEventListener('DOMContentLoaded', (event) => {
  267.   const enviarWhatsAppButton = document.getElementById('enviar-whatsapp');
  268.   enviarWhatsAppButton.addEventListener('click', () => {
  269.     const carritoTexto = carrito.map(producto => {
  270.       return `${producto.nombre} - $${formatearPrecio(producto.precio)}`;
  271.     }).join('\n');
  272.  
  273.     const mensajeWhatsApp = '*Mi Pedido:*\n' + carritoTexto + '\n*TOTAL: $' + formatearPrecio(carritoTotal) + '*';
  274.     // REEMPLAZAR NÚMERO WHATSAPP
  275.     const whatsappURL = `https://wa.me/529512345678?text=${encodeURIComponent(mensajeWhatsApp)}`; // REEMPLAZAR NÚMERO WHATSAPP
  276.     window.open(whatsappURL, '_blank');
  277.   });
  278. });
  279.  
  280. function validarAtributosSeleccionados(index) {
  281.   const selects = document.querySelectorAll(`#atributo${index} select`);
  282.   for (const select of selects) {
  283.     if (select.value === "") {
  284.       alert("Por favor, selecciona todas las opciones antes de agregar al carrito.");
  285.       return false;
  286.     }
  287.   }
  288.   return true;
  289. }
  290.  
  291. // Mover #carrito-container y #carrito-icon dentro de #page-container
  292. var pageContainer = document.getElementById('page-container');
  293. pageContainer.appendChild(carritoContainer);
  294. pageContainer.appendChild(carritoIcon);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement