app.js 14 KB

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