app.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. //--- Imports ---
  2. import { getOnlineUserCount, getUserList } from './service/chat.js';
  3. import { getProducts, sendOrder } from './service/product.js';
  4. import { login, existsTable, guestLogin, getTableFromUrl } from './service/auth.js';
  5. import { createGlobalLoader, showGlobalLoader, hideGlobalLoader } from './utils/loader.js';
  6. import { updateProgress, claimReward, getProgress } from './utils/progressBar.js';
  7. import { showError } from './utils/error.js';
  8. import { addHistoryRow, setupShoppingCart } from './utils/shoppingCart.js';
  9. import { hideGUI, showGUI } from './utils/gui.js';
  10. import { smartSearch } from './utils/searching.js';
  11. import { getUserData } from './service/user.js';
  12. import { getComment, COMMENT_TYPES } from './utils/get_comment.js';
  13. import { imageObserver } from './utils/observer.js';
  14. // --- Variables Globales ---
  15. // --- User Data ---
  16. let userId = -1;
  17. let userName = "Invitado";
  18. let chatUserName = "guest";
  19. let userTable = null;
  20. let userToken = null;
  21. let chatWebsocket = null;
  22. let isGuest = false;
  23. // --- Products & Cart ---
  24. let Allproducts = [];
  25. let cart = [];
  26. let itsEmpty = true;
  27. let cacheMode = false;
  28. // --- Configuration ---
  29. const favoriteCategories = ["Shop", "Pizzas Familiares", "Pizza Medianas"];
  30. const productPriority = {
  31. "Shop": [6, 12, 163, 168, 15, 665, 1],
  32. "Cervezas": [17],
  33. "Coctelería Gin Klein": [655],
  34. "Pizzas Familiares": [27],
  35. "Pizza Medianas": [2]
  36. }
  37. const userColors = [
  38. "text-red-500", "text-red-600", "text-rose-500", "text-rose-600",
  39. "text-orange-500", "text-orange-600", "text-amber-500", "text-amber-600",
  40. "text-yellow-500", "text-yellow-600", "text-lime-500", "text-lime-600",
  41. "text-green-500", "text-green-600", "text-emerald-500", "text-emerald-600",
  42. "text-teal-500", "text-teal-600", "text-cyan-500", "text-cyan-600",
  43. "text-sky-500", "text-sky-600", "text-blue-500", "text-blue-600",
  44. "text-indigo-500", "text-indigo-600",
  45. "text-violet-500", "text-violet-600", "text-purple-500", "text-purple-600",
  46. "text-fuchsia-500", "text-fuchsia-600", "text-pink-500", "text-pink-600",
  47. "text-gray-500", "text-gray-600", "text-zinc-500", "text-zinc-600",
  48. "text-neutral-500", "text-neutral-600", "text-stone-500", "text-stone-600"
  49. ];
  50. const productsWithVariety = {
  51. "480": ["Frambuesa", "Mango", "Maracuyá", "Piña", "Tradicional"]
  52. }
  53. //--- Elementos del DOM ---
  54. const productListElement = document.getElementById("productList");
  55. const cartItemsElement = document.getElementById("cartItems");
  56. const cartTotalElement = document.getElementById("cartTotal");
  57. const emptyCartTextElement = document.getElementById("emptyCartText");
  58. const checkoutButton = document.getElementById("checkoutButton");
  59. const originalCheckoutButtonText = checkoutButton ? checkoutButton.textContent : "Finalizar Pedido";
  60. const cartCountElement = document.getElementById("cartCount");
  61. // --- Chat Elements ---
  62. const chatMessagesElement = document.getElementById("chatMessages");
  63. const chatInputElement = document.getElementById("chatInput");
  64. const chatForm = document.getElementById("chatForm");
  65. const userList = document.getElementById("userList")
  66. const onlineUsersElement = document.querySelector("#onlineUsers h4");
  67. // --- Reward Elements ---
  68. const rewardBtn = document.getElementById('rewardBtn');
  69. const rewardModal = document.getElementById('rewardModal');
  70. const closeRewardModal = document.getElementById('closeRewardModal');
  71. const closeSuccessRewardModalButton = document.getElementById('closeSuccessRewardModal');
  72. const cancelRewardBtn = document.getElementById('cancelRewardBtn');
  73. const acceptTermsCheckbox = document.getElementById('acceptTermsCheckbox');
  74. const claimRewardBtn = document.getElementById('claimRewardBtn');
  75. const rewardContainer = document.getElementById('rewardContainer'); // ID NECESARIO EN HTML
  76. //--- Inicialización y Configuración ---
  77. async function initializeApp() {
  78. createGlobalLoader();
  79. showGlobalLoader("Conectando...");
  80. // 1. Obtener Mesa
  81. const urlTable = getTableFromUrl();
  82. console.log(urlTable);
  83. if (!urlTable) {
  84. showError("Mesa no especificada en URL.");
  85. console.warn("Mesa no especificada en URL.");
  86. hideGlobalLoader();
  87. return;
  88. }
  89. userTable = parseInt(urlTable);
  90. // 2. Verificar Cache
  91. const isCacheValid = await checkCache();
  92. if (!isCacheValid) {
  93. // 3. Guest Mode
  94. try {
  95. const guestData = await guestLogin();
  96. userToken = guestData.token;
  97. isGuest = true;
  98. userName = "Invitado";
  99. userId = 0; // ID temporal para guest
  100. // UI Guest
  101. if (typeof showToast === "function") {
  102. setTimeout(() => showToast("Modo invitado. Inicia sesión para más funciones."), 1000);
  103. setTimeout(() => showToast(`Mesa: ${userTable}`), 2000);
  104. }
  105. } catch (error) {
  106. showError("Error crítico de conexión.");
  107. hideGlobalLoader();
  108. return;
  109. }
  110. }
  111. // Configuración UI según estado
  112. updateUIForUserType();
  113. // Inicializar Componentes
  114. if (!isGuest) {
  115. chatUserName = userName.split(" ")[0].toLowerCase() + "_mesa" + userTable;
  116. initializeChat();
  117. initializeWebSocket();
  118. }
  119. await initializeProducts();
  120. await renderProducts(Allproducts);
  121. setupSearchListener();
  122. setupTabSwitching();
  123. updateCartDisplay();
  124. // Solo cargar historial si es usuario registrado
  125. if (!isGuest) {
  126. setupShoppingCart(userId, userToken, userName);
  127. }
  128. setupBasicListeners();
  129. initializeLoginModal();
  130. showGUI();
  131. hideGlobalLoader();
  132. }
  133. function updateUIForUserType() {
  134. const loginBtn = document.getElementById('openLoginBtn');
  135. const logoutBtn = document.getElementById('headerLogoutBtn'); // Nuevo botón header
  136. const userNameDisplay = document.getElementById('headerUserName'); // Span del nombre
  137. const historyTable = document.getElementById('historyTable'); // Tablero de historial
  138. if (isGuest) {
  139. // UI GUEST
  140. if (rewardContainer) rewardContainer.classList.add("hidden");
  141. if (loginBtn) loginBtn.classList.remove("hidden");
  142. if (logoutBtn) logoutBtn.classList.add("hidden");
  143. if (userNameDisplay) userNameDisplay.classList.add("hidden");
  144. if (historyTable) historyTable.parentElement.parentElement.classList.add("hidden");
  145. } else {
  146. // UI LOGUEADO
  147. if (rewardContainer) rewardContainer.classList.remove("hidden");
  148. if (loginBtn) loginBtn.classList.add("hidden");
  149. if (logoutBtn) logoutBtn.classList.remove("hidden");
  150. if (userNameDisplay) {
  151. // Mostramos solo el primer nombre para ahorrar espacio
  152. userNameDisplay.textContent = userName.split(" ")[0];
  153. userNameDisplay.classList.remove("hidden");
  154. }
  155. }
  156. }
  157. function initializeLoginModal() {
  158. const sessionModal = document.getElementById('sessionModal');
  159. const loginForm = document.getElementById('loginForm');
  160. // const logoutBtn = document.getElementById('logoutBtn'); // Ya no usamos el del modal
  161. const openLoginBtn = document.getElementById('openLoginBtn');
  162. const headerLogoutBtn = document.getElementById('headerLogoutBtn'); // Nuevo botón header
  163. // 1. Abrir modal (Guest intenta loguearse)
  164. if (openLoginBtn) {
  165. openLoginBtn.addEventListener('click', () => {
  166. document.querySelector("#emailInputContainer").classList.remove("hidden");
  167. document.querySelector("#pinInputContainer").classList.remove("hidden");
  168. const tableInput = document.getElementById("tableInput");
  169. if(tableInput) {
  170. tableInput.value = userTable;
  171. tableInput.readOnly = true;
  172. }
  173. // Ocultamos logout del modal si existiera, limpiamos UI
  174. const modalLogout = document.getElementById('logoutBtn');
  175. if(modalLogout) modalLogout.classList.add("hidden");
  176. document.querySelector("#loginTitle").textContent = "¡Bienvenido!";
  177. sessionModal.classList.remove('hidden');
  178. });
  179. }
  180. // 2. Funcionalidad Cerrar Sesión (Desde el Header)
  181. if (headerLogoutBtn) {
  182. headerLogoutBtn.addEventListener('click', () => {
  183. if(confirm("¿Estás seguro que deseas cerrar sesión?")) {
  184. setCookie("userToken", "", -1);
  185. window.location.reload();
  186. }
  187. });
  188. }
  189. // 3. Submit del Login (Igual que antes)
  190. loginForm.addEventListener('submit', async (event) => {
  191. event.preventDefault();
  192. showGlobalLoader("Iniciando sesión...");
  193. const fd = new FormData(loginForm);
  194. const email = fd.get('email').trim();
  195. const pin = fd.get('pin').trim();
  196. if (!email || !pin) {
  197. showError("Completa todos los campos.");
  198. hideGlobalLoader();
  199. return;
  200. }
  201. try {
  202. const data = await login(email, pin, userTable);
  203. userToken = data.token;
  204. userName = data.name;
  205. userId = data.id;
  206. isGuest = false;
  207. setCookie("userToken", userToken, 7);
  208. updateProgress(data.reward_progress || 0);
  209. sessionModal.classList.add('hidden');
  210. initializeApp();
  211. } catch (error) {
  212. console.error(error);
  213. hideGlobalLoader();
  214. }
  215. });
  216. // Cerrar modal click afuera
  217. sessionModal.addEventListener('click', (e) => {
  218. if (e.target === sessionModal && (isGuest || userId !== -1)) {
  219. sessionModal.classList.add('hidden');
  220. }
  221. });
  222. }
  223. // ... (Resto de funciones WebSocket y Chat igual, solo se ejecutan si !isGuest) ...
  224. function initializeWebSocket() {
  225. if (isGuest) return; // Seguridad extra
  226. if (!chatWebsocket) {
  227. const wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
  228. chatWebsocket = new WebSocket(`${wsProtocol}://${location.host}/api/chat/ws?token=${userToken}`);
  229. chatWebsocket.onopen = () => {
  230. chatWebsocket.send(JSON.stringify({
  231. type: "join",
  232. username: chatUserName
  233. }));
  234. }
  235. getOnlineUserCount(userToken).then(count => {
  236. onlineUsersElement.innerText = `${count} Usuario${count !== 1 ? 's' : ''} en línea`;
  237. });
  238. chatWebsocket.onmessage = (event) => {
  239. const data = JSON.parse(event.data);
  240. if (data.type === "message") displayChatMessage(data.username, data.message);
  241. else if (data.type === "join") newUserInChat(data.username);
  242. else if (data.type === "leave") userLeftChat(data.username);
  243. else if (data.type === "mentioned") {
  244. if (data.username && data.username !== chatUserName) return;
  245. showMentioned();
  246. }
  247. else if (data.type === "ping") {
  248. chatWebsocket.send(JSON.stringify({ type: "pong" }));
  249. }
  250. }
  251. }
  252. }
  253. function initializeChat() {
  254. if (isGuest || !chatForm) return;
  255. // ... (Código original de initializeChat) ...
  256. chatForm.addEventListener("submit", (event) => {
  257. event.preventDefault();
  258. if (chatInputElement.value.trim() === "") return;
  259. chatForm.querySelector("button").animate(
  260. [{ transform: 'scale(1)' }, { transform: 'scale(0.9)' }, { transform: 'scale(1)' }],
  261. { duration: 200, iterations: 1, easing: 'ease-in-out' }
  262. )
  263. sendMessage(chatInputElement.value.trim());
  264. chatInputElement.value = "";
  265. });
  266. let debounceTimer;
  267. chatInputElement.addEventListener("input", () => {
  268. const lastWord = chatInputElement.value.split(" ").at(-1);
  269. if (lastWord.trim().startsWith("@")) {
  270. clearTimeout(debounceTimer);
  271. debounceTimer = setTimeout(async () => {
  272. userList.classList.remove("hidden");
  273. let users = await getUserList(lastWord.trim().substring(1), userToken);
  274. users = users.filter(u => u !== chatUserName);
  275. users.push("IAKlein");
  276. userList.innerHTML = "";
  277. users.forEach(user => {
  278. const userItem = document.createElement("button");
  279. userItem.type = "button";
  280. userItem.onclick = () => {
  281. const inputValue = chatInputElement.value;
  282. const lastWordIndex = inputValue.lastIndexOf(lastWord);
  283. if (lastWordIndex !== -1) {
  284. chatInputElement.value = inputValue.slice(0, lastWordIndex) + `@${user}` + inputValue.slice(lastWordIndex + lastWord.length);
  285. }
  286. userList.classList.add("hidden");
  287. chatInputElement.value += " ";
  288. chatInputElement.focus();
  289. };
  290. const color = getUserColor(user);
  291. userItem.classList.add("list-user-name", "cursor-pointer", color);
  292. userItem.textContent = user;
  293. userList.appendChild(userItem);
  294. });
  295. }, 300);
  296. } else {
  297. userList.classList.add("hidden");
  298. clearTimeout(debounceTimer);
  299. }
  300. });
  301. }
  302. // ... (Funciones sendMessage, userMentioned, displayChatMessage, etc. iguales) ...
  303. async function sendMessage(message) {
  304. if (chatWebsocket) {
  305. if (chatWebsocket.readyState !== WebSocket.OPEN) {
  306. chatWebsocket = null;
  307. initializeWebSocket();
  308. }
  309. await chatWebsocket.send(JSON.stringify({
  310. type: "message",
  311. username: chatUserName,
  312. message: message
  313. }));
  314. let mentions_repeated = [];
  315. await setTimeout(() => {
  316. const mentionRegex = /@([a-zA-Z0-9_]+_mesa\d+|IAKlein)/g;
  317. const mentions = message.match(mentionRegex);
  318. if (mentions) {
  319. mentions.forEach(mention => {
  320. const username = mention.slice(1);
  321. const exist = mentions_repeated.find(u => u === username);
  322. if (exist || username === chatUserName) return;
  323. mentions_repeated.push(username);
  324. if (username === "IAKlein"){
  325. sendMessageToAI(message);
  326. }else {
  327. userMentioned(username);
  328. }
  329. });
  330. }
  331. }, 1000);
  332. }
  333. }
  334. function userMentioned(username) {
  335. chatWebsocket.send(JSON.stringify({
  336. type: "mention",
  337. username: username
  338. }));
  339. }
  340. function showMentioned(){
  341. const chatButton = document.querySelector("#chatIcon span");
  342. if (chatButton) {
  343. chatButton.classList.remove("hidden");
  344. chatButton.animate(
  345. [{ transform: 'scale(1)' }, { transform: 'scale(1.5)' }, { transform: 'scale(1)' }],
  346. { duration: 300, iterations: 3, easing: 'ease-in-out' }
  347. );
  348. }
  349. }
  350. window.hideMentioned = function(){
  351. const chatButton = document.querySelector("#chatIcon span");
  352. if (chatButton) chatButton.classList.add("hidden");
  353. }
  354. function getUserColor(username) {
  355. const hash = [...username].reduce((acc, char) => acc + char.charCodeAt(0), 0);
  356. return userColors[hash % userColors.length];
  357. }
  358. function displayChatMessage(sender, message, time = undefined) {
  359. let realtime = `[${time ? time : new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  360. let messageTemplate = chatMessagesElement.querySelector("#chatMessageTemplate");
  361. if (!messageTemplate) return;
  362. let messageClone = messageTemplate.content.cloneNode(true).firstElementChild;
  363. messageClone.querySelector(".chat-message-text").innerHTML = message;
  364. messageClone.querySelector(".chat-message-time").innerHTML = realtime;
  365. messageClone.querySelector(".chat-message-user").innerHTML = sender
  366. messageClone.querySelector(".chat-message-user").classList.add(getUserColor(sender));
  367. chatMessagesElement.appendChild(messageClone);
  368. chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
  369. }
  370. function newUserInChat(userName) {
  371. let userTemplate = chatMessagesElement.querySelector("#systemMessageTemplate");
  372. if (!userTemplate) return;
  373. const realtime = `[${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  374. let userClone = userTemplate.content.cloneNode(true).firstElementChild;
  375. userClone.classList.add("text-green-600");
  376. userClone.querySelector(".chat-message-time").innerHTML = realtime;
  377. userClone.querySelector(".chat-message-text").innerHTML = `*** ${userName} se ha unido al chat`;
  378. chatMessagesElement.appendChild(userClone);
  379. }
  380. function userLeftChat(userName) {
  381. let userTemplate = chatMessagesElement.querySelector("#systemMessageTemplate");
  382. if (!userTemplate) return;
  383. const realtime = `[${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  384. let userClone = userTemplate.content.cloneNode(true).firstElementChild;
  385. userClone.classList.add("text-red-600");
  386. userClone.querySelector(".chat-message-time").innerHTML = realtime;
  387. userClone.querySelector(".chat-message-text").innerHTML = `*** ${userName} se ha ido del chat`;
  388. chatMessagesElement.appendChild(userClone);
  389. }
  390. function sendMessageToAI(userMessage) {
  391. if (userMessage === "") return;
  392. const messages = Array.from(chatMessagesElement.querySelectorAll(".chat-message")).slice(-10);
  393. let formattedMessages = messages.map(msg => {
  394. const sender = msg.querySelector(".chat-message-user").textContent;
  395. const content = msg.querySelector(".chat-message-text").innerHTML;
  396. return { user: sender, content: content };
  397. });
  398. chatWebsocket.send(JSON.stringify({
  399. type: "ai_message",
  400. username: chatUserName,
  401. messages: formattedMessages
  402. }));
  403. chatInputElement.value = "";
  404. }
  405. //--- Manejo de Pestañas ---
  406. window.switchTab = function(targetTabId) {
  407. // BLOQUEO CHAT PARA GUEST
  408. if (targetTabId === 'chatTab' && isGuest) {
  409. if (typeof showToast === "function") showToast("Inicia sesión para usar el chat");
  410. // Opcional: abrir modal login
  411. const openLoginBtn = document.getElementById('openLoginBtn');
  412. if(openLoginBtn) openLoginBtn.click();
  413. return;
  414. }
  415. const targetButton = document.querySelector(`[data-target="${targetTabId}"]`);
  416. if (!targetButton) return;
  417. if (targetTabId === "chatTab") window.hideMentioned();
  418. const active = document.querySelector(':not(.hidden)[data-tab]');
  419. if (!active) return;
  420. const activeIndex = active.dataset.index;
  421. const to = document.querySelector(`#${targetTabId}[data-tab]`);
  422. if (!to) return;
  423. const toIndex = to.dataset.index;
  424. if (activeIndex === toIndex || transitioning) return;
  425. const buttons = document.querySelectorAll('.tab-btn');
  426. buttons.forEach(button => button.classList.remove('active'));
  427. targetButton.classList.add('active');
  428. performTabTransition(active, to, activeIndex, toIndex, targetButton);
  429. };
  430. // ... (setupTabSwitching, performTabTransition, setCookie, getCookie sin cambios) ...
  431. // Tab switching variables
  432. const animation_time = 200;
  433. let transitioning = false;
  434. function performTabTransition(active, to, activeIndex, toIndex, targetButton) {
  435. active.style.height = "100%";
  436. active.style.width = "100vw";
  437. to.style.height = "100%";
  438. to.style.width = "100vw";
  439. to.style.zIndex = "1";
  440. active.style.zIndex = "0";
  441. transitioning = true;
  442. const otherTabs = document.querySelectorAll('[data-tab]');
  443. otherTabs.forEach(tab => {
  444. if (tab !== active && tab !== to) {
  445. tab.classList.add('hidden');
  446. tab.classList.remove(`animate-[slideLeft_${animation_time}ms_ease-out]`, `animate-[slideRight_${animation_time}ms_ease-out]`);
  447. tab.classList.remove(`animate-[slideLeftIn_${animation_time}ms_ease-out]`, `animate-[slideRightIn_${animation_time}ms_ease-out]`);
  448. }
  449. });
  450. to.classList.remove('hidden');
  451. if (activeIndex < toIndex) {
  452. active.classList.add(`animate-[slideLeft_${animation_time}ms_ease-out]`);
  453. to.classList.add(`animate-[slideRightIn_${animation_time}ms_ease-out]`);
  454. } else if (activeIndex > toIndex) {
  455. active.classList.add(`animate-[slideRight_${animation_time}ms_ease-out]`);
  456. to.classList.add(`animate-[slideLeftIn_${animation_time}ms_ease-out]`);
  457. }
  458. setTimeout(() => {
  459. active.classList.remove(`animate-[slideLeft_${animation_time}ms_ease-out]`, `animate-[slideRight_${animation_time}ms_ease-out]`);
  460. active.classList.add('hidden');
  461. to.classList.remove(`animate-[slideLeftIn_${animation_time}ms_ease-out]`, `animate-[slideRightIn_${animation_time}ms_ease-out]`);
  462. transitioning = false;
  463. }, animation_time);
  464. const title = targetButton.dataset.title;
  465. if (title) {
  466. const mainTitle = document.getElementById('mainTitle');
  467. if (mainTitle) mainTitle.textContent = title;
  468. }
  469. }
  470. function setupTabSwitching() {
  471. const buttons = document.querySelectorAll('.tab-btn');
  472. buttons.forEach(btn => {
  473. btn.addEventListener('click', () => {
  474. const target = btn.dataset.target;
  475. window.switchTab(target);
  476. });
  477. });
  478. }
  479. function setCookie(name, value, days) {
  480. const expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
  481. document.cookie = `${name}=${value}; expires=${expires}; path=/`;
  482. }
  483. function getCookie(name) {
  484. const cookies = document.cookie.split('; ');
  485. for (const cookie of cookies) {
  486. const [cookieName, cookieValue] = cookie.split('=');
  487. if (cookieName === name) return decodeURIComponent(cookieValue);
  488. }
  489. return null;
  490. }
  491. function formatPrice(price) {
  492. return price.toLocaleString("es-CL", { style: "currency", currency: "CLP" });
  493. }
  494. // ... (Funciones de Productos, renderizado y carrito permanecen igual. addToCart usa isGuest para determinar funcionalidades si fuera necesario, pero por ahora todos compran) ...
  495. // (initializeProducts, createCategories, renderProducts, renderProductsWithAnimation, addComment, addToCart, removeFromCart, calculateTotal, updateCartDisplay, processOrder)
  496. async function initializeProducts() {
  497. Allproducts = await getProducts(userToken);
  498. }
  499. // [Incluir el resto de funciones de productos y carrito aquí, sin cambios, ya que funcionan con userToken sea guest o user]
  500. async function createCategories(products) {
  501. let categories = new Set(products.map(product => product.type || "Sin categoría"));
  502. categories = Array.from(categories).sort((a, b) => a.localeCompare(b));
  503. for (const category of [...favoriteCategories].reverse()) {
  504. if (categories.includes(category)) {
  505. categories = categories.filter(cat => cat !== category);
  506. categories.unshift(category);
  507. }
  508. }
  509. if (!productListElement) return;
  510. const categoryContainers = categories.map(category => {
  511. const container = document.createElement("div");
  512. container.classList.add("category-container", "mb-8", "p-4");
  513. const title = document.createElement("h2");
  514. title.classList.add("category-title", "text-3xl", "font-bold", "border-b-2", "pb-3", "mb-4");
  515. const lastChar = category.charAt(category.length - 1).toLowerCase();
  516. const pluralSuffix = ["a", "e", "i", "o", "u", "á", "é", "í", "ó", "ú", "p"].includes(lastChar)
  517. ? "s" : lastChar === "s" ? "" : "es";
  518. title.textContent = category + pluralSuffix;
  519. container.appendChild(title);
  520. const productList = document.createElement("div");
  521. productList.classList.add("product-list", "space-y-6");
  522. productList.id = `productList-${category}`;
  523. container.appendChild(productList);
  524. productListElement.appendChild(container);
  525. return { category, container: productList };
  526. });
  527. return categoryContainers;
  528. }
  529. async function renderProducts(products, groupInCategories = true, searchTerm = "") {
  530. if (!productListElement) return;
  531. const template = document.getElementById("product-card-template");
  532. if (!template) return;
  533. productListElement.innerHTML = "";
  534. let categoryContainers = [];
  535. if (groupInCategories) {
  536. categoryContainers = await createCategories(products);
  537. } else {
  538. categoryContainers = [{ category: searchTerm, container: productListElement }];
  539. }
  540. if (products.length === 0) {
  541. const noProductsMessage = document.createElement("p");
  542. noProductsMessage.textContent = "No hay productos disponibles.";
  543. productListElement.appendChild(noProductsMessage);
  544. return;
  545. }
  546. for (const { category, container } of categoryContainers) {
  547. let productsInCategory = groupInCategories ? products.filter(product => product.type === category) : products;
  548. if (favoriteCategories.includes(category) && productPriority[category]) {
  549. productsInCategory.sort((a, b) => {
  550. const aIndex = productPriority[category].indexOf(a.id);
  551. const bIndex = productPriority[category].indexOf(b.id);
  552. if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
  553. if (aIndex !== -1 && bIndex === -1) return -1;
  554. if (aIndex === -1 && bIndex !== -1) return 1;
  555. return 0;
  556. });
  557. }
  558. if (productsInCategory.length === 0) continue;
  559. productsInCategory.forEach(product => {
  560. const clone = template.content.cloneNode(true).firstElementChild;
  561. clone.querySelector(".product-type").textContent = product.type || "Sin categoría";
  562. clone.querySelector(".product-name").textContent = product.name;
  563. clone.querySelector(".product-description").textContent = product.description;
  564. clone.querySelector(".product-price").textContent = formatPrice(product.price);
  565. const image = clone.querySelector(".product-image");
  566. image.dataset.src = product.image
  567. const addBtn = clone.querySelector(".add-to-cart-btn");
  568. addBtn.dataset.productId = product.id;
  569. addBtn.addEventListener('click', (event) => {
  570. const productId = parseInt(event.target.dataset.productId);
  571. addToCart(productId, event.target);
  572. });
  573. container.appendChild(clone);
  574. imageObserver.observe(image);
  575. });
  576. }
  577. }
  578. async function renderProductsWithAnimation(products, groupInCategories = true, searchTerm = "") {
  579. if (!productListElement) return;
  580. const template = document.getElementById("product-card-template");
  581. if (!template) return;
  582. productListElement.style.opacity = "0";
  583. productListElement.style.transform = "scale(0.95)";
  584. setTimeout(async () => {
  585. productListElement.innerHTML = "";
  586. let categoryContainers = [];
  587. if (groupInCategories) {
  588. categoryContainers = await createCategories(products);
  589. } else {
  590. categoryContainers = [{ category: searchTerm, container: productListElement }];
  591. }
  592. categoryContainers.sort((a, b) => {
  593. const aIndex = favoriteCategories.indexOf(a.category);
  594. const bIndex = favoriteCategories.indexOf(b.category);
  595. return aIndex - bIndex;
  596. });
  597. if (products.length === 0) {
  598. const noProductsMessage = document.createElement("p");
  599. noProductsMessage.textContent = "No hay productos disponibles.";
  600. noProductsMessage.style.opacity = "0";
  601. noProductsMessage.style.transform = "translateY(20px)";
  602. noProductsMessage.style.transition = "opacity 0.3s ease, transform 0.3s ease";
  603. productListElement.appendChild(noProductsMessage);
  604. productListElement.style.opacity = "1";
  605. productListElement.style.transform = "scale(1)";
  606. setTimeout(() => {
  607. noProductsMessage.style.opacity = "1";
  608. noProductsMessage.style.transform = "translateY(0)";
  609. }, 50);
  610. return;
  611. }
  612. let animationDelay = 0;
  613. for (const { category, container } of categoryContainers) {
  614. let productsInCategory = groupInCategories ? products.filter(product => product.type === category) : products;
  615. if (productsInCategory.length === 0) continue;
  616. if (favoriteCategories.includes(category) && productPriority[category]) {
  617. productsInCategory.sort((a, b) => {
  618. const aIndex = productPriority[category].indexOf(a.id);
  619. const bIndex = productPriority[category].indexOf(b.id);
  620. if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
  621. if (aIndex !== -1 && bIndex === -1) return -1;
  622. if (aIndex === -1 && bIndex !== -1) return 1;
  623. return 0;
  624. });
  625. }
  626. productsInCategory.forEach((product, index) => {
  627. const clone = template.content.cloneNode(true).firstElementChild;
  628. clone.querySelector(".product-type").textContent = product.type || "Sin categoría";
  629. clone.querySelector(".product-name").textContent = product.name;
  630. clone.querySelector(".product-description").textContent = product.description;
  631. clone.querySelector(".product-price").textContent = formatPrice(product.price);
  632. const image = clone.querySelector(".product-image");
  633. image.dataset.src = product.image
  634. const addBtn = clone.querySelector(".add-to-cart-btn");
  635. addBtn.dataset.productId = product.id;
  636. addBtn.addEventListener('click', (event) => {
  637. const productId = parseInt(event.target.dataset.productId);
  638. addToCart(productId, event.target);
  639. });
  640. const productCard = clone.children[0];
  641. productCard.style.opacity = "0";
  642. productCard.style.transform = "translateY(20px) scale(0.95)";
  643. productCard.style.transition = "opacity 0.4s ease, transform 0.4s ease";
  644. container.appendChild(clone);
  645. imageObserver.observe(image);
  646. setTimeout(() => {
  647. productCard.style.opacity = "1";
  648. productCard.style.transform = "translateY(0) scale(1)";
  649. }, animationDelay);
  650. animationDelay += 50;
  651. });
  652. }
  653. productListElement.style.opacity = "1";
  654. productListElement.style.transform = "scale(1)";
  655. }, 150);
  656. }
  657. window.addComment = async function(productId) {
  658. const cartItem = cart.find(p => p.id === productId);
  659. if (!cartItem) return;
  660. const comment = await getComment(COMMENT_TYPES.LIBRE, [cartItem.comment]).catch(e => console.error(e));
  661. if (!comment) return;
  662. cartItem.comment += ` ${comment}`;
  663. }
  664. window.addToCart = async function(productId, buttonElement = null) {
  665. let comment = "";
  666. if (productsWithVariety[String(productId)]) {
  667. comment = await getComment(COMMENT_TYPES.DESPLEGABLE, productsWithVariety[String(productId)]);
  668. }
  669. const product = Allproducts.find(p => p.id === productId);
  670. if (!product) return;
  671. const cartItem = cart.find(item => item.id === productId);
  672. if (cartItem) {
  673. cartItem.quantity++;
  674. if (comment ) cartItem.comment += `, ${comment}`;
  675. } else {
  676. cart.push({ ...product, quantity: 1, comment });
  677. }
  678. if (buttonElement) {
  679. const originalHTML = buttonElement.innerHTML;
  680. buttonElement.textContent = "✔ Agregado!";
  681. buttonElement.disabled = true;
  682. setTimeout(() => {
  683. buttonElement.innerHTML = originalHTML;
  684. buttonElement.disabled = false;
  685. }, 300);
  686. }
  687. updateCartDisplay();
  688. if (typeof showToast === "function") showToast(`${product.name} agregado al carrito`);
  689. };
  690. window.removeFromCart = function(productId, removeAll = false) {
  691. const itemIndex = cart.findIndex(item => item.id === productId);
  692. if (itemIndex > -1) {
  693. if (removeAll || cart[itemIndex].quantity === 1) {
  694. cart.splice(itemIndex, 1);
  695. } else {
  696. cart[itemIndex].quantity--;
  697. }
  698. }
  699. updateCartDisplay();
  700. };
  701. function calculateTotal() {
  702. if (!cartTotalElement) return;
  703. const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  704. cartTotalElement.textContent = formatPrice(total);
  705. }
  706. function updateCartDisplay() {
  707. if (!cartItemsElement || !emptyCartTextElement || !checkoutButton || !cartCountElement) return;
  708. cartItemsElement.innerHTML = "";
  709. cartCountElement.textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
  710. if (cart.length === 0) {
  711. cartCountElement.classList.add("hidden");
  712. emptyCartTextElement.classList.remove("hidden");
  713. checkoutButton.disabled = true;
  714. itsEmpty = true;
  715. } else {
  716. cartCountElement.classList.remove("hidden");
  717. if (cartCountElement && itsEmpty) {
  718. itsEmpty = false;
  719. cartCountElement.animate([{ transform: 'scale(0)' }, { transform: 'scale(1)' }], { duration: 300, iterations: 1, easing: 'ease-in-out' });
  720. } else {
  721. cartCountElement.animate([{ transform: 'scale(1) rotate(0deg)' }, { transform: 'scale(1.2) rotate(180deg)' }, { transform: 'scale(1) rotate(360deg)' }], { duration: 300, iterations: 1, easing: 'ease-in-out' });
  722. }
  723. emptyCartTextElement.classList.add("hidden");
  724. checkoutButton.disabled = false;
  725. cart.forEach(item => {
  726. const cartItemHTML = `
  727. <div class="product-cart flex justify-between items-center border-b border-gray-700 pb-2 last:border-b-0 mb-2">
  728. <div>
  729. <h4 class="item-name-cart font-semibold text-base">${item.name} <span class="text-sm text-gray-400">(x${item.quantity})</span></h4>
  730. <p class="text-sm accent-red">${formatPrice(item.price * item.quantity)}</p>
  731. </div>
  732. <div class="flex items-center gap-1 sm:gap-2">
  733. <button class="comment-button text-gray-500 hover:text-gray-400 text-lg sm:text-xl font-bold p-1 rounded-full hover:bg-gray-700 transition-colors" onclick="addComment(${item.id})">
  734. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-plus"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 9h8" /><path d="M8 13h6" /><path d="M12.01 18.594l-4.01 2.406v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v5.5" /><path d="M16 19h6" /><path d="M19 16v6" /></svg>
  735. </button>
  736. <button onclick="addToCart(${item.id})" class="plus-button text-green-500 hover:text-green-400 text-lg sm:text-xl font-bold p-1 rounded-full hover:bg-gray-700 transition-colors">+</button>
  737. <button onclick="removeFromCart(${item.id})" class="minus-button text-yellow-500 hover:text-yellow-400 text-lg sm:text-xl font-bold p-1 rounded-full hover:bg-gray-700 transition-colors">-</button>
  738. <button onclick="removeFromCart(${item.id}, true)" class="remove-button text-red-500 hover:text-red-400 text-base sm:text-lg p-1 rounded-full hover:bg-gray-700 transition-colors">
  739. <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 sm:w-5 sm:h-5 pointer-events-none"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12.56 0c1.153 0 2.24.032 3.22.096M15 5.79V4.5A2.25 2.25 0 0012.75 2.25h-1.5A2.25 2.25 0 009 4.5v1.29m0 0L9 19.5M15 5.79l-1.5-1.5M9 5.79l1.5-1.5" /></svg>
  740. </button>
  741. </div>
  742. </div>
  743. `;
  744. cartItemsElement.innerHTML += cartItemHTML;
  745. });
  746. }
  747. calculateTotal();
  748. }
  749. async function processOrder() {
  750. if (cart.length === 0) return;
  751. showGlobalLoader();
  752. if (checkoutButton) {
  753. checkoutButton.disabled = true;
  754. checkoutButton.textContent = "Procesando...";
  755. }
  756. try {
  757. const orderData = {
  758. customerId: userId,
  759. table: userTable,
  760. items: cart.map(item => ({
  761. id: item.id,
  762. price: item.price,
  763. quantity: item.quantity,
  764. comment: item.comment ?? ""
  765. })),
  766. totalAmount: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
  767. orderDate: new Date().toLocaleString('sv-SE').replace(' ', 'T')
  768. };
  769. const data = await sendOrder(orderData, userToken);
  770. if (data && data.new_progress && data.new_progress !== getProgress()) {
  771. updateProgress(data.new_progress);
  772. }
  773. alert("Pedido enviado con éxito.");
  774. cart.forEach(item => {
  775. addHistoryRow({
  776. productName: item.name,
  777. quantity: item.quantity,
  778. price: item.price,
  779. });
  780. });
  781. cart = [];
  782. updateCartDisplay();
  783. } catch (error) {
  784. console.error("Error al procesar la orden:", error);
  785. alert(`Hubo un problema: ${error.message || "Por favor, inténtalo de nuevo."}`);
  786. } finally {
  787. hideGlobalLoader();
  788. checkoutButton.disabled = cart.length === 0;
  789. checkoutButton.textContent = originalCheckoutButtonText;
  790. }
  791. }
  792. // ... (Resto de rewards system) ...
  793. function initializeRewards() {
  794. closeSuccessRewardModalButton.addEventListener("click", closeSuccessRewardModal);
  795. rewardBtn.addEventListener('click', function () {
  796. if (!rewardBtn.disabled) {
  797. rewardModal.classList.remove('hidden');
  798. document.body.style.overflow = 'hidden';
  799. }
  800. });
  801. closeRewardModal.addEventListener('click', function () { closeModal(); });
  802. cancelRewardBtn.addEventListener('click', function () { closeModal(); });
  803. rewardModal.addEventListener('click', function (e) { if (e.target === rewardModal) closeModal(); });
  804. document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !rewardModal.classList.contains('hidden')) closeModal(); });
  805. claimRewardBtn.addEventListener('click', function () {
  806. if (!this.disabled && acceptTermsCheckbox.checked) {
  807. claimReward(userToken, userTable);
  808. closeModal();
  809. updateProgress(0);
  810. }
  811. });
  812. acceptTermsCheckbox.addEventListener('change', function () {
  813. if (this.checked) {
  814. claimRewardBtn.disabled = false;
  815. claimRewardBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  816. } else {
  817. claimRewardBtn.disabled = true;
  818. claimRewardBtn.classList.add('opacity-50', 'cursor-not-allowed');
  819. }
  820. });
  821. }
  822. function closeSuccessRewardModal() {
  823. const successRewardModal = document.getElementById("successRewardModal");
  824. successRewardModal.classList.add("hidden");
  825. document.body.style.overflow = '';
  826. }
  827. function closeModal() {
  828. rewardModal.classList.add('hidden');
  829. document.body.style.overflow = '';
  830. acceptTermsCheckbox.checked = false;
  831. claimRewardBtn.disabled = true;
  832. claimRewardBtn.classList.add('opacity-50', 'cursor-not-allowed');
  833. }
  834. export function beforeUnloadHandler() {
  835. // Para guest no hacemos nada especial al salir
  836. if (userToken && !isGuest) {
  837. // Opcional: logout
  838. }
  839. }
  840. async function checkCache() {
  841. const tokenCache = getCookie("userToken");
  842. if (tokenCache) {
  843. userToken = tokenCache;
  844. try {
  845. const user = await getUserData(userToken);
  846. if (user) {
  847. userId = user.id;
  848. userName = user.name;
  849. updateProgress(user.reward_progress || 0);
  850. return true;
  851. }
  852. } catch (error) {
  853. setCookie("userToken", "", -1);
  854. return false;
  855. }
  856. }
  857. return false;
  858. }
  859. function setupSearchListener() {
  860. const searchInput = document.getElementById("searchInput");
  861. if (!searchInput) return;
  862. let debounceTimer;
  863. searchInput.addEventListener("input", () => {
  864. clearTimeout(debounceTimer);
  865. productListElement.style.opacity = "0.7";
  866. productListElement.style.transform = "scale(0.98)";
  867. productListElement.style.transition = "opacity 0.2s ease, transform 0.2s ease";
  868. debounceTimer = setTimeout(() => {
  869. const searchTerm = searchInput.value.toLowerCase();
  870. if (searchTerm.trim() === "") {
  871. renderProductsWithAnimation(Allproducts);
  872. return;
  873. }
  874. const foundProducts = smartSearch(Allproducts, searchTerm);
  875. renderProductsWithAnimation(foundProducts, true, searchTerm);
  876. }, 200);
  877. });
  878. }
  879. function setupBasicListeners() {
  880. if (!checkoutButton) return;
  881. checkoutButton.addEventListener("click", processOrder);
  882. initializeRewards();
  883. window.addEventListener('popstate', function (event) {
  884. this.history.pushState(null, null, this.location.href);
  885. if (!rewardModal.classList.contains('hidden')) closeModal();
  886. else window.switchTab('menuTab');
  887. });
  888. window.addEventListener('beforeunload', beforeUnloadHandler);
  889. }
  890. document.addEventListener("DOMContentLoaded", async () => {
  891. hideGUI();
  892. initializeApp();
  893. });