app.js 36 KB

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