app.js 36 KB

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