app.js 37 KB

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