sync - added week menus

This commit is contained in:
2025-09-22 09:45:28 -07:00
parent b9ac37183a
commit 45779f1739
7 changed files with 1385 additions and 8 deletions

View File

@@ -83,6 +83,16 @@
<li class="nav-item">
<a class="nav-link" href="/templates">Templates</a>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" onclick="location.href='/weeklymenu'">
<i class="bi bi-calendar-week"></i> Weekly Menu
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" onclick="location.href='/tracker'">
<i class="bi bi-calendar-check"></i> Tracker
</button>
</li>
</ul>
<div class="tab-content mt-3">
@@ -103,11 +113,17 @@
document.addEventListener('DOMContentLoaded', function() {
const currentPath = window.location.pathname;
const tabs = document.querySelectorAll('.nav-link');
tabs.forEach(tab => {
const href = tab.getAttribute('onclick');
if (href && href.includes(currentPath)) {
tab.classList.add('active');
} else if (currentPath === '/tracker' && href && href.includes('/tracker')) {
// Special case: ensure Tracker tab is active when on /tracker
tab.classList.add('active');
} else if (currentPath === '/weeklymenu' && href && href.includes('/weeklymenu')) {
// Special case: ensure Weekly Menu tab is active when on /weeklymenu
tab.classList.add('active');
} else {
tab.classList.remove('active');
}

View File

@@ -13,6 +13,7 @@
<tr>
<th>Select</th>
<th>Name</th>
<th>Brand</th>
<th>Serving</th>
<th>Cal</th>
<th>Protein</th>
@@ -29,6 +30,7 @@
<tr>
<td><input type="checkbox" name="selected_foods" value="{{ food.id }}"></td>
<td>{{ food.name }}</td>
<td>{{ food.brand or '' }}</td>
<td>{{ food.serving_size }} {{ food.serving_unit }}</td>
<td>{{ "%.2f"|format(food.calories) }}</td>
<td>{{ "%.2f"|format(food.protein) }}g</td>
@@ -38,7 +40,7 @@
<td>{{ "%.2f"|format(food.sodium) }}mg</td>
<td>{{ "%.2f"|format(food.calcium) }}mg</td>
<td>
<button type="button" class="btn btn-sm btn-outline-primary"
<button type="button" class="btn btn-sm btn-outline-primary"
onclick="editFood({{ food.id }})">
<i class="bi bi-pencil"></i> Edit
</button>
@@ -65,10 +67,14 @@
<div class="modal-body">
<form id="addFoodForm" action="/foods/add" method="post">
<div class="row">
<div class="col-12 mb-3">
<div class="col-8 mb-3">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="col-4 mb-3">
<label class="form-label">Brand</label>
<input type="text" class="form-control" name="brand" placeholder="Optional">
</div>
</div>
<div class="row">
<div class="col-6 mb-3">
@@ -142,10 +148,14 @@
<form id="editFoodForm" action="/foods/edit" method="post">
<input type="hidden" name="food_id" id="edit_food_id">
<div class="row">
<div class="col-12 mb-3">
<div class="col-8 mb-3">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="name" id="edit_name" required>
</div>
<div class="col-4 mb-3">
<label class="form-label">Brand</label>
<input type="text" class="form-control" name="brand" id="edit_brand" placeholder="Optional">
</div>
</div>
<div class="row">
<div class="col-6 mb-3">
@@ -277,6 +287,7 @@ document.addEventListener('DOMContentLoaded', function() {
{% for food in foods %}
{{ food.id }}: {
name: '{{ food.name | replace("'", "\\'") }}',
brand: '{{ food.brand | replace("'", "\\'") }}',
serving_size: '{{ food.serving_size | replace("'", "\\'") }}',
serving_unit: '{{ food.serving_unit | replace("'", "\\'") }}',
calories: {{ food.calories }},
@@ -295,9 +306,10 @@ document.addEventListener('DOMContentLoaded', function() {
window.editFood = function(foodId) {
const food = foodsData[foodId];
if (!food) return;
document.getElementById('edit_food_id').value = foodId;
document.getElementById('edit_name').value = food.name;
document.getElementById('edit_brand').value = food.brand || '';
document.getElementById('edit_serving_size').value = food.serving_size;
document.getElementById('edit_serving_unit').value = food.serving_unit;
document.getElementById('edit_calories').value = food.calories;
@@ -308,7 +320,7 @@ document.addEventListener('DOMContentLoaded', function() {
document.getElementById('edit_sugar').value = food.sugar;
document.getElementById('edit_sodium').value = food.sodium;
document.getElementById('edit_calcium').value = food.calcium;
new bootstrap.Modal(document.getElementById('editFoodModal')).show();
};
});

388
templates/tracker.html Normal file
View File

@@ -0,0 +1,388 @@
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-md-8">
<!-- Date Navigation -->
<div class="d-flex justify-content-between align-items-center mb-4">
<button class="btn btn-outline-secondary" onclick="navigateDate('{{ prev_date }}')">
<i class="bi bi-chevron-left"></i> Yesterday
</button>
<div class="text-center">
<h3>{{ current_date.strftime('%A, %B %d, %Y') }}</h3>
{% if is_modified %}
<span class="badge bg-warning text-dark">Custom</span>
{% else %}
<span class="badge bg-success">As Planned</span>
{% endif %}
</div>
<button class="btn btn-outline-secondary" onclick="navigateDate('{{ next_date }}')">
Tomorrow <i class="bi bi-chevron-right"></i>
</button>
</div>
<!-- Reset to Plan Button (only show if modified) -->
{% if is_modified %}
<div class="d-flex justify-content-center mb-4">
<button class="btn btn-outline-primary" onclick="resetToPlan()">
<i class="bi bi-arrow-counterclockwise"></i> Reset to Plan
</button>
</div>
{% endif %}
<!-- Template Actions -->
<div class="d-flex gap-2 mb-4">
<button class="btn btn-success" onclick="saveAsTemplate()">
<i class="bi bi-save"></i> Save as Template
</button>
<button class="btn btn-primary" onclick="applyTemplate()">
<i class="bi bi-upload"></i> Apply Template
</button>
</div>
<!-- Meal Times -->
{% set meal_times = ["Breakfast", "Lunch", "Dinner", "Snack 1", "Snack 2", "Beverage 1", "Beverage 2"] %}
{% for meal_time in meal_times %}
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0">{{ meal_time }}</h5>
</div>
<div class="card-body">
<div id="meals-{{ meal_time|lower|replace(' ', '-') }}">
{% set meals_for_time = [] %}
{% for tracked_meal in tracked_meals %}
{% if tracked_meal.meal_time == meal_time %}
{% set _ = meals_for_time.append(tracked_meal) %}
{% endif %}
{% endfor %}
{% if meals_for_time %}
{% for tracked_meal in meals_for_time %}
<div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
<div>
<strong>{{ tracked_meal.meal.name }}</strong>
{% if tracked_meal.quantity != 1.0 %}
<span class="text-muted">({{ "%.1f"|format(tracked_meal.quantity) }}x)</span>
{% endif %}
</div>
<button class="btn btn-sm btn-outline-danger" onclick="removeMeal({{ tracked_meal.id }})">
<i class="bi bi-trash"></i>
</button>
</div>
{% endfor %}
{% else %}
<p class="text-muted mb-0">No meals tracked</p>
{% endif %}
</div>
<!-- Add Meal Button -->
<button class="btn btn-sm btn-outline-success mt-2" onclick="addMealToTime('{{ meal_time }}')">
<i class="bi bi-plus"></i> Add Meal
</button>
</div>
</div>
{% endfor %}
</div>
<!-- Right Column - Nutrition Totals -->
<div class="col-md-4">
<div class="card sticky-top" style="top: 20px;">
<div class="card-header">
<h5 class="mb-0">Daily Totals</h5>
</div>
<div class="card-body">
<div class="row text-center">
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong class="h4 text-primary">{{ "%.0f"|format(day_totals.calories) }}</strong>
<div class="small text-muted">Calories</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong class="h4 text-success">{{ "%.1f"|format(day_totals.protein) }}g</strong>
<div class="small text-muted">Protein ({{ day_totals.protein_pct }}%)</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong class="h4 text-warning">{{ "%.1f"|format(day_totals.carbs) }}g</strong>
<div class="small text-muted">Carbs ({{ day_totals.carbs_pct }}%)</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong class="h4 text-danger">{{ "%.1f"|format(day_totals.fat) }}g</strong>
<div class="small text-muted">Fat ({{ day_totals.fat_pct }}%)</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong>{{ "%.1f"|format(day_totals.fiber) }}g</strong>
<div class="small text-muted">Fiber</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong>{{ "%.1f"|format(day_totals.net_carbs) }}g</strong>
<div class="small text-muted">Net Carbs</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong>{{ "%.0f"|format(day_totals.sugar) }}g</strong>
<div class="small text-muted">Sugar</div>
</div>
</div>
<div class="col-6 mb-3">
<div class="border rounded p-2">
<strong>{{ "%.0f"|format(day_totals.sodium) }}mg</strong>
<div class="small text-muted">Sodium</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Add Meal Modal -->
<div class="modal fade" id="addMealModal" tabindex="-1" aria-labelledby="addMealModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addMealModalLabel">Add Meal to <span id="mealTimeDisplay"></span></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="addMealForm">
<input type="hidden" id="addMealTime" name="meal_time">
<input type="hidden" name="person" value="{{ person }}">
<input type="hidden" name="date" value="{{ current_date.isoformat() }}">
<div class="mb-3">
<label class="form-label">Select Meal</label>
<select class="form-control" name="meal_id" required>
<option value="">Choose meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label class="form-label">Quantity (multiplier)</label>
<input type="number" step="0.1" class="form-control" name="quantity" value="1.0" min="0.1">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="submitAddMeal()">Add Meal</button>
</div>
</div>
</div>
</div>
<!-- Save Template Modal -->
<div class="modal fade" id="saveTemplateModal" tabindex="-1" aria-labelledby="saveTemplateModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="saveTemplateModalLabel">Save Day as Template</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="saveTemplateForm">
<input type="hidden" name="person" value="{{ person }}">
<input type="hidden" name="date" value="{{ current_date.isoformat() }}">
<div class="mb-3">
<label class="form-label">Template Name</label>
<input type="text" class="form-control" name="template_name" required placeholder="e.g., High Protein Day">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" onclick="submitSaveTemplate()">Save Template</button>
</div>
</div>
</div>
</div>
<!-- Apply Template Modal -->
<div class="modal fade" id="applyTemplateModal" tabindex="-1" aria-labelledby="applyTemplateModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="applyTemplateModalLabel">Apply Template</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="applyTemplateForm">
<input type="hidden" name="person" value="{{ person }}">
<input type="hidden" name="date" value="{{ current_date.isoformat() }}">
<div class="mb-3">
<label class="form-label">Select Template</label>
<select class="form-control" name="template_id" required>
<option value="">Choose template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
<div class="alert alert-warning">
<strong>Warning:</strong> This will replace all meals currently tracked for this day.
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="submitApplyTemplate()">Apply Template</button>
</div>
</div>
</div>
</div>
<script>
// Date navigation
function navigateDate(date) {
const url = new URL(window.location);
url.searchParams.set('date', date);
window.location.href = url.toString();
}
// Add meal to specific time
function addMealToTime(mealTime) {
document.getElementById('mealTimeDisplay').textContent = mealTime;
document.getElementById('addMealTime').value = mealTime;
new bootstrap.Modal(document.getElementById('addMealModal')).show();
}
// Submit add meal form
async function submitAddMeal() {
const form = document.getElementById('addMealForm');
const formData = new FormData(form);
try {
const response = await fetch('/tracker/add_meal', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('addMealModal')).hide();
location.reload();
} else {
alert('Error: ' + result.message);
}
} catch (error) {
alert('Error: ' + error.message);
}
}
// Remove meal
async function removeMeal(trackedMealId) {
if (confirm('Remove this meal from the tracker?')) {
try {
const response = await fetch(`/tracker/remove_meal/${trackedMealId}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.status === 'success') {
location.reload();
} else {
alert('Error: ' + result.message);
}
} catch (error) {
alert('Error: ' + error.message);
}
}
}
// Save as template
function saveAsTemplate() {
new bootstrap.Modal(document.getElementById('saveTemplateModal')).show();
}
// Submit save template
async function submitSaveTemplate() {
const form = document.getElementById('saveTemplateForm');
const formData = new FormData(form);
try {
const response = await fetch('/tracker/save_template', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('saveTemplateModal')).hide();
alert('Template saved successfully!');
} else {
alert('Error: ' + result.message);
}
} catch (error) {
alert('Error: ' + error.message);
}
}
// Apply template
function applyTemplate() {
new bootstrap.Modal(document.getElementById('applyTemplateModal')).show();
}
// Submit apply template
async function submitApplyTemplate() {
const form = document.getElementById('applyTemplateForm');
const formData = new FormData(form);
try {
const response = await fetch('/tracker/apply_template', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('applyTemplateModal')).hide();
location.reload();
} else {
alert('Error: ' + result.message);
}
} catch (error) {
alert('Error: ' + error.message);
}
}
// Reset to plan
async function resetToPlan() {
if (confirm('Reset this day back to the original plan? All custom changes will be lost.')) {
const formData = new FormData();
formData.append('person', '{{ person }}');
formData.append('date', '{{ current_date.isoformat() }}');
try {
const response = await fetch('/tracker/reset_to_plan', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.status === 'success') {
location.reload();
} else {
alert('Error: ' + result.message);
}
} catch (error) {
alert('Error: ' + error.message);
}
}
}
</script>
{% endblock %}

400
templates/weeklymenu.html Normal file
View File

@@ -0,0 +1,400 @@
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2><i class="bi bi-calendar-week"></i> Weekly Menus</h2>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createWeeklyMenuModal">
<i class="bi bi-plus-circle"></i> Create Weekly Menu
</button>
</div>
<div class="card">
<div class="card-header">
<h5 class="mb-0">Your Weekly Menus</h5>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped" id="weeklyMenusTable">
<thead>
<tr>
<th>Weekly Menu Name</th>
<th>Templates Assigned</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Weekly menus will be loaded here -->
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Create Weekly Menu Modal -->
<div class="modal fade" id="createWeeklyMenuModal" tabindex="-1" aria-labelledby="createWeeklyMenuModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createWeeklyMenuModalLabel">Create New Weekly Menu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="createWeeklyMenuForm">
<div class="modal-body">
<div class="mb-3">
<label for="weeklyMenuName" class="form-label">Weekly Menu Name</label>
<input type="text" class="form-control" id="weeklyMenuName" name="name" required>
</div>
<h6 class="mb-3">Assign Templates to Days</h6>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="monday" class="form-label">Monday</label>
<select class="form-control template-select" id="monday" name="monday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="tuesday" class="form-label">Tuesday</label>
<select class="form-control template-select" id="tuesday" name="tuesday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="wednesday" class="form-label">Wednesday</label>
<select class="form-control template-select" id="wednesday" name="wednesday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="thursday" class="form-label">Thursday</label>
<select class="form-control template-select" id="thursday" name="thursday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="friday" class="form-label">Friday</label>
<select class="form-control template-select" id="friday" name="friday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="saturday" class="form-label">Saturday</label>
<select class="form-control template-select" id="saturday" name="saturday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="sunday" class="form-label">Sunday</label>
<select class="form-control template-select" id="sunday" name="sunday">
<option value="">Select template...</option>
{% for template in templates %}
<option value="{{ template.id }}">{{ template.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Create Weekly Menu</button>
</div>
</form>
</div>
</div>
</div>
<!-- Apply Weekly Menu Modal -->
<div class="modal fade" id="applyWeeklyMenuModal" tabindex="-1" aria-labelledby="applyWeeklyMenuModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="applyWeeklyMenuModalLabel">Apply Weekly Menu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="applyWeeklyMenuForm">
<div class="modal-body">
<p>Apply this weekly menu to your plan starting from the selected week:</p>
<div class="mb-3">
<label for="weekStartDate" class="form-label">Select Week Start Date (Monday)</label>
<input type="date" class="form-control" id="weekStartDate" name="week_start_date" required>
</div>
<div class="mb-3">
<label for="applyPerson" class="form-label">Person</label>
<select class="form-control" id="applyPerson" name="person" required>
<option value="Person A">Person A</option>
<option value="Person B">Person B</option>
</select>
</div>
<div id="applyOverwriteWarning" class="alert alert-warning" style="display: none;">
<i class="bi bi-exclamation-triangle"></i>
<strong>Warning:</strong> There are already meals planned for this week.
Applying the weekly menu will overwrite them.
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Apply Weekly Menu</button>
</div>
</form>
</div>
</div>
</div>
<script>
let currentWeeklyMenuId = null;
document.addEventListener('DOMContentLoaded', function() {
loadWeeklyMenus();
// Handle weekly menu creation
document.getElementById('createWeeklyMenuForm').addEventListener('submit', function(e) {
e.preventDefault();
createWeeklyMenu();
});
// Handle weekly menu application
document.getElementById('applyWeeklyMenuForm').addEventListener('submit', function(e) {
e.preventDefault();
applyWeeklyMenu();
});
});
function loadWeeklyMenus() {
fetch('/weeklymenu')
.then(response => response.text())
.then(html => {
// Extract weekly menus data from the HTML response
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const weeklyMenus = JSON.parse(doc.querySelector('script[data-weekly-menus]')?.textContent || '[]');
const tbody = document.querySelector('#weeklyMenusTable tbody');
tbody.innerHTML = '';
if (weeklyMenus.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">No weekly menus created yet. Click "Create Weekly Menu" to get started.</td></tr>';
return;
}
const dayNames = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
weeklyMenus.forEach(weeklyMenu => {
const row = document.createElement('tr');
row.innerHTML = `
<td><strong>${weeklyMenu.name}</strong></td>
<td>
${weeklyMenu.weekly_menu_days && weeklyMenu.weekly_menu_days.length > 0 ?
weeklyMenu.weekly_menu_days.map(wmd =>
`<span class="badge bg-secondary me-1">${dayNames[wmd.day_of_week]}: ${wmd.template.name}</span>`
).join('') : 'No templates assigned'}
</td>
<td>
<button class="btn btn-sm btn-outline-primary me-2" onclick="applyWeeklyMenuModal(${weeklyMenu.id})">
<i class="bi bi-play-circle"></i> Apply
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteWeeklyMenu(${weeklyMenu.id})">
<i class="bi bi-trash"></i> Delete
</button>
</td>
`;
tbody.appendChild(row);
});
})
.catch(error => {
console.error('Error loading weekly menus:', error);
});
}
function createWeeklyMenu() {
const form = document.getElementById('createWeeklyMenuForm');
const formData = new FormData(form);
// Build template assignments string
const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
const assignments = [];
days.forEach((day, index) => {
const templateId = formData.get(day);
if (templateId) {
assignments.push(`${index}:${templateId}`);
}
});
const data = {
name: formData.get('name'),
template_assignments: assignments.join(',')
};
fetch('/weeklymenu/create', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('createWeeklyMenuModal')).hide();
form.reset();
loadWeeklyMenus();
} else {
alert('Error creating weekly menu: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error creating weekly menu');
});
}
function applyWeeklyMenuModal(weeklyMenuId) {
currentWeeklyMenuId = weeklyMenuId;
// Set default date to current week's Monday
const today = new Date();
const monday = new Date(today);
monday.setDate(today.getDate() - today.getDay() + 1); // Get Monday of current week
document.getElementById('weekStartDate').value = monday.toISOString().split('T')[0];
document.getElementById('applyOverwriteWarning').style.display = 'none';
new bootstrap.Modal(document.getElementById('applyWeeklyMenuModal')).show();
}
function applyWeeklyMenu() {
const form = document.getElementById('applyWeeklyMenuForm');
const formData = new FormData(form);
const data = {
person: formData.get('person'),
week_start_date: formData.get('week_start_date')
};
fetch(`/weeklymenu/${currentWeeklyMenuId}/apply`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
})
.then(response => response.json())
.then(data => {
if (data.status === 'confirm_overwrite') {
// Show overwrite warning
document.getElementById('applyOverwriteWarning').style.display = 'block';
// Change button text to confirm overwrite
const submitBtn = document.querySelector('#applyWeeklyMenuForm button[type="submit"]');
submitBtn.textContent = 'Overwrite Existing Meals';
submitBtn.onclick = () => confirmApplyOverwrite(data);
} else if (data.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('applyWeeklyMenuModal')).hide();
alert('Weekly menu applied to your plan successfully!');
} else {
alert('Error applying weekly menu: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error applying weekly menu');
});
}
function confirmApplyOverwrite(overwriteData) {
const form = document.getElementById('applyWeeklyMenuForm');
const formData = new FormData(form);
const data = {
person: formData.get('person'),
week_start_date: formData.get('week_start_date'),
confirm_overwrite: 'true'
};
fetch(`/weeklymenu/${currentWeeklyMenuId}/apply`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
bootstrap.Modal.getInstance(document.getElementById('applyWeeklyMenuModal')).hide();
alert('Weekly menu applied to your plan successfully!');
} else {
alert('Error applying weekly menu: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error applying weekly menu');
});
}
function deleteWeeklyMenu(weeklyMenuId) {
if (!confirm('Are you sure you want to delete this weekly menu?')) {
return;
}
fetch(`/weeklymenu/${weeklyMenuId}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
loadWeeklyMenus();
} else {
alert('Error deleting weekly menu: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error deleting weekly menu');
});
}
</script>
<!-- Hidden script to pass weekly menus data -->
<script type="application/json" data-weekly-menus>
{{ weekly_menus|tojson }}
</script>
{% endblock %}