| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- import { initializeChat as serviceInitializeChat, sendMessage as serviceSendMessage, sendOrder, getProducts, existsUser } from './service.js';
- let userName = '';
- let userTable = null;
- let products = [];
- let itsEmpty = true;
- let cart = [];
- let chatHistory = [
- { role: "system", content: "¡Hola! Soy tu asistente en Biergarten Klein. ¿Te gustaría una recomendación de nuestras cervezas artesanales?" }
- ];
- // --- Elementos del DOM ---
- const productListElement = document.getElementById("productList");
- const cartItemsElement = document.getElementById("cartItems");
- const cartTotalElement = document.getElementById("cartTotal");
- const emptyCartTextElement = document.getElementById("emptyCartText");
- const checkoutButton = document.getElementById("checkoutButton");
- const originalCheckoutButtonText = checkoutButton ? checkoutButton.textContent : "Finalizar Pedido";
- console.log(originalCheckoutButtonText)
- const chatMessagesElement = document.getElementById("chatMessages");
- const chatInputElement = document.getElementById("chatInput");
- const sendChatButton = document.getElementById("sendChatButton");
- const aiLoadingIndicator = document.getElementById("aiLoadingIndicator");
- const cartCountElement = document.getElementById("cartCount");
- // --- Loader Global ---
- let globalLoaderElement = null;
- function createGlobalLoader() {
- if (document.getElementById('globalLoader')) return;
- globalLoaderElement = document.createElement('div');
- globalLoaderElement.id = 'globalLoader';
- 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';
- globalLoaderElement.style.opacity = '0';
- globalLoaderElement.innerHTML = `
- <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>
- <p class="text-white text-xl mt-4">Procesando su pedido...</p>
- `;
- document.body.appendChild(globalLoaderElement);
- }
- function showGlobalLoader() {
- if (!globalLoaderElement) createGlobalLoader();
- globalLoaderElement.style.display = 'flex';
- setTimeout(() => { if (globalLoaderElement) globalLoaderElement.style.opacity = '1'; }, 10);
- }
- function hideGlobalLoader() {
- if (globalLoaderElement) {
- globalLoaderElement.style.opacity = '0';
- setTimeout(() => { if (globalLoaderElement) globalLoaderElement.style.display = 'none'; }, 300);
- }
- }
- function formatPrice(price) {
- return price.toLocaleString("es-CL", { style: "currency", currency: "CLP" });
- }
- async function processOrder() {
- if (cart.length === 0) return;
- showGlobalLoader();
- if (checkoutButton) {
- checkoutButton.disabled = true;
- checkoutButton.textContent = "Procesando...";
- }
- try {
- const orderData = {
- customerName: userName,
- table: userTable,
- items: cart.map(item => ({ id: item.id, name: item.name, quantity: item.quantity, price: item.price, itemTotal: item.price * item.quantity })),
- totalAmount: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
- orderDate: new Date().toLocaleString('sv-SE').replace(' ', 'T')
- };
- console.log("Enviando Pedido:", orderData);
- await sendOrder(orderData);
- alert("Pedido enviado con éxito.");
- cart = []
- updateCartDisplay();
- } catch (error) {
- console.error("Error al procesar la orden:", error);
- alert(`Hubo un problema: ${error.message || "Por favor, inténtalo de nuevo."}`);
-
-
- } finally {
- hideGlobalLoader();
- checkoutButton.disabled = cart.length === 0;
- checkoutButton.textContent = originalCheckoutButtonText
- }
- }
- async function renderProducts() {
- if (!productListElement) return;
- const template = document.getElementById("product-card-template");
- if (!template) return;
- productListElement.innerHTML = "";
- products = await getProducts();
- products.forEach(product => {
- const clone = template.content.cloneNode(true);
- clone.querySelector(".product-type").textContent = product.type || "Sin categoría";
- clone.querySelector(".product-name").textContent = product.name;
- clone.querySelector(".product-description").textContent = product.description;
- clone.querySelector(".product-price").textContent = formatPrice(product.price);
- clone.querySelector(".product-image").style.backgroundImage = `url('${product.image}')`;
- const addBtn = clone.querySelector(".add-to-cart-btn");
- addBtn.dataset.productId = product.id; // el listener usa esta info
- productListElement.appendChild(clone);
- });
- document.querySelectorAll('.add-to-cart-btn').forEach(button => {
- button.addEventListener('click', (event) => {
- const productId = parseInt(event.target.dataset.productId);
- addToCart(productId, event.target);
- });
- });
- }
- window.addToCart = async (productId, buttonElement = null) => {
- const product = products.find(p => p.id === productId);
- if (!product) return;
- const cartItem = cart.find(item => item.id === productId);
- if (cartItem) {
- cartItem.quantity++;
- } else {
- cart.push({ ...product, quantity: 1 });
- }
- if (buttonElement) {
- const originalHTML = buttonElement.innerHTML;
- buttonElement.textContent = "✔ Agregado!";
- buttonElement.classList.replace('bg-accent-red', 'bg-green-500');
- buttonElement.classList.remove("hover:bg-red-700");
- buttonElement.disabled = true;
- setTimeout(() => {
- buttonElement.innerHTML = originalHTML;
- buttonElement.classList.replace('bg-green-500', 'bg-accent-red');
- buttonElement.classList.add("hover:bg-red-700");
- buttonElement.disabled = false;
- }, 1500);
- }
- updateCartDisplay();
- // Dentro de window.addToCart (después de updateCartDisplay())
- if (typeof showToast === "function") showToast(`${product.name} agregado al carrito`);
- };
- window.removeFromCart = (productId, removeAll = false) => {
- const itemIndex = cart.findIndex(item => item.id === productId);
- if (itemIndex > -1) {
- if (removeAll || cart[itemIndex].quantity === 1) {
- cart.splice(itemIndex, 1);
- } else {
- cart[itemIndex].quantity--;
- }
- }
- updateCartDisplay();
- };
- function updateCartDisplay() {
- if (!cartItemsElement || !emptyCartTextElement || !checkoutButton || !cartCountElement) return;
- cartItemsElement.innerHTML = "";
- cartCountElement.textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
- if (cart.length === 0) {
- cartCountElement.classList.add("hidden");
- emptyCartTextElement.classList.remove("hidden");
- checkoutButton.disabled = true;
- itsEmpty = true;
- } else {
- cartCountElement.classList.remove("hidden");
- if (cartCountElement && itsEmpty) {
- itsEmpty = false;
- cartCountElement.animate([
- { transform: 'scale(0)' },
- { transform: 'scale(1)' }
- ],{
- duration: 300,
- iterations: 1,
- easing: 'ease-in-out'
- })
- }else {
- cartCountElement.animate([
- { transform: 'scale(1) rotate(0deg)' },
- { transform: 'scale(1.2) rotate(180deg)' },
- { transform: 'scale(1) rotate(360deg)' }
- ], {
- duration: 300,
- iterations: 1,
- easing: 'ease-in-out'
- })
- }
- emptyCartTextElement.classList.add("hidden");
- checkoutButton.disabled = false;
- cart.forEach(item => {
- const cartItemHTML = `
- <div class="flex justify-between items-center border-b border-gray-700 pb-2 last:border-b-0 mb-2">
- <div>
- <h4 class="font-semibold text-base">${item.name} <span class="text-sm text-gray-400">(x${item.quantity})</span></h4>
- <p class="text-sm accent-red">${formatPrice(item.price * item.quantity)}</p>
- </div>
- <div class="flex items-center gap-1 sm:gap-2">
- <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>
- <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>
- <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">
- <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>
- </button>
- </div>
- </div>
- `;
- cartItemsElement.innerHTML += cartItemHTML;
- });
- }
- calculateTotal();
- }
- function calculateTotal() {
- if (!cartTotalElement) return;
- const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
- cartTotalElement.textContent = formatPrice(total);
- }
- // --- Lógica del Chat ---
- function displayChatMessage(sender, message) {
- if (!chatMessagesElement) return;
- const bubbleClass = sender === "user" ? "chat-bubble-user" : "chat-bubble-ai";
- const messageDiv = document.createElement("div");
- messageDiv.classList.add("chat-bubble", bubbleClass);
- messageDiv.innerHTML = sender === "ai" && window.marked ? marked.parse(message) : message;
- chatMessagesElement.appendChild(messageDiv);
- chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
- }
- async function sendMessageToAI() {
- if (!chatInputElement || !aiLoadingIndicator) return;
- const userInput = chatInputElement.value.trim();
- if (!userInput) return;
- displayChatMessage("user", userInput);
- chatInputElement.value = '';
- aiLoadingIndicator.classList.remove("hidden");
- try {
- const response = await serviceSendMessage(userInput, chatHistory);
- if (!response) {
- displayChatMessage("ai", "Hubo un problema al conectar con el Chef IA.");
- } else if (response === "not_init") {
- if (await serviceInitializeChat()) {
- const response = await serviceSendMessage(userInput, chatHistory, userName);
- if (response) {
- chatHistory = response.messageList;
- displayChatMessage("ai", response.assistantResponse);
- } else {
- displayChatMessage("ai", "Hubo un problema al enviar el mensaje.");
- }
- } else {
- displayChatMessage("ai", "Fallo la reconexión. Por favor, refresca la página.");
- }
- } else if (response.assistantResponse) {
- chatHistory = response.messageList;
- displayChatMessage("ai", response.assistantResponse);
- }
- } catch (error) {
- console.error("Error enviando mensaje a IA:", error);
- displayChatMessage("ai", `Error: ${error.message || "No se pudo conectar con el Chef IA."}`);
- } finally {
- aiLoadingIndicator.classList.add("hidden");
- if (chatInputElement) chatInputElement.focus();
- }
- }
- // --- Event Listeners ---
- document.addEventListener("DOMContentLoaded", async () => {
- createGlobalLoader();
- updateCartDisplay();
- async function initializeApp() {
- await renderProducts();
- try {
- if (await serviceInitializeChat()) {
- console.log("Chat AI Asistente inicializado exitosamente.");
- } else {
- console.warn("Chat AI no pudo inicializarse.");
- displayChatMessage("ai", "No se pudo conectar con el Chef IA en este momento.");
- }
- } catch (error) {
- console.error("Error durante la inicialización del Chat AI:", error);
- displayChatMessage("ai", "Error al iniciar la IA.");
- }
- }
- if (checkoutButton) checkoutButton.addEventListener("click", processOrder);
- /* ---------- MANEJO DEL POPUP INICIAL ---------- */
- const sessionModal = document.getElementById('sessionModal');
- const sessionAcceptBtn = document.getElementById('sessionAcceptBtn');
- const tableInput = document.getElementById('tableInput');
- const clientCodeInput = document.getElementById('clientCodeInput');
- sessionAcceptBtn.addEventListener('click', async () => {
- const mesa = parseInt(tableInput.value, 10);
- const codigo = clientCodeInput.value.trim();
- if (!mesa || !codigo) {
- alert('Por favor completa ambos campos.');
- return;
- }
- const existUser = await existsUser(codigo);
- if (!existUser.success) {
- alert('El código de cliente no existe.');
- return;
- }
- userName = existUser.userName;
- //destruye el modal
- sessionModal.remove();
- startSession(mesa);
- });
- /* ---- FUNCIÓN que recibe los dos parámetros ---- */
- function startSession(mesa) {
- userTable = mesa;
- initializeApp();
- }
- });
- if (sendChatButton) sendChatButton.addEventListener("click", sendMessageToAI);
- if (chatInputElement) {
- chatInputElement.addEventListener("keypress", (event) => {
- if (event.key === "Enter") {
- event.preventDefault();
- sendMessageToAI();
- }
- });
- }
|