new functions for saving translations into db and more

This commit is contained in:
Mateo Körber Belmonte
2025-03-13 21:40:08 +01:00
parent 39995d6e75
commit 0a4dad7966
+248 -35
View File
@@ -274,17 +274,11 @@ async function sendAiTranslateRequest() {
// Format the data as described in the prompt
let promptText = '';
// Store original dishes for reference
const originalDishes = [];
data.forEach(entry => {
// Add meat dish
if (entry.meat_main) {
promptText += `${entry.meat_main}\n`;
originalDishes.push({
main: entry.meat_main,
side: entry.meat_side || ''
});
if (entry.meat_side) {
promptText += `${entry.meat_side}\n\n`;
@@ -296,10 +290,6 @@ async function sendAiTranslateRequest() {
// Add vegetarian dish
if (entry.veggi_main) {
promptText += `${entry.veggi_main}\n`;
originalDishes.push({
main: entry.veggi_main,
side: entry.veggi_side || ''
});
if (entry.veggi_side) {
promptText += `${entry.veggi_side}\n\n`;
@@ -325,18 +315,153 @@ async function sendAiTranslateRequest() {
return;
}
// Show the results to the user
console.log('AI response:', aiData.result);
console.log('Original dishes:', originalDishes);
// Create a modal to display the translation with original dishes
displayTranslation(aiData.result, originalDishes);
// Parse the AI response
let cleanedText = aiData.result
.trim()
.replace(/\n/g, '');
// Extract just the array part if needed
if (cleanedText.indexOf('[') >= 0) {
cleanedText = cleanedText.substring(cleanedText.indexOf('['));
if (!cleanedText.endsWith(']')) {
const lastBracket = cleanedText.lastIndexOf(']');
if (lastBracket > 0) {
cleanedText = cleanedText.substring(0, lastBracket + 1);
}
}
}
const parseJsObject = function(str) {
try {
return (new Function('return ' + str))();
} catch (e) {
console.error('Failed to parse:', e);
throw new Error('Invalid format in translation response');
}
};
// Parse the translation data
const translations = parseJsObject(cleanedText);
// Save translations to database using the new function
const saveResult = await saveTranslationsToDatabase(translations);
if (saveResult.success) {
alert(saveResult.message);
} else {
alert('Fehler beim Speichern: ' + saveResult.message);
}
} catch (error) {
console.error('Error sending AI request:', error);
alert('Fehler bei der KI-Anfrage: ' + error.message);
}
}
async function saveTranslationsToDatabase(translations, originalDishes = null) {
try {
// Get current week
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
let entries = [];
if (originalDishes === null) {
// Case 1: Called from sendAiTranslateRequest with full data
// Fetch the current week's menu data
const response = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
let translationIndex = 0;
// Map translations to database entries
data.forEach(entry => {
const englishEntry = {
date: entry.date,
meatMain: '',
meatSide: '',
veggiMain: '',
veggiSide: ''
};
// Add meat dish translation
if (entry.meat_main && translations[translationIndex]) {
englishEntry.meatMain = translations[translationIndex].main_course;
englishEntry.meatSide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add vegetarian dish translation
if (entry.veggi_main && translations[translationIndex]) {
englishEntry.veggiMain = translations[translationIndex].main_course;
englishEntry.veggiSide = translations[translationIndex].side_dish;
translationIndex++;
}
entries.push(englishEntry);
});
} else {
// Case 2: Called from displayTranslation with form values
// Fetch the original data to get the dates
const response = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
// Create entries with dates from original data
let translationIndex = 0;
data.forEach(entry => {
const englishEntry = {
date: entry.date,
meatMain: '',
meatSide: '',
veggiMain: '',
veggiSide: ''
};
// Add meat dish translation if original has meat dish
if (entry.meat_main && translations[translationIndex]) {
englishEntry.meatMain = translations[translationIndex].main_course;
englishEntry.meatSide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add vegetarian dish translation if original has veggie dish
if (entry.veggi_main && translations[translationIndex]) {
englishEntry.veggiMain = translations[translationIndex].main_course;
englishEntry.veggiSide = translations[translationIndex].side_dish;
translationIndex++;
}
entries.push(englishEntry);
});
}
// Save translations to database
const saveResponse = await fetch('/save-week-en', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ week, entries })
});
const saveResult = await saveResponse.json();
return { success: true, message: 'Englische Übersetzungen wurden gespeichert.' };
} catch (error) {
console.error('Error saving translations to database:', error);
return { success: false, message: 'Fehler beim Speichern der Übersetzungen: ' + error.message };
}
}
function sendTestTranslateRequest() {
const testResponse = `[{'main_course':'Turkey schnitzel with pepper sauce','side_dish':'served with spaghetti'},{'main_course':'Lentil curry with coconut milk','side_dish':'served with rice'},{'main_course':'White cabbage stew with potatoes and ground beef','side_dish':'served with a side salad and homemade bread'},{'main_course':'Sweet potato gnocchi with cheese sauce and arugula','side_dish':'served with a side salad'},{'main_course':'Ramsons bratwurst','side_dish':'accompanied by steakhouse fries'},{'main_course':'"Poached eggs" in mustard sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Chicken breast fillet in herb sauce','side_dish':'with fried potatoes and a side salad'},{'main_course':'Vegetable fritter with dip','side_dish':'served with couscous'},{'main_course':'Halibut fillet in lemon herb sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Vegetable rösti with dip','side_dish':'served with potato salad'}]`;
@@ -435,6 +560,7 @@ function displayTranslation(translationText, originalDishes = []) {
mainCourseInput.style.marginBottom = '10px';
mainCourseInput.style.width = '100%';
mainCourseInput.style.boxSizing = 'border-box';
mainCourseInput.placeholder = 'Hauptgericht';
const sideDishInput = document.createElement('input');
sideDishInput.type = 'text';
@@ -442,6 +568,7 @@ function displayTranslation(translationText, originalDishes = []) {
sideDishInput.style.padding = '8px';
sideDishInput.style.width = '100%';
sideDishInput.style.boxSizing = 'border-box';
sideDishInput.placeholder = 'Beilage';
dishContainer.appendChild(dishHeader);
dishContainer.appendChild(mainCourseInput);
@@ -496,26 +623,36 @@ function displayTranslation(translationText, originalDishes = []) {
closeBtn.style.cursor = 'pointer';
closeBtn.onclick = () => document.body.removeChild(modal);
const copyBtn = document.createElement('button');
copyBtn.textContent = 'Übersetzungen kopieren';
copyBtn.style.padding = '8px 16px';
copyBtn.style.backgroundColor = '#1e88e5';
copyBtn.style.color = 'white';
copyBtn.style.border = 'none';
copyBtn.style.borderRadius = '4px';
copyBtn.style.cursor = 'pointer';
copyBtn.onclick = () => {
// Get all translated texts
const saveBtn = document.createElement('button');
saveBtn.textContent = 'Übersetzungen speichern';
saveBtn.style.padding = '8px 16px';
saveBtn.style.backgroundColor = '#1e88e5';
saveBtn.style.color = 'white';
saveBtn.style.border = 'none';
saveBtn.style.borderRadius = '4px';
saveBtn.style.cursor = 'pointer';
saveBtn.onclick = async () => {
// Get all translated texts from form fields
const updatedTranslations = [];
const inputs = form.querySelectorAll('input');
let copyText = '';
for (let i = 0; i < inputs.length; i += 2) {
copyText += `${inputs[i].value}\n${inputs[i + 1].value}\n\n`;
const mainCourse = inputs[i].value;
const sideDish = inputs[i + 1].value;
updatedTranslations.push({
main_course: mainCourse,
side_dish: sideDish
});
}
// Save the translations to the database
const saveResult = await saveTranslationsToDatabase(updatedTranslations, originalDishes);
if (saveResult.success) {
alert('Übersetzungen wurden in der Datenbank gespeichert!');
} else {
alert('Fehler beim Speichern: ' + saveResult.message);
}
navigator.clipboard.writeText(copyText)
.then(() => alert('Übersetzungen wurden in die Zwischenablage kopiert!'))
.catch(err => console.error('Fehler beim Kopieren:', err));
};
const disclaimer = document.createElement('p');
@@ -524,7 +661,7 @@ function displayTranslation(translationText, originalDishes = []) {
disclaimer.style.fontWeight = 'bold';
buttonContainer.appendChild(generateBtn);
buttonContainer.appendChild(copyBtn);
buttonContainer.appendChild(saveBtn);
buttonContainer.appendChild(closeBtn);
buttonContainer.appendChild(disclaimer);
modalContent.appendChild(buttonContainer);
@@ -538,6 +675,82 @@ function displayTranslation(translationText, originalDishes = []) {
}
}
async function displayEnglishTranslations() {
try {
// Get current week to load data
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
// First, fetch the current week's German menu data for reference
const germanResponse = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const germanData = await germanResponse.json();
// Sort the data by day index to ensure correct order
germanData.sort((a, b) => a.day_index - b.day_index);
// Create array of original dishes for reference
const originalDishes = [];
germanData.forEach(entry => {
// Add meat dish
if (entry.meat_main) {
originalDishes.push({
main: entry.meat_main,
side: entry.meat_side || ''
});
}
// Add vegetarian dish
if (entry.veggi_main) {
originalDishes.push({
main: entry.veggi_main,
side: entry.veggi_side || ''
});
}
});
// Now fetch English translations
const englishResponse = await fetch(`/load-week-en?week=${encodeURIComponent(week)}`);
const englishData = await englishResponse.json();
// Create formatted data for display
const formattedTranslations = [];
// Always create translation objects for each German dish, even if no English data exists
germanData.forEach(entry => {
// Find matching English entry by date (may be undefined)
const englishEntry = englishData.find(en => en.date === entry.date);
// Add meat dish translation (empty strings if no match)
if (entry.meat_main) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.meat_main || '' : '',
side_dish: englishEntry ? englishEntry.meat_side || '' : ''
});
}
// Add vegetarian dish translation (empty strings if no match)
if (entry.veggi_main) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.veggi_main || '' : '',
side_dish: englishEntry ? englishEntry.veggi_side || '' : ''
});
}
});
// Format as JSON string for the existing displayTranslation function
// This will always contain objects for each dish, even with empty fields
const translationText = JSON.stringify(formattedTranslations);
// Use a custom title for the modal to indicate these are from the database
displayTranslation(translationText, originalDishes);
} catch (error) {
console.error('Error loading English translations:', error);
alert('Fehler beim Laden der englischen Übersetzungen: ' + error.message);
}
}
// Initialize the display when page loads
updateWeekDisplay();
updateDayDisplay();