Files
apps-registry/workloads/ecommerce/assets/js/app.js
T
devops 54d2f208ae
Build and Push Frontend / build (push) Successful in 1m57s
feat(ecommerce): release Ari Shopping Frontend v2
2026-07-18 16:34:01 -05:00

1 line
5.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(()=>{"use strict";const $=(s,r=document)=>r.querySelector(s),$$=(s,r=document)=>[...r.querySelectorAll(s)];const S={products:[],store:null,category:"Todos",query:"",sort:"featured",cart:JSON.parse(localStorage.getItem("ari-cart-v2")||"{}"),wish:JSON.parse(localStorage.getItem("ari-wish-v2")||"[]")};const E={grid:$("#grid"),cat:$("#categories"),search:$("#search"),sort:$("#sort"),summary:$("#summary"),empty:$("#empty"),drawer:$("#drawer"),overlay:$("#overlay"),items:$("#cartItems"),count:$("#cartCount"),total:$("#cartTotal"),toast:$("#toast"),card:$("#card")};const money=v=>new Intl.NumberFormat(S.store?.locale||"es-CO",{style:"currency",currency:S.store?.currency||"COP",maximumFractionDigits:0}).format(v);const norm=v=>String(v||"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");const p=id=>S.products.find(x=>x.id===id);function save(){localStorage.setItem("ari-cart-v2",JSON.stringify(S.cart));localStorage.setItem("ari-wish-v2",JSON.stringify(S.wish))}function toast(m){E.toast.textContent=m;E.toast.hidden=false;setTimeout(()=>E.toast.hidden=true,2600)}function categories(){E.cat.innerHTML=["Todos",...new Set(S.products.map(x=>x.category))].map(x=>`<button class="chip ${S.category===x?"active":""}" data-c="${x}">${x}</button>`).join("")}function list(){let q=norm(S.query),a=S.products.filter(x=>x.available!==false&&(S.category==="Todos"||x.category===S.category)&&(!q||norm([x.name,x.category,x.description,...(x.tags||[])].join(" ")).includes(q)));a.sort((x,y)=>S.sort==="asc"?x.price-y.price:S.sort==="desc"?y.price-x.price:S.sort==="new"?Number(y.new)-Number(x.new):Number(y.featured)-Number(x.featured));return a}function render(){let a=list();E.grid.innerHTML="";E.summary.textContent=`${a.length} producto${a.length===1?"":"s"} disponible${a.length===1?"":"s"}`;E.empty.hidden=!!a.length;a.forEach(x=>{let f=E.card.content.cloneNode(true),c=$(".card",f),img=$("img",f),w=$(".wish",f);img.src=x.images?.[0]||"assets/img/brand/favicon.svg";img.alt=x.name;$(".category",f).textContent=x.category;$("h3",f).textContent=x.name;$(".price strong",f).textContent=money(x.price);let d=$(".price del",f);x.compareAtPrice>x.price?d.textContent=money(x.compareAtPrice):d.remove();$(".body p",f).textContent=x.description;if(x.new)$(".badges",f).insertAdjacentHTML("beforeend",'<span class="badge">Nuevo</span>');if(x.compareAtPrice>x.price)$(".badges",f).insertAdjacentHTML("beforeend",`<span class="badge sale">-${Math.round((1-x.price/x.compareAtPrice)*100)}%</span>`);w.classList.toggle("active",S.wish.includes(x.id));w.textContent=S.wish.includes(x.id)?"♥":"♡";w.onclick=()=>{S.wish=S.wish.includes(x.id)?S.wish.filter(i=>i!==x.id):[...S.wish,x.id];save();render();toast(S.wish.includes(x.id)?"Guardado en favoritos":"Eliminado de favoritos")};$(".add",f).onclick=()=>add(x.id);E.grid.append(f)});cart()}function add(id){S.cart[id]=(S.cart[id]||0)+1;save();cart();toast(`${p(id).name} agregado`)}function cart(){let a=Object.entries(S.cart).map(([id,q])=>({x:p(id),q})).filter(i=>i.x),n=a.reduce((s,i)=>s+i.q,0),t=a.reduce((s,i)=>s+i.x.price*i.q,0);E.count.textContent=n;E.total.textContent=money(t);E.items.innerHTML=a.length?a.map(i=>`<article class="line" data-id="${i.x.id}"><img src="${i.x.images[0]}" alt=""><div><strong>${i.x.name}</strong><small>${money(i.x.price)}</small><div class="qty"><button data-d="-1"></button><span>${i.q}</span><button data-d="1">+</button></div></div><button class="remove">×</button></article>`).join(""):'<div class="drawerEmpty">Tu carrito está vacío.</div>';$$('[data-d]',E.items).forEach(b=>b.onclick=()=>{let id=b.closest('[data-id]').dataset.id;S.cart[id]+=Number(b.dataset.d);if(S.cart[id]<=0)delete S.cart[id];save();cart()});$$('.remove',E.items).forEach(b=>b.onclick=()=>{delete S.cart[b.closest('[data-id]').dataset.id];save();cart()})}function open(){E.drawer.classList.add("open");E.overlay.hidden=false;document.body.classList.add("lock")}function close(){E.drawer.classList.remove("open");E.overlay.hidden=true;document.body.classList.remove("lock")}function order(){let a=Object.entries(S.cart).map(([id,q])=>({x:p(id),q})).filter(i=>i.x);if(!a.length)return;let total=a.reduce((s,i)=>s+i.x.price*i.q,0),m=[`Hola ${S.store.brand} 👋`,`Quiero confirmar disponibilidad:`,"",...a.map(i=>`• ${i.q} x ${i.x.name}${money(i.x.price*i.q)}`),"",`Total estimado: ${money(total)}`,"","Nombre:","Ciudad:"].join("\n"),num=String(S.store.whatsappNumber||"").replace(/\D/g,"");if(num)window.open(`https://wa.me/${num}?text=${encodeURIComponent(m)}`,"_blank");else navigator.clipboard.writeText(m).then(()=>toast("Pedido copiado. Configura WhatsApp en data/store.json"))}async function init(){let [st,pr]=await Promise.all([fetch("data/store.json",{cache:"no-store"}).then(r=>r.json()),fetch("data/products.json",{cache:"no-store"}).then(r=>r.json())]);S.store=st;S.products=pr.products||[];categories();render()}E.search.oninput=e=>{S.query=e.target.value;render()};E.sort.onchange=e=>{S.sort=e.target.value;render()};E.cat.onclick=e=>{let b=e.target.closest('[data-c]');if(!b)return;S.category=b.dataset.c;categories();render()};$("#cartOpen").onclick=open;$("#cartClose").onclick=close;E.overlay.onclick=close;$("#clearCart").onclick=()=>{S.cart={};save();cart()};$("#checkout").onclick=order;init().catch(e=>{console.error(e);E.summary.textContent="Error cargando catálogo"})})();