app.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { initializeChat as serviceInitializeChat, sendMessage as serviceSendMessage, sendOrder, getProducts } from './service.js';
  2. let userName = '';
  3. let userTable = null;
  4. let products = [];
  5. let cart = [];
  6. let chatHistory = [
  7. { role: "system", content: "¡Hola! Soy tu asistente en Biergarten Klein. ¿Te gustaría una recomendación de nuestras cervezas artesanales?" }
  8. ];
  9. // --- Elementos del DOM ---
  10. const productListElement = document.getElementById("productList");
  11. const cartItemsElement = document.getElementById("cartItems");
  12. const cartTotalElement = document.getElementById("cartTotal");
  13. const emptyCartTextElement = document.getElementById("emptyCartText");
  14. const checkoutButton = document.getElementById("checkoutButton");
  15. const originalCheckoutButtonText = checkoutButton ? checkoutButton.textContent : "Finalizar Pedido";
  16. const chatMessagesElement = document.getElementById("chatMessages");
  17. const chatInputElement = document.getElementById("chatInput");
  18. const sendChatButton = document.getElementById("sendChatButton");
  19. const aiLoadingIndicator = document.getElementById("aiLoadingIndicator");
  20. // --- Modales ---
  21. const welcomeModal = document.getElementById("welcomeModal");
  22. const startOrderButton = document.getElementById("startOrderButton");
  23. const userNameInput = document.getElementById("userNameInput");
  24. const userTableInput = document.getElementById("userTableInput");
  25. const orderConfirmationModal = document.getElementById("orderConfirmationModal");
  26. const closeConfirmationModalButton = document.getElementById("closeConfirmationModalButton");
  27. const orderErrorModal = document.getElementById("orderErrorModal");
  28. const closeOrderErrorModalButton = document.getElementById("closeOrderErrorModalButton");
  29. const newOrderButton = document.getElementById("newOrderButton");
  30. const retryButton = document.getElementById("retryButton");
  31. // --- Loader Global ---
  32. let globalLoaderElement = null;
  33. function createGlobalLoader() {
  34. if (document.getElementById('globalLoader')) return;
  35. globalLoaderElement = document.createElement('div');
  36. globalLoaderElement.id = 'globalLoader';
  37. globalLoaderElement.className = 'fixed inset-0 bg-black bg-opacity-80 flex flex-col items-center justify-center z-[2000] transition-opacity duration-300 ease-in-out pointer-events-none';
  38. globalLoaderElement.style.opacity = '0';
  39. globalLoaderElement.innerHTML = `
  40. <div style="border: 6px solid rgba(255, 255, 255, 0.2); border-radius: 50%; border-top: 6px solid #dc2626; width: 60px; height: 60px; animation: spin 1s linear infinite;"></div>
  41. <p class="text-white text-xl mt-4">Procesando su pedido...</p>
  42. `;
  43. document.body.appendChild(globalLoaderElement);
  44. }
  45. function showGlobalLoader() {
  46. if (!globalLoaderElement) createGlobalLoader();
  47. globalLoaderElement.style.display = 'flex';
  48. setTimeout(() => { if (globalLoaderElement) globalLoaderElement.style.opacity = '1'; }, 10);
  49. }
  50. function hideGlobalLoader() {
  51. if (globalLoaderElement) {
  52. globalLoaderElement.style.opacity = '0';
  53. setTimeout(() => { if (globalLoaderElement) globalLoaderElement.style.display = 'none'; }, 300);
  54. }
  55. }
  56. document.getElementById("currentYear").textContent = new Date().getFullYear().toString();
  57. function formatPrice(price) {
  58. return price.toLocaleString("es-CL", { style: "currency", currency: "CLP" });
  59. }
  60. async function processOrder() {
  61. if (cart.length === 0) return;
  62. showGlobalLoader();
  63. if (checkoutButton) {
  64. checkoutButton.disabled = true;
  65. checkoutButton.textContent = "Procesando...";
  66. }
  67. try {
  68. const orderData = {
  69. customerName: userName,
  70. table: userTable,
  71. items: cart.map(item => ({ id: item.id, name: item.name, quantity: item.quantity, price: item.price, itemTotal: item.price * item.quantity })),
  72. totalAmount: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
  73. orderDate: new Date().toISOString(),
  74. };
  75. console.log("Enviando Pedido:", orderData);
  76. await sendOrder(orderData);
  77. if (orderConfirmationModal) orderConfirmationModal.style.display = "flex";
  78. } catch (error) {
  79. console.error("Error al procesar la orden:", error);
  80. if (orderErrorModal) {
  81. const errorMessageElement = orderErrorModal.querySelector('p.text-lg');
  82. if (errorMessageElement) {
  83. errorMessageElement.textContent = `Hubo un problema: ${error.message || "Por favor, inténtalo de nuevo."}`;
  84. }
  85. orderErrorModal.style.display = "flex";
  86. }
  87. } finally {
  88. hideGlobalLoader();
  89. if (checkoutButton) {
  90. checkoutButton.disabled = cart.length === 0;
  91. checkoutButton.textContent = originalCheckoutButtonText;
  92. }
  93. }
  94. }
  95. async function renderProducts() {
  96. if (!productListElement) return;
  97. productListElement.innerHTML = "";
  98. products = await getProducts();
  99. products.forEach(product => {
  100. const productCardContainer = document.createElement('div');
  101. productCardContainer.innerHTML = `
  102. <div class="product-card rounded-lg shadow-lg overflow-hidden transition-all duration-300 hover:shadow-2xl hover:transform hover:-translate-y-1 flex flex-col sm:flex-row">
  103. <img src="${product.image}" alt="[Imagen de ${product.name}]" class="w-full sm:w-1/3 h-48 sm:h-auto object-cover">
  104. <div class="p-6 flex flex-col justify-between flex-grow">
  105. <div>
  106. <h4 class="text-xl font-semibold mb-1">${product.name}</h4>
  107. <p class="text-gray-400 text-base mb-3">${product.description}</p>
  108. </div>
  109. <div class="flex justify-between items-center mt-4">
  110. <span class="text-2xl font-bold accent-red">${formatPrice(product.price)}</span>
  111. <button data-product-id="${product.id}" class="add-to-cart-btn bg-accent-red hover:bg-red-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-300 ease-in-out text-sm">
  112. Agregar
  113. </button>
  114. </div>
  115. </div>
  116. </div>
  117. `;
  118. productListElement.appendChild(productCardContainer.firstElementChild);
  119. });
  120. document.querySelectorAll('.add-to-cart-btn').forEach(button => {
  121. button.addEventListener('click', (event) => {
  122. const productId = parseInt(event.target.closest('button').dataset.productId);
  123. addToCart(productId, event.target.closest('button'));
  124. });
  125. });
  126. }
  127. window.addToCart = async (productId, buttonElement = null) => {
  128. const product = products.find(p => p.id === productId);
  129. if (!product) return;
  130. const cartItem = cart.find(item => item.id === productId);
  131. if (cartItem) {
  132. cartItem.quantity++;
  133. } else {
  134. cart.push({ ...product, quantity: 1 });
  135. }
  136. if (buttonElement) {
  137. const originalText = buttonElement.textContent;
  138. buttonElement.textContent = "✔ Agregado!";
  139. buttonElement.classList.replace('bg-accent-red', 'bg-green-500');
  140. buttonElement.classList.remove("hover:bg-red-700");
  141. buttonElement.disabled = true;
  142. setTimeout(() => {
  143. buttonElement.textContent = originalText;
  144. buttonElement.classList.replace('bg-green-500', 'bg-accent-red');
  145. buttonElement.classList.add("hover:bg-red-700");
  146. buttonElement.disabled = false;
  147. }, 1500);
  148. }
  149. updateCartDisplay();
  150. };
  151. window.removeFromCart = (productId, removeAll = false) => {
  152. const itemIndex = cart.findIndex(item => item.id === productId);
  153. if (itemIndex > -1) {
  154. if (removeAll || cart[itemIndex].quantity === 1) {
  155. cart.splice(itemIndex, 1);
  156. } else {
  157. cart[itemIndex].quantity--;
  158. }
  159. }
  160. updateCartDisplay();
  161. };
  162. function updateCartDisplay() {
  163. if (!cartItemsElement || !emptyCartTextElement || !checkoutButton) return;
  164. cartItemsElement.innerHTML = "";
  165. if (cart.length === 0) {
  166. emptyCartTextElement.classList.remove("hidden");
  167. checkoutButton.disabled = true;
  168. } else {
  169. emptyCartTextElement.classList.add("hidden");
  170. checkoutButton.disabled = false;
  171. cart.forEach(item => {
  172. const cartItemHTML = `
  173. <div class="flex justify-between items-center border-b border-gray-700 pb-2 last:border-b-0 mb-2">
  174. <div>
  175. <h4 class="font-semibold text-base">${item.name} <span class="text-sm text-gray-400">(x${item.quantity})</span></h4>
  176. <p class="text-sm accent-red">${formatPrice(item.price * item.quantity)}</p>
  177. </div>
  178. <div class="flex items-center gap-1 sm:gap-2">
  179. <button onclick="addToCart(${item.id})" class="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>
  180. <button onclick="removeFromCart(${item.id})" class="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>
  181. <button onclick="removeFromCart(${item.id}, true)" class="text-red-500 hover:text-red-400 text-base sm:text-lg p-1 rounded-full hover:bg-gray-700 transition-colors">
  182. <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>
  183. </button>
  184. </div>
  185. </div>
  186. `;
  187. cartItemsElement.innerHTML += cartItemHTML;
  188. });
  189. }
  190. calculateTotal();
  191. }
  192. function calculateTotal() {
  193. if (!cartTotalElement) return;
  194. const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  195. cartTotalElement.textContent = formatPrice(total);
  196. }
  197. // --- Lógica del Chat ---
  198. function displayChatMessage(sender, message) {
  199. if (!chatMessagesElement) return;
  200. const bubbleClass = sender === "user" ? "chat-bubble-user" : "chat-bubble-ai";
  201. const messageDiv = document.createElement("div");
  202. messageDiv.classList.add("chat-bubble", bubbleClass);
  203. messageDiv.innerHTML = sender === "ai" && window.marked ? marked.parse(message) : message;
  204. chatMessagesElement.appendChild(messageDiv);
  205. chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
  206. }
  207. async function sendMessageToAI() {
  208. if (!chatInputElement || !aiLoadingIndicator) return;
  209. const userInput = chatInputElement.value.trim();
  210. if (!userInput) return;
  211. displayChatMessage("user", userInput);
  212. chatInputElement.value = '';
  213. aiLoadingIndicator.classList.remove("hidden");
  214. try {
  215. const response = await serviceSendMessage(userInput, chatHistory);
  216. if (!response) {
  217. displayChatMessage("ai", "Hubo un problema al conectar con el Chef IA.");
  218. } else if (response === "not_init") {
  219. displayChatMessage("ai", "El chat no está inicializado. Intentando reconectar...");
  220. if (await serviceInitializeChat()) {
  221. displayChatMessage("ai", "Reconexión exitosa. Por favor, envía tu mensaje de nuevo.");
  222. } else {
  223. displayChatMessage("ai", "Fallo la reconexión. Por favor, refresca la página.");
  224. }
  225. } else if (response.assistantResponse) {
  226. chatHistory = response.messageList;
  227. displayChatMessage("ai", response.assistantResponse);
  228. }
  229. } catch (error) {
  230. console.error("Error enviando mensaje a IA:", error);
  231. displayChatMessage("ai", `Error: ${error.message || "No se pudo conectar con el Chef IA."}`);
  232. } finally {
  233. aiLoadingIndicator.classList.add("hidden");
  234. if (chatInputElement) chatInputElement.focus();
  235. }
  236. }
  237. // --- Event Listeners ---
  238. document.addEventListener("DOMContentLoaded", async () => {
  239. createGlobalLoader();
  240. updateCartDisplay();
  241. if (welcomeModal && startOrderButton) {
  242. startOrderButton.addEventListener('click', () => {
  243. const name = userNameInput.value.trim();
  244. const table = userTableInput.value;
  245. if (name && table) {
  246. userName = name;
  247. userTable = parseInt(table);
  248. welcomeModal.style.display = 'none';
  249. // Iniciar la app después de obtener los datos
  250. initializeApp();
  251. } else {
  252. alert('Por favor, ingresa tu nombre y número de mesa para continuar.');
  253. }
  254. });
  255. }
  256. async function initializeApp() {
  257. await renderProducts();
  258. try {
  259. if (await serviceInitializeChat()) {
  260. console.log("Chat AI Asistente inicializado exitosamente.");
  261. } else {
  262. console.warn("Chat AI no pudo inicializarse.");
  263. displayChatMessage("ai", "No se pudo conectar con el Chef IA en este momento.");
  264. }
  265. } catch (error) {
  266. console.error("Error durante la inicialización del Chat AI:", error);
  267. displayChatMessage("ai", "Error al iniciar el Chef IA.");
  268. }
  269. }
  270. });
  271. if (checkoutButton) checkoutButton.addEventListener("click", processOrder);
  272. if (closeConfirmationModalButton) closeConfirmationModalButton.addEventListener("click", () => { orderConfirmationModal.style.display = "none"; });
  273. if (closeOrderErrorModalButton) closeOrderErrorModalButton.addEventListener("click", () => { orderErrorModal.style.display = "none"; });
  274. if (newOrderButton) {
  275. newOrderButton.addEventListener("click", () => {
  276. orderConfirmationModal.style.display = "none";
  277. cart = [];
  278. updateCartDisplay();
  279. });
  280. }
  281. if (retryButton) retryButton.addEventListener("click", () => { orderErrorModal.style.display = "none"; });
  282. if (sendChatButton) sendChatButton.addEventListener("click", sendMessageToAI);
  283. if (chatInputElement) {
  284. chatInputElement.addEventListener("keypress", (event) => {
  285. if (event.key === "Enter") {
  286. event.preventDefault();
  287. sendMessageToAI();
  288. }
  289. });
  290. }