app.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. //--- Imports ---
  2. import { getOnlineUserCount, getUserList } from './service/chat.js';
  3. import { getProducts, sendOrder } from './service/product.js';
  4. import { login } 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. // --- Variables Globales ---
  14. // --- User Data ---
  15. let userId = -1;
  16. let userName = "Cliente";
  17. let chatUserName = "prueba_mesa43"
  18. let userTable = null;
  19. let userToken = null;
  20. let chatWebsocket = null;
  21. // --- Products & Cart ---
  22. let Allproducts = [];
  23. let cart = [];
  24. let itsEmpty = true;
  25. let cacheMode = false;
  26. // --- Configuration ---
  27. const favoriteCategories = ["Shop", "Pizzas Familiares", "Pizza Medianas"];
  28. const productPriority = {
  29. "Shop": [
  30. 6, 12, 163, 168, 15, 665, 1
  31. ],
  32. "Cervezas": [
  33. 17,
  34. ],
  35. "Coctelería Gin Klein": [
  36. 655
  37. ],
  38. "Pizzas Familiares": [
  39. 27
  40. ],
  41. "Pizza Medianas": [
  42. 2
  43. ]
  44. }
  45. const userColors = [
  46. // Rojos
  47. "text-red-500", "text-red-600", "text-rose-500", "text-rose-600",
  48. "text-orange-500", "text-orange-600", "text-amber-500", "text-amber-600",
  49. // Amarillos / dorados
  50. "text-yellow-500", "text-yellow-600", "text-lime-500", "text-lime-600",
  51. // Verdes
  52. "text-green-500", "text-green-600", "text-emerald-500", "text-emerald-600",
  53. "text-teal-500", "text-teal-600", "text-cyan-500", "text-cyan-600",
  54. // Azules
  55. "text-sky-500", "text-sky-600", "text-blue-500", "text-blue-600",
  56. "text-indigo-500", "text-indigo-600",
  57. // Violetas / púrpuras æ
  58. "text-violet-500", "text-violet-600", "text-purple-500", "text-purple-600",
  59. "text-fuchsia-500", "text-fuchsia-600", "text-pink-500", "text-pink-600",
  60. // Neutros variados
  61. "text-gray-500", "text-gray-600", "text-zinc-500", "text-zinc-600",
  62. "text-neutral-500", "text-neutral-600", "text-stone-500", "text-stone-600"
  63. ];
  64. const productsWithVariety = {
  65. "480": [
  66. "Frambuesa",
  67. "Mango",
  68. "Maracuyá",
  69. "Piña",
  70. "Tradicional"
  71. ]
  72. }
  73. //--- Elementos del DOM ---
  74. // --- Product & Cart Elements ---
  75. const productListElement = document.getElementById("productList");
  76. const cartItemsElement = document.getElementById("cartItems");
  77. const cartTotalElement = document.getElementById("cartTotal");
  78. const emptyCartTextElement = document.getElementById("emptyCartText");
  79. const checkoutButton = document.getElementById("checkoutButton");
  80. const originalCheckoutButtonText = checkoutButton ? checkoutButton.textContent : "Finalizar Pedido";
  81. const cartCountElement = document.getElementById("cartCount");
  82. // --- Chat Elements ---
  83. const chatMessagesElement = document.getElementById("chatMessages");
  84. const chatInputElement = document.getElementById("chatInput");
  85. const chatForm = document.getElementById("chatForm");
  86. const userList = document.getElementById("userList")
  87. const onlineUsersElement = document.querySelector("#onlineUsers h4");
  88. // --- Reward Elements ---
  89. const rewardBtn = document.getElementById('rewardBtn');
  90. const rewardModal = document.getElementById('rewardModal');
  91. const closeRewardModal = document.getElementById('closeRewardModal');
  92. const closeSuccessRewardModalButton = document.getElementById('closeSuccessRewardModal');
  93. const cancelRewardBtn = document.getElementById('cancelRewardBtn');
  94. const acceptTermsCheckbox = document.getElementById('acceptTermsCheckbox');
  95. const claimRewardBtn = document.getElementById('claimRewardBtn');
  96. //--- Inicialización y Configuración ---
  97. /**
  98. * Main application initialization
  99. */
  100. async function initializeApp() {
  101. showGlobalLoader("Cargando productos...");
  102. chatUserName = userName.split(" ")[0].toLowerCase() + "_mesa"+userTable
  103. initializeChat();
  104. initializeWebSocket();
  105. await initializeProducts();
  106. await renderProducts(Allproducts);
  107. setupSearchListener();
  108. setupTabSwitching();
  109. updateCartDisplay();
  110. setupShoppingCart(userId, userToken, userName);
  111. setupBasicListeners();
  112. showGUI();
  113. hideGlobalLoader();
  114. }
  115. /**
  116. * Initialize login modal and authentication
  117. */
  118. function initializeLoginModal() {
  119. const sessionModal = document.getElementById('sessionModal');
  120. const loginForm = document.getElementById('loginForm');
  121. const logoutBtn = document.getElementById('logoutBtn');
  122. sessionModal.classList.remove('hidden');
  123. // Login form submission
  124. loginForm.addEventListener('submit', async (event) => {
  125. event.preventDefault();
  126. event.stopPropagation();
  127. const fd = new FormData(loginForm);
  128. if (cacheMode) {
  129. userTable = Number(fd.get('table').trim());
  130. sessionModal.classList.add('hidden');
  131. initializeApp();
  132. return;
  133. }
  134. const email = fd.get('email').trim();
  135. const pin = fd.get('pin').trim();
  136. userTable = Number(fd.get('table').trim());
  137. if (!email || !pin || !userTable) {
  138. showError("Por favor, completa todos los campos.");
  139. return;
  140. }
  141. try {
  142. const { data } = await login(email, pin);
  143. userToken = data.token;
  144. userName = data.name;
  145. userId = data.id;
  146. setCookie("userToken", userToken, 7);
  147. updateProgress(data.reward_progress || 0);
  148. if (!userToken || data.id === undefined) {
  149. showError("Error al iniciar sesión.");
  150. return;
  151. }
  152. sessionModal.classList.add('hidden');
  153. initializeApp();
  154. } catch (error) {
  155. console.error(error);
  156. }
  157. });
  158. // Logout functionality
  159. if (logoutBtn) {
  160. logoutBtn.addEventListener('click', () => {
  161. setCookie("userToken", "", -1);
  162. userId = -1;
  163. userName = "Cliente";
  164. userTable = null;
  165. userToken = null;
  166. cacheMode = false;
  167. hideGUI();
  168. sessionModal.classList.remove('hidden');false
  169. // Reset UI elements
  170. document.querySelector("#emailInputContainer").classList.remove("hidden");
  171. document.querySelector("#pinInputContainer").classList.remove("hidden");
  172. document.getElementById("loginTitle").textContent = "¡Bienvenido!";
  173. document.querySelector("#emailInput").setAttribute("required", "");
  174. document.querySelector("#pinInput").setAttribute("required", "");
  175. logoutBtn.classList.add("hidden");
  176. document.querySelector("#recoveryPIN").classList.remove("hidden");
  177. });
  178. }
  179. }
  180. function initializeWebSocket() {
  181. if (!chatWebsocket) {
  182. const wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
  183. chatWebsocket = new WebSocket(`${wsProtocol}://${location.host}/api/chat/ws?token=${userToken}`);
  184. chatWebsocket.onopen = () => {
  185. chatWebsocket.send(JSON.stringify({
  186. type: "join",
  187. username: chatUserName
  188. }));
  189. }
  190. getOnlineUserCount(userToken).then(count => {
  191. onlineUsersElement.innerText = `${count} Usuario${count !== 1 ? 's' : ''} en línea`;
  192. });
  193. chatWebsocket.onmessage = (event) => {
  194. const data = JSON.parse(event.data);
  195. if (data.type === "message") {
  196. displayChatMessage(data.username, data.message);
  197. }
  198. else if (data.type === "join") {
  199. newUserInChat(data.username);
  200. getOnlineUserCount(userToken).then(count => {
  201. onlineUsersElement.innerText = `${count} Usuario${count !== 1 ? 's' : ''} en línea`;
  202. });
  203. }
  204. else if (data.type === "leave") {
  205. userLeftChat(data.username);
  206. getOnlineUserCount(userToken).then(count => {
  207. onlineUsersElement.innerText = `${count} Usuario${count !== 1 ? 's' : ''} en línea`;
  208. });
  209. }
  210. else if (data.type === "mentioned") {
  211. if (data.username && data.username !== chatUserName) return; // not for me
  212. showMentioned();
  213. }
  214. else if (data.type === "ping") {
  215. chatWebsocket.send(JSON.stringify({
  216. type: "pong"
  217. }));
  218. }
  219. }
  220. }
  221. }
  222. async function sendMessage(message) {
  223. if (chatWebsocket) {
  224. if (chatWebsocket.readyState !== WebSocket.OPEN) {
  225. console.error("WebSocket is not open, reopening...");
  226. chatWebsocket = null;
  227. initializeWebSocket();
  228. }
  229. await chatWebsocket.send(JSON.stringify({
  230. type: "message",
  231. username: chatUserName,
  232. message: message
  233. }));
  234. let mentions_repeated = [];
  235. await setTimeout(() => {
  236. const mentionRegex = /@([a-zA-Z0-9_]+_mesa\d+|IAKlein)/g;
  237. const mentions = message.match(mentionRegex);
  238. if (mentions) {
  239. mentions.forEach(mention => {
  240. const username = mention.slice(1);
  241. const exist = mentions_repeated.find(u => u === username);
  242. console.log("Mentioned user:", username,"List", mentions_repeated, "Exist before:", exist);
  243. if (exist || username === chatUserName) return; // don't mention myself if multiple mentions
  244. mentions_repeated.push(username);
  245. if (username === "IAKlein"){
  246. sendMessageToAI(message);
  247. }else {
  248. userMentioned(username);
  249. }
  250. });
  251. }
  252. }, 1000); // small delay to ensure message order
  253. // regex text_mesa111 or IAKlein
  254. }
  255. }
  256. function userMentioned(username) {
  257. chatWebsocket.send(JSON.stringify({
  258. type: "mention",
  259. username: username
  260. }));
  261. }
  262. /**
  263. * Initialize chat functionality
  264. */
  265. function initializeChat() {
  266. if (!chatForm) return;
  267. chatForm.addEventListener("submit", (event) => {
  268. event.preventDefault();
  269. if (chatInputElement.value.trim() === "") return;
  270. chatForm.querySelector("button").animate(
  271. [{ transform: 'scale(1)' }, { transform: 'scale(0.9)' }, { transform: 'scale(1)' }],
  272. { duration: 200, iterations: 1, easing: 'ease-in-out' }
  273. )
  274. sendMessage(chatInputElement.value.trim());
  275. chatInputElement.value = "";
  276. });
  277. let debounceTimer;
  278. chatInputElement.addEventListener("input", () => {
  279. const lastWord = chatInputElement.value.split(" ").at(-1);
  280. if (lastWord.trim().startsWith("@")) {
  281. clearTimeout(debounceTimer);
  282. debounceTimer = setTimeout(async () => {
  283. userList.classList.remove("hidden");
  284. let users = await getUserList(lastWord.trim().substring(1), userToken);
  285. users = users.filter(u => u !== chatUserName);
  286. users.push("IAKlein");
  287. userList.innerHTML = "";
  288. users.forEach(user => {
  289. const userItem = document.createElement("button");
  290. userItem.type = "button";
  291. userItem.onclick = () => {
  292. // Replace the last occurrence of lastWord with @user
  293. const inputValue = chatInputElement.value;
  294. const lastWordIndex = inputValue.lastIndexOf(lastWord);
  295. if (lastWordIndex !== -1) {
  296. chatInputElement.value = inputValue.slice(0, lastWordIndex) + `@${user}` + inputValue.slice(lastWordIndex + lastWord.length);
  297. }
  298. userList.classList.add("hidden");
  299. chatInputElement.value += " ";
  300. chatInputElement.focus();
  301. };
  302. const color = getUserColor(user);
  303. userItem.classList.add("list-user-name", "cursor-pointer", color);
  304. userItem.textContent = user;
  305. userList.appendChild(userItem);
  306. });
  307. }, 300); // Debounce delay (300ms)
  308. } else {
  309. userList.classList.add("hidden");
  310. clearTimeout(debounceTimer);
  311. }
  312. });
  313. }
  314. export function beforeUnloadHandler() {
  315. if (userToken) {
  316. logout();
  317. }
  318. }
  319. /**
  320. * Setup basic event listeners
  321. */
  322. function setupBasicListeners() {
  323. if (!checkoutButton) return;
  324. checkoutButton.addEventListener("click", processOrder);
  325. initializeRewards();
  326. // Close model - Back button on phone
  327. window.addEventListener('popstate', function (event) {
  328. alert("back");
  329. this.history.pushState(null, null, this.location.href);
  330. if (!rewardModal.classList.contains('hidden')) {
  331. closeModal();
  332. }else {
  333. window.switchTab('menuTab');
  334. }
  335. });
  336. window.addEventListener('beforeunload', beforeUnloadHandler);
  337. }
  338. /**
  339. * Setup search functionality with debouncing
  340. */
  341. function setupSearchListener() {
  342. const searchInput = document.getElementById("searchInput");
  343. if (!searchInput) return;
  344. let debounceTimer;
  345. searchInput.addEventListener("input", () => {
  346. clearTimeout(debounceTimer);
  347. // Visual feedback during search
  348. productListElement.style.opacity = "0.7";
  349. productListElement.style.transform = "scale(0.98)";
  350. productListElement.style.transition = "opacity 0.2s ease, transform 0.2s ease";
  351. // Debounce search for 200ms
  352. debounceTimer = setTimeout(() => {
  353. const searchTerm = searchInput.value.toLowerCase();
  354. if (searchTerm.trim() === "") {
  355. renderProductsWithAnimation(Allproducts);
  356. return;
  357. }
  358. const foundProducts = smartSearch(Allproducts, searchTerm);
  359. renderProductsWithAnimation(foundProducts, true, searchTerm);
  360. }, 200);
  361. });
  362. }
  363. // Tab switching variables
  364. const animation_time = 200;
  365. let transitioning = false;
  366. /**
  367. * Switch to a specific tab programmatically
  368. * @param {string} targetTabId - The ID of the target tab (e.g., 'chatTab', 'productsTab')
  369. */
  370. window.switchTab = function(targetTabId) {
  371. const targetButton = document.querySelector(`[data-target="${targetTabId}"]`);
  372. if (!targetButton) {
  373. console.warn(`Tab button with target "${targetTabId}" not found`);
  374. return;
  375. }
  376. if (targetTabId === "chatTab") {
  377. window.hideMentioned();
  378. }
  379. const active = document.querySelector(':not(.hidden)[data-tab]');
  380. if (!active) {
  381. console.warn('No active tab found');
  382. return;
  383. }
  384. const activeIndex = active.dataset.index;
  385. const to = document.querySelector(`#${targetTabId}[data-tab]`);
  386. if (!to) {
  387. console.warn(`Target tab "${targetTabId}" not found`);
  388. return;
  389. }
  390. const toIndex = to.dataset.index;
  391. if (activeIndex === toIndex || transitioning) return;
  392. // Update button states
  393. const buttons = document.querySelectorAll('.tab-btn');
  394. buttons.forEach(button => {
  395. button.classList.remove('active');
  396. });
  397. targetButton.classList.add('active');
  398. // Perform tab transition
  399. performTabTransition(active, to, activeIndex, toIndex, targetButton);
  400. };
  401. /**
  402. * Perform the actual tab transition with animations
  403. * @param {Element} active - Currently active tab
  404. * @param {Element} to - Target tab to switch to
  405. * @param {string} activeIndex - Index of active tab
  406. * @param {string} toIndex - Index of target tab
  407. * @param {Element} targetButton - Button that triggered the switch
  408. */
  409. function performTabTransition(active, to, activeIndex, toIndex, targetButton) {
  410. active.style.height = "100%";
  411. active.style.width = "100vw";
  412. to.style.height = "100%";
  413. to.style.width = "100vw";
  414. to.style.zIndex = "1";
  415. active.style.zIndex = "0";
  416. transitioning = true;
  417. const otherTabs = document.querySelectorAll('[data-tab]');
  418. otherTabs.forEach(tab => {
  419. if (tab !== active && tab !== to) {
  420. tab.classList.add('hidden');
  421. tab.classList.remove(`animate-[slideLeft_${animation_time}ms_ease-out]`, `animate-[slideRight_${animation_time}ms_ease-out]`);
  422. tab.classList.remove(`animate-[slideLeftIn_${animation_time}ms_ease-out]`, `animate-[slideRightIn_${animation_time}ms_ease-out]`);
  423. }
  424. });
  425. to.classList.remove('hidden');
  426. // Animate tab transition
  427. if (activeIndex < toIndex) {
  428. // Slide left
  429. active.classList.add(`animate-[slideLeft_${animation_time}ms_ease-out]`);
  430. to.classList.add(`animate-[slideRightIn_${animation_time}ms_ease-out]`);
  431. } else if (activeIndex > toIndex) {
  432. // Slide right
  433. active.classList.add(`animate-[slideRight_${animation_time}ms_ease-out]`);
  434. to.classList.add(`animate-[slideLeftIn_${animation_time}ms_ease-out]`);
  435. }
  436. setTimeout(() => {
  437. active.classList.remove(`animate-[slideLeft_${animation_time}ms_ease-out]`, `animate-[slideRight_${animation_time}ms_ease-out]`);
  438. active.classList.add('hidden');
  439. to.classList.remove(`animate-[slideLeftIn_${animation_time}ms_ease-out]`, `animate-[slideRightIn_${animation_time}ms_ease-out]`);
  440. transitioning = false;
  441. }, animation_time);
  442. // Update header title if needed
  443. const title = targetButton.dataset.title;
  444. if (title) {
  445. const mainTitle = document.getElementById('mainTitle');
  446. if (mainTitle) {
  447. mainTitle.textContent = title;
  448. }
  449. }
  450. }
  451. /**
  452. * Setup tab switching functionality with animations
  453. */
  454. function setupTabSwitching() {
  455. // Tab switching functionality
  456. const buttons = document.querySelectorAll('.tab-btn');
  457. buttons.forEach(btn => {
  458. btn.addEventListener('click', () => {
  459. const target = btn.dataset.target;
  460. window.switchTab(target);
  461. });
  462. });
  463. }
  464. //--- Funciones de Utilidad ---
  465. /**
  466. * Set a cookie with expiration
  467. */
  468. function setCookie(name, value, days) {
  469. const expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
  470. document.cookie = `${name}=${value}; expires=${expires}; path=/`;
  471. }
  472. /**
  473. * Get a cookie value by name
  474. */
  475. function getCookie(name) {
  476. const cookies = document.cookie.split('; ');
  477. for (const cookie of cookies) {
  478. const [cookieName, cookieValue] = cookie.split('=');
  479. if (cookieName === name) {
  480. return decodeURIComponent(cookieValue);
  481. }
  482. }
  483. return null;
  484. }
  485. /**
  486. * Check and validate cached user data
  487. */
  488. async function checkCache() {
  489. const tokenCache = getCookie("userToken");
  490. let user = null;
  491. if (tokenCache) {
  492. userToken = tokenCache;
  493. try {
  494. const data = await getUserData(userToken);
  495. user = data.data;
  496. } catch (error) {
  497. console.error("Error fetching user data:", error);
  498. console.error("Invalid user token, clearing cache.");
  499. setCookie("userToken", "", -1);
  500. return false;
  501. }
  502. if (user) {
  503. userId = user.id;
  504. userName = user.name;
  505. updateProgress(user.reward_progress || 0);
  506. // Update UI for cached user
  507. const [emailInputContainer, pinInputContainer] = [
  508. document.getElementById("emailInputContainer"),
  509. document.getElementById("pinInputContainer")
  510. ];
  511. const [emailInput, pinInput] = [
  512. document.getElementById("emailInput"),
  513. document.getElementById("pinInput")
  514. ];
  515. const loginTitle = document.getElementById("loginTitle");
  516. loginTitle.textContent = `¡Bienvenido ${user.name.split(" ")[0]}!`;
  517. emailInputContainer.classList.add("hidden");
  518. emailInput.removeAttribute("required");
  519. pinInputContainer.classList.add("hidden");
  520. pinInput.removeAttribute("required");
  521. document.querySelector("#logoutBtn").classList.remove("hidden");
  522. document.querySelector("#recoveryPIN").classList.add("hidden");
  523. cacheMode = true;
  524. return true;
  525. }
  526. }
  527. return cacheMode;
  528. }
  529. /**
  530. * Format price to Chilean peso currency
  531. */
  532. function formatPrice(price) {
  533. return price.toLocaleString("es-CL", { style: "currency", currency: "CLP" });
  534. }
  535. //--- Gestión de Productos ---
  536. /**
  537. * Initialize products from API
  538. */
  539. async function initializeProducts() {
  540. Allproducts = await getProducts(userToken);
  541. }
  542. /**
  543. * Create category containers for products
  544. */
  545. async function createCategories(products) {
  546. let categories = new Set(products.map(product => product.type || "Sin categoría"));
  547. categories = Array.from(categories).sort((a, b) => a.localeCompare(b));
  548. // Prioritize favorite categories
  549. for (const category of favoriteCategories.reverse()) {
  550. if (categories.includes(category)) {
  551. categories = categories.filter(cat => cat !== category);
  552. categories.unshift(category);
  553. }
  554. }
  555. if (!productListElement) return;
  556. const categoryContainers = categories.map(category => {
  557. const container = document.createElement("div");
  558. container.classList.add("category-container", "mb-8", "p-4");
  559. const title = document.createElement("h2");
  560. title.classList.add("category-title", "text-3xl", "font-bold", "border-b-2", "pb-3", "mb-4");
  561. // Pluralize category name
  562. const lastChar = category.charAt(category.length - 1).toLowerCase();
  563. const pluralSuffix = ["a", "e", "i", "o", "u", "á", "é", "í", "ó", "ú", "p"].includes(lastChar)
  564. ? "s"
  565. : lastChar === "s" ? "" : "es";
  566. title.textContent = category + pluralSuffix;
  567. container.appendChild(title);
  568. const productList = document.createElement("div");
  569. productList.classList.add("product-list", "space-y-6");
  570. productList.id = `productList-${category}`;
  571. container.appendChild(productList);
  572. productListElement.appendChild(container);
  573. return { category, container: productList };
  574. });
  575. return categoryContainers;
  576. }
  577. /**
  578. * Render products in their respective categories
  579. */
  580. async function renderProducts(products, groupInCategories = true, searchTerm = "") {
  581. if (!productListElement) return;
  582. const template = document.getElementById("product-card-template");
  583. if (!template) return;
  584. productListElement.innerHTML = "";
  585. let categoryContainers = [];
  586. if (groupInCategories) {
  587. categoryContainers = await createCategories(products);
  588. } else {
  589. categoryContainers = [{ category: searchTerm, container: productListElement }];
  590. }
  591. if (products.length === 0) {
  592. const noProductsMessage = document.createElement("p");
  593. noProductsMessage.textContent = "No hay productos disponibles.";
  594. productListElement.appendChild(noProductsMessage);
  595. return;
  596. }
  597. for (const { category, container } of categoryContainers) {
  598. let productsInCategory = groupInCategories
  599. ? products.filter(product => product.type === category)
  600. : products;
  601. // Prioritize products in favorite categories
  602. if (favoriteCategories.includes(category) && productPriority[category]) {
  603. productsInCategory.sort((a, b) => {
  604. const aIndex = productPriority[category].indexOf(a.id);
  605. const bIndex = productPriority[category].indexOf(b.id);
  606. // If both products are in priority list, sort by their priority order
  607. if (aIndex !== -1 && bIndex !== -1) {
  608. return aIndex - bIndex;
  609. }
  610. // If only 'a' is in priority list, it should come first
  611. if (aIndex !== -1 && bIndex === -1) {
  612. return -1;
  613. }
  614. // If only 'b' is in priority list, it should come first
  615. if (aIndex === -1 && bIndex !== -1) {
  616. return 1;
  617. }
  618. // If neither is in priority list, maintain original order
  619. return 0;
  620. });
  621. }
  622. if (productsInCategory.length === 0) continue;
  623. productsInCategory.forEach(product => {
  624. const clone = template.content.cloneNode(true);
  625. clone.querySelector(".product-type").textContent = product.type || "Sin categoría";
  626. clone.querySelector(".product-name").textContent = product.name;
  627. clone.querySelector(".product-description").textContent = product.description;
  628. clone.querySelector(".product-price").textContent = formatPrice(product.price);
  629. clone.querySelector(".product-image").style.backgroundImage = `url('${product.image}')`;
  630. const addBtn = clone.querySelector(".add-to-cart-btn");
  631. addBtn.dataset.productId = product.id;
  632. addBtn.addEventListener('click', (event) => {
  633. const productId = parseInt(event.target.dataset.productId);
  634. addToCart(productId, event.target);
  635. });
  636. container.appendChild(clone);
  637. });
  638. }
  639. }
  640. /**
  641. * Render products with smooth animations
  642. */
  643. async function renderProductsWithAnimation(products, groupInCategories = true, searchTerm = "") {
  644. if (!productListElement) return;
  645. const template = document.getElementById("product-card-template");
  646. if (!template) return;
  647. // Fade out current content
  648. productListElement.style.opacity = "0";
  649. productListElement.style.transform = "scale(0.95)";
  650. setTimeout(async () => {
  651. productListElement.innerHTML = "";
  652. let categoryContainers = [];
  653. if (groupInCategories) {
  654. categoryContainers = await createCategories(products);
  655. } else {
  656. categoryContainers = [{ category: searchTerm, container: productListElement }];
  657. }
  658. // ordenar las categorias por favoriteCategories
  659. categoryContainers.sort((a, b) => {
  660. const aIndex = favoriteCategories.indexOf(a.category);
  661. const bIndex = favoriteCategories.indexOf(b.category);
  662. return aIndex - bIndex;
  663. });
  664. if (products.length === 0) {
  665. const noProductsMessage = document.createElement("p");
  666. noProductsMessage.textContent = "No hay productos disponibles.";
  667. noProductsMessage.style.opacity = "0";
  668. noProductsMessage.style.transform = "translateY(20px)";
  669. noProductsMessage.style.transition = "opacity 0.3s ease, transform 0.3s ease";
  670. productListElement.appendChild(noProductsMessage);
  671. // Restore container
  672. productListElement.style.opacity = "1";
  673. productListElement.style.transform = "scale(1)";
  674. // Animate message
  675. setTimeout(() => {
  676. noProductsMessage.style.opacity = "1";
  677. noProductsMessage.style.transform = "translateY(0)";
  678. }, 50);
  679. return;
  680. }
  681. let animationDelay = 0;
  682. for (const { category, container } of categoryContainers) {
  683. let productsInCategory = groupInCategories
  684. ? products.filter(product => product.type === category)
  685. : products;
  686. if (productsInCategory.length === 0) continue;
  687. if (favoriteCategories.includes(category) && productPriority[category]) {
  688. productsInCategory.sort((a, b) => {
  689. const aIndex = productPriority[category].indexOf(a.id);
  690. const bIndex = productPriority[category].indexOf(b.id);
  691. // If both products are in priority list, sort by their priority order
  692. if (aIndex !== -1 && bIndex !== -1) {
  693. return aIndex - bIndex;
  694. }
  695. // If only 'a' is in priority list, it should come first
  696. if (aIndex !== -1 && bIndex === -1) {
  697. return -1;
  698. }
  699. // If only 'b' is in priority list, it should come first
  700. if (aIndex === -1 && bIndex !== -1) {
  701. return 1;
  702. }
  703. // If neither is in priority list, maintain original order
  704. return 0;
  705. });
  706. }
  707. productsInCategory.forEach((product, index) => {
  708. const clone = template.content.cloneNode(true);
  709. clone.querySelector(".product-type").textContent = product.type || "Sin categoría";
  710. clone.querySelector(".product-name").textContent = product.name;
  711. clone.querySelector(".product-description").textContent = product.description;
  712. clone.querySelector(".product-price").textContent = formatPrice(product.price);
  713. clone.querySelector(".product-image").style.backgroundImage = `url('${product.image}')`;
  714. const addBtn = clone.querySelector(".add-to-cart-btn");
  715. addBtn.dataset.productId = product.id;
  716. addBtn.addEventListener('click', (event) => {
  717. const productId = parseInt(event.target.dataset.productId);
  718. addToCart(productId, event.target);
  719. });
  720. // Get the first child (the product card element)
  721. const productCard = clone.children[0];
  722. // Set initial animation state
  723. productCard.style.opacity = "0";
  724. productCard.style.transform = "translateY(20px) scale(0.95)";
  725. productCard.style.transition = "opacity 0.4s ease, transform 0.4s ease";
  726. container.appendChild(clone);
  727. // Animate in with staggered delay
  728. setTimeout(() => {
  729. productCard.style.opacity = "1";
  730. productCard.style.transform = "translateY(0) scale(1)";
  731. }, animationDelay);
  732. animationDelay += 50; // 50ms delay between each product
  733. });
  734. }
  735. // Restore container with smooth transition
  736. productListElement.style.opacity = "1";
  737. productListElement.style.transform = "scale(1)";
  738. }, 150); // Wait for fade out to complete
  739. }
  740. //--- Gestión del Carrito ---
  741. /**
  742. * Add product to cart with visual feedback
  743. */
  744. window.addComment = async function(productId) {
  745. const cartItem = cart.find(p => p.id === productId);
  746. if (!cartItem) return;
  747. const comment = await getComment(COMMENT_TYPES.LIBRE, [cartItem.comment]).catch(e => console.error(e));
  748. if (!comment) return;
  749. cartItem.comment += ` ${comment}`;
  750. console.log(cartItem);
  751. }
  752. window.addToCart = async function(productId, buttonElement = null) {
  753. let comment = "";
  754. if (productsWithVariety[String(productId)]) {
  755. comment = await getComment(COMMENT_TYPES.DESPLEGABLE, productsWithVariety[String(productId)]);
  756. }
  757. const product = Allproducts.find(p => p.id === productId);
  758. if (!product) return;
  759. const cartItem = cart.find(item => item.id === productId);
  760. if (cartItem) {
  761. cartItem.quantity++;
  762. cartItem.comment += `${comment}, `;
  763. } else {
  764. cart.push({ ...product, quantity: 1, comment });
  765. }
  766. // Visual feedback for button
  767. if (buttonElement) {
  768. const originalHTML = buttonElement.innerHTML;
  769. buttonElement.textContent = "✔ Agregado!";
  770. buttonElement.disabled = true;
  771. setTimeout(() => {
  772. buttonElement.innerHTML = originalHTML;
  773. buttonElement.disabled = false;
  774. }, 300);
  775. }
  776. updateCartDisplay();
  777. // Show toast notification if available
  778. if (typeof showToast === "function") {
  779. showToast(`${product.name} agregado al carrito`);
  780. }
  781. };
  782. /**
  783. * Remove product from cart
  784. */
  785. window.removeFromCart = function(productId, removeAll = false) {
  786. const itemIndex = cart.findIndex(item => item.id === productId);
  787. if (itemIndex > -1) {
  788. if (removeAll || cart[itemIndex].quantity === 1) {
  789. cart.splice(itemIndex, 1);
  790. } else {
  791. cart[itemIndex].quantity--;
  792. }
  793. }
  794. updateCartDisplay();
  795. };
  796. /**
  797. * Calculate total cart amount
  798. */
  799. function calculateTotal() {
  800. if (!cartTotalElement) return;
  801. const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  802. cartTotalElement.textContent = formatPrice(total);
  803. }
  804. /**
  805. * Update cart display with animations
  806. */
  807. function updateCartDisplay() {
  808. if (!cartItemsElement || !emptyCartTextElement || !checkoutButton || !cartCountElement) return;
  809. cartItemsElement.innerHTML = "";
  810. cartCountElement.textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
  811. if (cart.length === 0) {
  812. cartCountElement.classList.add("hidden");
  813. emptyCartTextElement.classList.remove("hidden");
  814. checkoutButton.disabled = true;
  815. itsEmpty = true;
  816. } else {
  817. cartCountElement.classList.remove("hidden");
  818. // Animate cart count badge
  819. if (cartCountElement && itsEmpty) {
  820. itsEmpty = false;
  821. cartCountElement.animate([
  822. { transform: 'scale(0)' },
  823. { transform: 'scale(1)' }
  824. ], {
  825. duration: 300,
  826. iterations: 1,
  827. easing: 'ease-in-out'
  828. });
  829. } else {
  830. cartCountElement.animate([
  831. { transform: 'scale(1) rotate(0deg)' },
  832. { transform: 'scale(1.2) rotate(180deg)' },
  833. { transform: 'scale(1) rotate(360deg)' }
  834. ], {
  835. duration: 300,
  836. iterations: 1,
  837. easing: 'ease-in-out'
  838. });
  839. }
  840. emptyCartTextElement.classList.add("hidden");
  841. checkoutButton.disabled = false;
  842. // Render cart items
  843. cart.forEach(item => {
  844. const cartItemHTML = `
  845. <div class="product-cart flex justify-between items-center border-b border-gray-700 pb-2 last:border-b-0 mb-2">
  846. <div>
  847. <h4 class="item-name-cart font-semibold text-base">${item.name} <span class="text-sm text-gray-400">(x${item.quantity})</span></h4>
  848. <p class="text-sm accent-red">${formatPrice(item.price * item.quantity)}</p>
  849. </div>
  850. <div class="flex items-center gap-1 sm:gap-2">
  851. <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})">
  852. <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>
  853. </button>
  854. <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>
  855. <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>
  856. <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">
  857. <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>
  858. </button>
  859. </div>
  860. </div>
  861. `;
  862. cartItemsElement.innerHTML += cartItemHTML;
  863. });
  864. }
  865. calculateTotal();
  866. }
  867. //--- Procesamiento de Pedidos ---
  868. /**
  869. * Process and send order to backend
  870. */
  871. async function processOrder() {
  872. if (cart.length === 0) return;
  873. showGlobalLoader();
  874. if (checkoutButton) {
  875. checkoutButton.disabled = true;
  876. checkoutButton.textContent = "Procesando...";
  877. }
  878. try {
  879. const orderData = {
  880. customerId: userId,
  881. table: userTable,
  882. items: cart.map(item => ({
  883. id: item.id,
  884. price: item.price,
  885. quantity: item.quantity,
  886. comment: item.comment ?? ""
  887. })),
  888. totalAmount: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
  889. orderDate: new Date().toLocaleString('sv-SE').replace(' ', 'T')
  890. };
  891. const data = await sendOrder(orderData, userToken);
  892. if (data && data.new_progress && data.new_progress !== getProgress()) {
  893. updateProgress(data.new_progress);
  894. }
  895. alert("Pedido enviado con éxito.");
  896. // Add items to history
  897. cart.forEach(item => {
  898. addHistoryRow({
  899. productName: item.name,
  900. quantity: item.quantity,
  901. price: item.price,
  902. });
  903. });
  904. // Clear cart
  905. cart = [];
  906. updateCartDisplay();
  907. } catch (error) {
  908. console.error("Error al procesar la orden:", error);
  909. alert(`Hubo un problema: ${error.message || "Por favor, inténtalo de nuevo."}`);
  910. } finally {
  911. hideGlobalLoader();
  912. checkoutButton.disabled = cart.length === 0;
  913. checkoutButton.textContent = originalCheckoutButtonText;
  914. }
  915. }
  916. //--- Funcionalidad del Chat ---
  917. /**
  918. * Display chat message with proper styling
  919. */
  920. function showMentioned(){
  921. const chatButton = document.querySelector("#chatIcon span");
  922. if (chatButton) {
  923. //get after element
  924. chatButton.classList.remove("hidden");
  925. chatButton.animate(
  926. [
  927. { transform: 'scale(1)' },
  928. { transform: 'scale(1.5)' },
  929. { transform: 'scale(1)' }
  930. ],
  931. {
  932. duration: 300,
  933. iterations: 3,
  934. easing: 'ease-in-out'
  935. }
  936. );
  937. }
  938. }
  939. window.hideMentioned = function(){
  940. const chatButton = document.querySelector("#chatIcon span");
  941. if (chatButton) {
  942. chatButton.classList.add("hidden");
  943. }
  944. }
  945. function getUserColor(username) {
  946. const hash = [...username].reduce((acc, char) => acc + char.charCodeAt(0), 0);
  947. const color = userColors[hash % userColors.length];
  948. return color;
  949. }
  950. function displayChatMessage(sender, message, time = undefined) {
  951. let realtime = `[${time ? time : new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  952. let messageTemplate = chatMessagesElement.querySelector("#chatMessageTemplate");
  953. if (!messageTemplate) return;
  954. let messageClone = messageTemplate.content.cloneNode(true).firstElementChild;
  955. messageClone.querySelector(".chat-message-text").innerHTML = message;
  956. messageClone.querySelector(".chat-message-time").innerHTML = realtime;
  957. messageClone.querySelector(".chat-message-user").innerHTML = sender
  958. messageClone.querySelector(".chat-message-user").classList.add(getUserColor(sender));
  959. chatMessagesElement.appendChild(messageClone);
  960. chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
  961. }
  962. function newUserInChat(userName) {
  963. let userTemplate = chatMessagesElement.querySelector("#systemMessageTemplate");
  964. if (!userTemplate) return;
  965. const realtime = `[${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  966. let userClone = userTemplate.content.cloneNode(true).firstElementChild;
  967. userClone.classList.add("text-green-600");
  968. userClone.querySelector(".chat-message-time").innerHTML = realtime;
  969. userClone.querySelector(".chat-message-text").innerHTML = `*** ${userName} se ha unido al chat`;
  970. chatMessagesElement.appendChild(userClone);
  971. }
  972. function userLeftChat(userName) {
  973. let userTemplate = chatMessagesElement.querySelector("#systemMessageTemplate");
  974. if (!userTemplate) return;
  975. const realtime = `[${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}] `;
  976. let userClone = userTemplate.content.cloneNode(true).firstElementChild;
  977. userClone.classList.add("text-red-600");
  978. userClone.querySelector(".chat-message-time").innerHTML = realtime;
  979. userClone.querySelector(".chat-message-text").innerHTML = `*** ${userName} se ha ido del chat`;
  980. chatMessagesElement.appendChild(userClone);
  981. }
  982. function sendMessageToAI(userMessage) {
  983. if (userMessage === "") return;
  984. const messages = Array.from(chatMessagesElement.querySelectorAll(".chat-message")).slice(-10);
  985. let formattedMessages = messages.map(msg => {
  986. const sender = msg.querySelector(".chat-message-user").textContent;
  987. const content = msg.querySelector(".chat-message-text").innerHTML;
  988. return { user: sender, content: content };
  989. });
  990. chatWebsocket.send(JSON.stringify({
  991. type: "ai_message",
  992. username: chatUserName,
  993. messages: formattedMessages
  994. }));
  995. chatInputElement.value = "";
  996. }
  997. //--- Sistema de Recompensas ---
  998. /**
  999. * Initialize rewards functionality
  1000. */
  1001. function initializeRewards() {
  1002. // Event listeners for reward system
  1003. closeSuccessRewardModalButton.addEventListener("click", closeSuccessRewardModal);
  1004. rewardBtn.addEventListener('click', function () {
  1005. if (!rewardBtn.disabled) {
  1006. rewardModal.classList.remove('hidden');
  1007. document.body.style.overflow = 'hidden';
  1008. }
  1009. });
  1010. // Close modal - X button
  1011. closeRewardModal.addEventListener('click', function () {
  1012. closeModal();
  1013. });
  1014. // Close modal - Cancel button
  1015. cancelRewardBtn.addEventListener('click', function () {
  1016. closeModal();
  1017. });
  1018. // Close modal - click outside
  1019. rewardModal.addEventListener('click', function (e) {
  1020. if (e.target === rewardModal) {
  1021. closeModal();
  1022. }
  1023. });
  1024. // Close modal - Escape key
  1025. document.addEventListener('keydown', function (e) {
  1026. if (e.key === 'Escape' && !rewardModal.classList.contains('hidden')) {
  1027. closeModal();
  1028. }
  1029. });
  1030. // Handle reward claim
  1031. claimRewardBtn.addEventListener('click', function () {
  1032. if (!this.disabled && acceptTermsCheckbox.checked) {
  1033. claimReward(userToken, userTable);
  1034. closeModal();
  1035. updateProgress(0);
  1036. }
  1037. });
  1038. // Handle terms checkbox
  1039. acceptTermsCheckbox.addEventListener('change', function () {
  1040. if (this.checked) {
  1041. claimRewardBtn.disabled = false;
  1042. claimRewardBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  1043. } else {
  1044. claimRewardBtn.disabled = true;
  1045. claimRewardBtn.classList.add('opacity-50', 'cursor-not-allowed');
  1046. }
  1047. });
  1048. }
  1049. /**
  1050. * Close success reward modal
  1051. */
  1052. function closeSuccessRewardModal() {
  1053. const successRewardModal = document.getElementById("successRewardModal");
  1054. successRewardModal.classList.add("hidden");
  1055. document.body.style.overflow = '';
  1056. }
  1057. /**
  1058. * Close reward modal and reset form
  1059. */
  1060. function closeModal() {
  1061. rewardModal.classList.add('hidden');
  1062. document.body.style.overflow = '';
  1063. // Reset form
  1064. acceptTermsCheckbox.checked = false;
  1065. claimRewardBtn.disabled = true;
  1066. claimRewardBtn.classList.add('opacity-50', 'cursor-not-allowed');
  1067. }
  1068. //--- Inicialización de la Aplicación ---
  1069. /**
  1070. * Initialize the application when DOM is loaded
  1071. */
  1072. document.addEventListener("DOMContentLoaded", async () => {
  1073. hideGUI();
  1074. const isCacheValid = await checkCache();
  1075. if (!isCacheValid) {
  1076. console.warn("Cache is invalid");
  1077. }
  1078. createGlobalLoader();
  1079. // Uncomment these lines when ready to initialize the full app:
  1080. initializeLoginModal();
  1081. // initializeApp();
  1082. });