lokesh341's picture
Update static/script.js
7efbd6f verified
raw
history blame
10.3 kB
let conversation = [
{ role: 'bot', message: 'Hi there! I\'m Chef Bot! May I know your name?' }
];
let selectedItems = [];
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 {
addMessage('bot', 'Please type something to continue! 😊');
}
}
function handleResponse(userInput) {
const lowerInput = userInput.toLowerCase();
let botResponse = '';
// Step 1: After name input
if (conversation.length === 2) {
botResponse = `Nice to meet you, ${userInput}! 😊 What type of food would you like to explore today?`;
displayOptions([
{ text: 'Vegetarian', class: 'green' },
{ text: 'Non-Vegetarian', class: 'red' },
{ text: 'Both', class: 'gray' }
]);
}
// Step 2: After dietary preference
else if (lowerInput === 'vegetarian' || lowerInput === 'non-vegetarian' || lowerInput === 'both') {
botResponse = `Awesome! Let me fetch some ${lowerInput} menu items for you...`;
addMessage('bot', botResponse);
fetchMenuItems(lowerInput);
return;
}
// Step 3: Search for specific items
else {
botResponse = `Looking for something with "${userInput}"...`;
addMessage('bot', botResponse);
suggestItems(userInput);
return;
}
addMessage('bot', botResponse);
}
// Fetch menu items from Salesforce
function fetchMenuItems(dietaryPreference) {
fetch('/get_menu_items', { method: 'GET' })
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Oops! Couldn’t fetch menu items: ${data.error}. Try again?`);
} else {
const filteredItems = data.menu_items.filter(item => {
if (dietaryPreference === 'both') return true;
// Client-side filtering (update if Salesforce supports this)
return dietaryPreference === 'vegetarian'
? item.name.toLowerCase().includes('veg')
: !item.name.toLowerCase().includes('veg');
});
if (filteredItems.length > 0) {
addMessage('bot', `Here are some ${dietaryPreference} menu items:`);
displayItemsList(filteredItems, 'menuItemsList');
} else {
addMessage('bot', `No ${dietaryPreference} items found. Try searching for something specific!`);
}
console.log(`Fetched menu items for ${dietaryPreference}:`, filteredItems);
}
})
.catch(error => {
addMessage('bot', `Error connecting to the database: ${error.message}. I’ll try again soon!`);
setTimeout(() => fetchMenuItems(dietaryPreference), 2000); // Retry after 2 seconds
});
}
// Fetch suggestions from Salesforce
function suggestItems(searchTerm) {
fetch('/suggest_items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ search_term: searchTerm })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Couldn’t find anything for "${searchTerm}": ${data.error}. Try another term?`);
} else if (data.suggestions.length > 0) {
addMessage('bot', `Found these suggestions for "${searchTerm}":`);
displayItemsList(data.suggestions, 'suggestionsList');
} else {
addMessage('bot', `No matches for "${searchTerm}". Maybe try "chicken" or "rice"?`);
}
console.log(`Suggestions for ${searchTerm}:`, data.suggestions);
})
.catch(error => {
addMessage('bot', `Error fetching suggestions: ${error.message}. Retrying...`);
setTimeout(() => suggestItems(searchTerm), 2000); // Retry after 2 seconds
});
}
// Fetch item details from Salesforce with improved error handling
function fetchItemDetails(itemName) {
fetch('/get_item_details', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item_name: itemName })
})
.then(response => response.json())
.then(data => {
if (data.error) {
addMessage('bot', `Sorry, couldn’t get details for "${itemName}": ${data.error}. Does it exist in our menu?`);
} else {
const details = data.item_details;
selectedItems.push(details);
addMessage('bot', `Here’s what I found for "${itemName}":`);
displaySelectedItems();
console.log(`Details fetched for ${itemName}:`, details);
}
})
.catch(error => {
addMessage('bot', `Error fetching details for "${itemName}": ${error.message}. I’ll retry...`);
setTimeout(() => fetchItemDetails(itemName), 2000); // Retry after 2 seconds
});
}
// Display items (menu items or suggestions)
function displayItemsList(items, containerId) {
const container = document.getElementById(containerId);
if (!container) {
console.error(`${containerId} container not found!`);
addMessage('bot', 'Something went wrong with the display. Please try again!');
return;
}
container.innerHTML = '';
items.forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.className = containerId === 'menuItemsList' ? 'ingredient-item' : 'suggestion-item';
const img = document.createElement('img');
img.src = item.image_url || 'https://via.placeholder.com/60';
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';
button.onclick = () => fetchItemDetails(item.name);
itemDiv.appendChild(img);
itemDiv.appendChild(name);
itemDiv.appendChild(button);
container.appendChild(itemDiv);
});
}
// Display selected items with details
function displaySelectedItems() {
const selectedArea = document.getElementById('itemDetails');
if (!selectedArea) {
console.error('Item details container not found!');
addMessage('bot', 'Can’t show details right now. Try again later!');
return;
}
selectedArea.innerHTML = '';
if (selectedItems.length === 0) {
selectedArea.innerHTML = '<div>No items selected yet!</div>';
} else {
selectedItems.forEach(item => {
const div = document.createElement('div');
div.innerHTML = `<strong>${item.name}</strong><br>Description: ${item.description}<br>Ingredients: ${item.ingredients}`;
selectedArea.appendChild(div);
});
}
}
// Display options (Vegetarian, Non-Vegetarian, Both)
function displayOptions(options) {
const chatMessages = document.getElementId('chatMessages');
if (!chatMessages) {
console.error('Chat messages container not found for options!');
return;
}
const optionsDiv = document.createElement('div');
optionsDiv.style.marginTop = '10px';
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 });
handleResponse(opt.text);
};
optionsDiv.appendChild(button);
});
const backButton = document.createElement('button');
backButton.textContent = 'Go Back';
backButton.className = 'option-button';
backButton.style.marginTop = '10px';
backButton.onclick = () => resetConversation();
optionsDiv.appendChild(document.createElement('br'));
optionsDiv.appendChild(backButton);
chatMessages.appendChild(optionsDiv);
}
// Reset conversation
function resetConversation() {
const userName = conversation.length > 1 ? conversation[1].message : 'Friend';
conversation = [
{ role: 'bot', message: `Hi there! I'm Chef Bot! May I know your name?` },
{ role: 'user', message: userName },
{ role: 'bot', message: `Nice to meet you, ${userName}! 😊 What type of food would you like to explore today?` }
];
selectedItems = [];
const chatMessages = document.getElementById('chatMessages');
chatMessages.innerHTML = '';
conversation.forEach(msg => addMessage(msg.role, msg.message));
displayOptions([
{ text: 'Vegetarian', class: 'green' },
{ text: 'Non-Vegetarian', class: 'red' },
{ text: 'Both', class: 'gray' }
]);
document.getElementById('suggestionsList').innerHTML = '';
document.getElementById('menuItemsList').innerHTML = '';
displaySelectedItems();
}
// Event listeners
document.getElementById('userInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
// Initial load
console.log('Chef Bot script loaded successfully!');