app.js 35 KB

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