chatbot8 / static /script.js
nagasurendra's picture
Update static/script.js
3909544 verified
let conversation = [
{ role: 'bot', message: "Hi there! I'm Chef Bot! May I know your name?" }
];
let selectedIngredients = [];
let selectedMenuItem = null;
let cart = [];
function addMessage(role, message) {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found!');
return;
}
const messageDiv = document.createElement('div');
messageDiv.className = role === 'bot' ? 'bot-message' : 'user-message';
messageDiv.textContent = message;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
console.log(`Added ${role} message: ${message}`);
}
function sendMessage() {
const userInput = document.getElementById('userInput');
if (!userInput) {
console.error('User input field not found!');
return;
}
const message = userInput.value.trim();
if (message) {
addMessage('user', message);
conversation.push({ role: 'user', message: message });
userInput.value = '';
setTimeout(() => handleResponse(message), 500);
} else {
console.warn('Empty message!');
}
}
function handleResponse(userInput) {
const lastMessage = conversation[conversation.length - 1].message.toLowerCase();
let botResponse = '';
let options = [];
if (conversation.length === 2) { // After name input
botResponse = `Nice to meet you, ${userInput}! 😊 Let's create your perfect meal! What type of food would you prefer?`;
options = [
{ text: 'Vegetarian', class: 'green' },
{ text: 'Non-Vegetarian', class: 'red' }
];
}else if (lastMessage.includes('non-vegetarian')) {
conversation.push({ role: 'user', message: 'Non-Vegetarian' });
console.log("Food preference selected: Non-Vegetarian");
botResponse = 'Great choice! 🍽️ Please select a non-vegetarian option:';
fetchIngredients('non-vegetarian');
return;
}
else if (lastMessage.includes('vegetarian')) {
conversation.push({ role: 'user', message: 'Vegetarian' });
console.log("Food preference selected: Vegetarian");
botResponse = 'Great choice! 🍽️ Here are some vegetarian ingredients:';
fetchIngredients('vegetarian');
return;
} else if (lastMessage.includes('chicken') || lastMessage.includes('beef') || lastMessage.includes('lamb')) {
conversation.push({ role: 'user', message: lastMessage });
console.log(`Non-veg option selected: ${lastMessage}`);
botResponse = `Great! Here are some ${lastMessage} ingredients available:`;
fetchIngredients(lastMessage.toLowerCase());
return;
} else if (lastMessage.includes('yes') && selectedMenuItem) {
botResponse = 'Here are some ingredients to customize your dish:';
handleYesResponse(); // Fetch non-veg ingredients for customization
return;
} else if (lastMessage.includes('no') && selectedMenuItem) {
addToCart(selectedMenuItem);
botResponse = 'Item added to cart! Would you like to order more?';
options = [
{ text: 'Yes', class: 'green' },
{ text: 'No', class: 'red' }
];
selectedMenuItem = null;
}
addMessage('bot', botResponse);
if (options.length > 0) {
displayOptions(options);
}
}
function handleYesResponse() {
const botResponse = 'Here is your selected dish:';
addMessage('bot', botResponse);
// Display the selected menu item (Name, Image, etc.)
// Fetch ingredients for customization (both veg and non-veg)
fetchIngredientsForCustomization('both');
}
function fetchIngredientsForCustomization(foodPreference) {
fetch('/get_ingredients_for_customization', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ dietary_preference: foodPreference })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Sorry, there was an error fetching ingredients: ${data.error}`);
} else {
const ingredients = data.ingredients || [];
addMessage('bot', 'Please select ingredients:');
displayCustomizationIngredients(ingredients);
}
})
.catch(error => {
addMessage('bot', `Error: Unable to connect to the ingredient database. ${error.message}`);
});
}
function displayCustomizationIngredients(ingredients) {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for customization ingredients!');
return;
}
// Clear previous ingredient lists and selected area
let ingredientsList = document.querySelector('.customization-ingredients-list');
if (!ingredientsList) {
ingredientsList = document.createElement('div');
ingredientsList.className = 'customization-ingredients-list';
chatMessages.appendChild(ingredientsList);
} else {
ingredientsList.innerHTML = ''; // Clear previous list
}
let selectedArea = document.querySelector('.selected-customization-ingredients');
if (!selectedArea) {
selectedArea = document.createElement('div');
selectedArea.className = 'selected-customization-ingredients';
chatMessages.appendChild(selectedArea);
} else {
selectedArea.innerHTML = ''; // Clear previous selections
}
// Display New Ingredients
ingredients.forEach(ingredient => {
const item = document.createElement('div');
item.className = 'ingredient-item';
const img = document.createElement('img');
img.src = ingredient.image_url || 'https://via.placeholder.com/80';
img.alt = ingredient.name;
const name = document.createElement('div');
name.textContent = ingredient.name;
name.style.textAlign = 'center';
name.style.marginTop = '5px';
name.style.fontSize = '12px';
const button = document.createElement('button');
button.textContent = 'Add';
button.onclick = () => {
// Create the description like "Paneer Biryani with Coriander Powder"
const addedIngredient = ingredient.name;
// Ensure that we don't add the same combination twice
if (!selectedIngredients.some(item => item.name === addedIngredient)) {
selectedIngredients.push({ name: addedIngredient, image_url: ingredient.image_url });
displaySelectedCustomizationIngredients(); // Update selected ingredients display
}
};
item.appendChild(img);
item.appendChild(name);
item.appendChild(button);
ingredientsList.appendChild(item);
});
}
// Display the selected ingredients in a single line
function displaySelectedCustomizationIngredients() {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for selected customization ingredients!');
return;
}
let selectedArea = document.querySelector('.selected-customization-ingredients');
if (!selectedArea) {
selectedArea = document.createElement('div');
selectedArea.className = 'selected-customization-ingredients';
chatMessages.appendChild(selectedArea);
} else {
selectedArea.innerHTML = ''; // Clear previous selections
}
// Collect selected ingredients in a single line
const selectedIngredientsText = selectedIngredients.length > 0
? selectedMenuItem.name + " with " + selectedIngredients.map(ingredient => ingredient.name).join(', ')
: "";
// Display the ingredients as a single line
const ingredientsDiv = document.createElement('div');
ingredientsDiv.textContent = selectedIngredientsText;
selectedArea.appendChild(ingredientsDiv);
// Ensure the submit button and custom instructions box appear once and do not disappear
if (!document.querySelector('.submit-customization-button')) {
let submitButton = document.createElement('button');
submitButton.className = 'submit-customization-button';
submitButton.textContent = 'Submit';
submitButton.onclick = submitCustomizationIngredients;
chatMessages.appendChild(submitButton);
// Adding a text area for custom instructions
const textarea = document.createElement('textarea');
textarea.placeholder = 'Enter any special instructions...';
selectedArea.appendChild(textarea);
}
}
function submitCustomizationIngredients() {
// Handle the submission of ingredients and instructions here
console.log("Ingredients submitted:", selectedIngredients);
// You can also handle the custom instructions from the textarea if needed
}
function submitCustomizationIngredients() {
const textarea = document.querySelector('.selected-customization-ingredients textarea');
const instructions = textarea ? textarea.value.trim() : '';
fetch('/submit_customization_ingredients', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ ingredients: selectedIngredients, instructions: instructions })
})
.then(response => response.json())
.then(data => {
if (data.success) {
addMessage('bot', 'Ingredients submitted successfully! Would you like to order more?');
const options = [
{ text: 'Yes', class: 'green' },
{ text: 'No', class: 'red' }
];
displayOptions(options);
} else {
addMessage('bot', 'There was an issue submitting your ingredients. Please try again.');
}
})
.catch(error => {
addMessage('bot', `Error: ${error.message}`);
});
}
function fetchIngredients(foodPreference) {
fetch('/get_ingredients', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ dietary_preference: foodPreference })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Sorry, there was an error fetching ingredients: ${data.error}`);
} else {
const ingredients = data.ingredients || [];
addMessage('bot', 'Please select ingredients:');
displayIngredientsList(ingredients);
displaySelectedIngredients();
}
})
.catch(error => {
addMessage('bot', `Error: Unable to connect to the ingredient database. ${error.message}`);
});
}
function fetchMenuItems(category) {
fetch('/get_menu_items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ category: category })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Sorry, there was an error fetching menu items: ${data.error}`);
} else {
const menuItems = data.menu_items || [];
addMessage('bot', 'Here are some dishes based on your selection:');
displayMenuItems(menuItems);
}
})
.catch(error => {
addMessage('bot', `Error: Unable to connect to the menu database. ${error.message}`);
});
}
function displayIngredientsList(ingredients) {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for ingredients!');
return;
}
let ingredientsList = document.querySelector('.ingredients-list');
if (!ingredientsList) {
ingredientsList = document.createElement('div');
ingredientsList.className = 'ingredients-list';
chatMessages.appendChild(ingredientsList);
} else {
ingredientsList.innerHTML = '';
}
ingredients.forEach(ingredient => {
const item = document.createElement('div');
item.className = 'ingredient-item';
const img = document.createElement('img');
img.src = ingredient.image_url || 'https://via.placeholder.com/80';
img.alt = ingredient.name;
const name = document.createElement('div');
name.textContent = ingredient.name;
name.style.textAlign = 'center';
name.style.marginTop = '5px';
name.style.fontSize = '12px';
const button = document.createElement('button');
button.textContent = 'Add';
button.onclick = () => {
if (!selectedIngredients.some(item => item.name === ingredient.name)) {
selectedIngredients.push(ingredient);
displaySelectedIngredients();
}
};
item.appendChild(img);
item.appendChild(name);
item.appendChild(button);
ingredientsList.appendChild(item);
});
}
function displayMenuItems(menuItems) {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for menu items!');
return;
}
let menuItemsList = document.querySelector('.menu-items-list');
if (!menuItemsList) {
menuItemsList = document.createElement('div');
menuItemsList.className = 'menu-items-list';
chatMessages.appendChild(menuItemsList);
} else {
menuItemsList.innerHTML = '';
}
menuItems.forEach(item => {
const menuItem = document.createElement('div');
menuItem.className = 'menu-item';
const img = document.createElement('img');
img.src = item.image_url || 'https://via.placeholder.com/80';
img.alt = item.name;
const name = document.createElement('div');
name.textContent = item.name;
name.style.textAlign = 'center';
name.style.marginTop = '5px';
name.style.fontSize = '12px';
const button = document.createElement('button');
button.textContent = 'Add to Cart';
button.onclick = () => {
selectedMenuItem = item;
addMessage('bot', `World-class selection! Would you like to customize your dish further?`);
const options = [
{ text: 'Yes', class: 'green' },
{ text: 'No', class: 'red' }
];
displayOptions(options);
};
menuItem.appendChild(img);
menuItem.appendChild(name);
menuItem.appendChild(button);
menuItemsList.appendChild(menuItem);
});
}
function displaySelectedIngredients() {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for selected ingredients!');
return;
}
let selectedArea = document.querySelector('.selected-ingredients');
if (!selectedArea) {
selectedArea = document.createElement('div');
selectedArea.className = 'selected-ingredients';
chatMessages.appendChild(selectedArea);
} else {
selectedArea.innerHTML = '';
}
selectedIngredients.forEach(ingredient => {
const div = document.createElement('div');
div.textContent = ingredient.name;
selectedArea.appendChild(div);
});
if (selectedIngredients.length > 0) {
let submitButton = document.querySelector('.submit-button');
if (!submitButton) {
submitButton = document.createElement('button');
submitButton.className = 'submit-button';
submitButton.textContent = 'Submit Ingredients';
submitButton.onclick = submitIngredients;
chatMessages.appendChild(submitButton);
}
}
}
function submitIngredients() {
fetch('/submit_ingredients', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ ingredients: selectedIngredients })
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Extract the ingredient names from the selectedIngredients array
const ingredientNames = selectedIngredients.map(ingredient => ingredient.name.toLowerCase()).join(' ');
// Fetch menu items based on ingredient names
fetchMenuItems(ingredientNames);
} else {
addMessage('bot', 'There was an issue submitting your ingredients. Please try again.');
}
})
.catch(error => {
addMessage('bot', `Error: ${error.message}`);
});
}
function fetchMenuItems(ingredientNames) {
fetch('/get_menu_items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ ingredient_names: ingredientNames })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Sorry, there was an error fetching menu items: ${data.error}`);
} else {
const menuItems = data.menu_items || [];
addMessage('bot', 'Here are some dishes based on your selected ingredients:');
displayMenuItems(menuItems);
}
})
.catch(error => {
addMessage('bot', `Error: Unable to connect to the menu database. ${error.message}`);
});
}
function displayCustomizationInput() {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for customization input!');
return;
}
let customizationArea = document.querySelector('.customization-input');
if (!customizationArea) {
customizationArea = document.createElement('div');
customizationArea.className = 'customization-input';
const textarea = document.createElement('textarea');
textarea.placeholder = 'Enter any special instructions...';
const submitButton = document.createElement('button');
submitButton.textContent = 'Submit Instructions';
submitButton.onclick = () => {
const instructions = textarea.value.trim();
if (instructions) {
addMessage('user', instructions);
conversation.push({ role: 'user', message: instructions });
}
addToCart({ ...selectedMenuItem, instructions, ingredients: selectedIngredients });
addMessage('bot', 'Item added to cart! Would you like to order more?');
const options = [
{ text: 'Yes', class: 'green' },
{ text: 'No', class: 'red' }
];
displayOptions(options);
selectedMenuItem = null;
selectedIngredients = [];
};
customizationArea.appendChild(textarea);
customizationArea.appendChild(submitButton);
chatMessages.appendChild(customizationArea);
}
}
function addToCart(item) {
cart.push(item);
console.log('Cart:', cart);
}
function displayOptions(options) {
const chatMessages = document.getElementById('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for options!');
return;
}
options.forEach(opt => {
const button = document.createElement('button');
button.textContent = opt.text;
button.className = `option-button ${opt.class}`;
button.onclick = () => {
addMessage('user', opt.text);
conversation.push({ role: 'user', message: opt.text });
chatMessages.innerHTML = '';
conversation.forEach(msg => addMessage(msg.role, msg.message));
setTimeout(() => handleResponse(opt.text), 500);
};
chatMessages.appendChild(button);
});
chatMessages.appendChild(document.createElement('br'));
const backButton = document.createElement('button');
backButton.textContent = 'Go Back';
backButton.className = 'option-button';
backButton.onclick = () => {
conversation.pop();
selectedIngredients = [];
selectedMenuItem = null;
chatMessages.innerHTML = '';
conversation.forEach(msg => addMessage(msg.role, msg.message));
setTimeout(() => handleResponse(conversation[conversation.length - 1].message), 500);
};
chatMessages.appendChild(backButton);
}
document.getElementById('userInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
console.log('Script loaded successfully');