app.js 39 KB

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