app.js 45 KB

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