app.js 37 KB

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