app.js 35 KB

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