starting templates 2

This commit is contained in:
2025-09-19 15:05:19 -07:00
parent a7aa0e302c
commit 7adf7e4d14
4 changed files with 648 additions and 68 deletions

Binary file not shown.

264
main.py
View File

@@ -68,12 +68,32 @@ class MealFood(Base):
class Plan(Base):
__tablename__ = "plans"
id = Column(Integer, primary_key=True, index=True)
person = Column(String, index=True) # Person A or Person B
date = Column(String, index=True) # Changed from Date to String to store "Day1", "Day2", etc.
date = Column(Date, index=True) # Store actual calendar dates
meal_id = Column(Integer, ForeignKey("meals.id"))
meal = relationship("Meal")
class Template(Base):
__tablename__ = "templates"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
# Relationship to template meals
template_meals = relationship("TemplateMeal", back_populates="template")
class TemplateMeal(Base):
__tablename__ = "template_meals"
id = Column(Integer, primary_key=True, index=True)
template_id = Column(Integer, ForeignKey("templates.id"))
meal_id = Column(Integer, ForeignKey("meals.id"))
meal_time = Column(String) # Breakfast, Lunch, Dinner, Snack 1, Snack 2, Beverage 1, Beverage 2
template = relationship("Template", back_populates="template_meals")
meal = relationship("Meal")
# Pydantic models
@@ -511,39 +531,67 @@ async def delete_meals(meal_ids: dict = Body(...), db: Session = Depends(get_db)
# Plan tab
@app.get("/plan", response_class=HTMLResponse)
async def plan_page(request: Request, person: str = "Person A", db: Session = Depends(get_db)):
# Create 14 days (Day1 through Day14)
days = [f"Day{i}" for i in range(1, 15)]
# Get plans for the person (using day names as dates)
async def plan_page(request: Request, person: str = "Person A", week_start_date: str = None, db: Session = Depends(get_db)):
from datetime import datetime, timedelta
# If no week_start_date provided, use current week starting from Monday
if not week_start_date:
today = datetime.now().date()
# Find Monday of current week
week_start_date = (today - timedelta(days=today.weekday())).isoformat()
else:
week_start_date = datetime.fromisoformat(week_start_date).date()
# Generate 7 days starting from Monday
days = []
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for i in range(7):
day_date = week_start_date + timedelta(days=i)
days.append({
'date': day_date,
'name': day_names[i],
'display': day_date.strftime('%b %d')
})
# Get plans for the person for this week
plans = {}
for day in days:
try:
day_plans = db.query(Plan).filter(Plan.person == person, Plan.date == day).all()
plans[day] = day_plans
day_plans = db.query(Plan).filter(Plan.person == person, Plan.date == day['date']).all()
plans[day['date'].isoformat()] = day_plans
except Exception as e:
print(f"Error loading plans for {day}: {e}")
plans[day] = []
print(f"Error loading plans for {day['date']}: {e}")
plans[day['date'].isoformat()] = []
# Calculate daily totals
daily_totals = {}
for day in days:
daily_totals[day] = calculate_day_nutrition(plans[day], db)
day_key = day['date'].isoformat()
daily_totals[day_key] = calculate_day_nutrition(plans[day_key], db)
meals = db.query(Meal).all()
# Calculate previous and next week dates
prev_week = (week_start_date - timedelta(days=7)).isoformat()
next_week = (week_start_date + timedelta(days=7)).isoformat()
return templates.TemplateResponse("plan.html", {
"request": request, "person": person, "days": days,
"plans": plans, "daily_totals": daily_totals, "meals": meals
"plans": plans, "daily_totals": daily_totals, "meals": meals,
"week_start_date": week_start_date.isoformat(),
"prev_week": prev_week, "next_week": next_week,
"week_range": f"{days[0]['display']} - {days[-1]['display']}, {week_start_date.year}"
})
@app.post("/plan/add")
async def add_to_plan(request: Request, person: str = Form(...),
plan_day: str = Form(...), meal_id: int = Form(...),
db: Session = Depends(get_db)):
async def add_to_plan(request: Request, person: str = Form(...),
plan_date: str = Form(...), meal_id: int = Form(...),
db: Session = Depends(get_db)):
try:
plan = Plan(person=person, date=plan_day, meal_id=meal_id)
from datetime import datetime
plan_date_obj = datetime.fromisoformat(plan_date).date()
plan = Plan(person=person, date=plan_date_obj, meal_id=meal_id)
db.add(plan)
db.commit()
return {"status": "success"}
@@ -551,11 +599,13 @@ async def add_to_plan(request: Request, person: str = Form(...),
db.rollback()
return {"status": "error", "message": str(e)}
@app.get("/plan/{person}/{day}")
async def get_day_plan(person: str, day: str, db: Session = Depends(get_db)):
"""Get all meals for a specific day"""
@app.get("/plan/{person}/{date}")
async def get_day_plan(person: str, date: str, db: Session = Depends(get_db)):
"""Get all meals for a specific date"""
try:
plans = db.query(Plan).filter(Plan.person == person, Plan.date == day).all()
from datetime import datetime
plan_date = datetime.fromisoformat(date).date()
plans = db.query(Plan).filter(Plan.person == person, Plan.date == plan_date).all()
result = []
for plan in plans:
result.append({
@@ -569,22 +619,25 @@ async def get_day_plan(person: str, day: str, db: Session = Depends(get_db)):
return {"status": "error", "message": str(e)}
@app.post("/plan/update_day")
async def update_day_plan(request: Request, person: str = Form(...),
day: str = Form(...), meal_ids: str = Form(...),
db: Session = Depends(get_db)):
"""Replace all meals for a specific day"""
async def update_day_plan(request: Request, person: str = Form(...),
date: str = Form(...), meal_ids: str = Form(...),
db: Session = Depends(get_db)):
"""Replace all meals for a specific date"""
try:
from datetime import datetime
plan_date = datetime.fromisoformat(date).date()
# Parse meal_ids (comma-separated string)
meal_id_list = [int(x.strip()) for x in meal_ids.split(',') if x.strip()]
# Delete existing plans for this day
db.query(Plan).filter(Plan.person == person, Plan.date == day).delete()
# Delete existing plans for this date
db.query(Plan).filter(Plan.person == person, Plan.date == plan_date).delete()
# Add new plans
for meal_id in meal_id_list:
plan = Plan(person=person, date=day, meal_id=meal_id)
plan = Plan(person=person, date=plan_date, meal_id=meal_id)
db.add(plan)
db.commit()
return {"status": "success"}
except Exception as e:
@@ -611,8 +664,143 @@ async def detailed(request: Request):
return templates.TemplateResponse("detailed.html", {"request": request, "title": "Detailed"})
@app.get("/templates", response_class=HTMLResponse)
async def templates_page(request: Request):
return templates.TemplateResponse("plans.html", {"request": request, "title": "Templates"})
async def templates_page(request: Request, db: Session = Depends(get_db)):
templates_list = db.query(Template).all()
meals = db.query(Meal).all()
# Convert templates to dictionaries for JSON serialization
templates_data = []
for template in templates_list:
template_meals = db.query(TemplateMeal).filter(TemplateMeal.template_id == template.id).all()
template_dict = {
"id": template.id,
"name": template.name,
"template_meals": []
}
for tm in template_meals:
template_dict["template_meals"].append({
"meal_time": tm.meal_time,
"meal_id": tm.meal_id,
"meal": {
"id": tm.meal.id,
"name": tm.meal.name,
"meal_type": tm.meal.meal_type
}
})
templates_data.append(template_dict)
return templates.TemplateResponse("plans.html", {
"request": request,
"title": "Templates",
"templates": templates_data,
"meals": meals
})
@app.post("/templates/create")
async def create_template(request: Request, name: str = Form(...),
meal_assignments: str = Form(...), db: Session = Depends(get_db)):
"""Create a new template with meal assignments"""
try:
# Create template
template = Template(name=name)
db.add(template)
db.flush() # Get template ID
# Parse meal assignments (format: "meal_time:meal_id,meal_time:meal_id,...")
if meal_assignments:
assignments = meal_assignments.split(',')
for assignment in assignments:
if ':' in assignment:
meal_time, meal_id = assignment.split(':', 1)
if meal_id.strip(): # Only add if meal_id is not empty
template_meal = TemplateMeal(
template_id=template.id,
meal_id=int(meal_id.strip()),
meal_time=meal_time.strip()
)
db.add(template_meal)
db.commit()
return {"status": "success", "template_id": template.id}
except Exception as e:
db.rollback()
return {"status": "error", "message": str(e)}
@app.get("/templates/{template_id}")
async def get_template(template_id: int, db: Session = Depends(get_db)):
"""Get template details with meal assignments"""
try:
template = db.query(Template).filter(Template.id == template_id).first()
if not template:
return {"status": "error", "message": "Template not found"}
template_meals = db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).all()
result = {
"id": template.id,
"name": template.name,
"meals": []
}
for tm in template_meals:
result["meals"].append({
"meal_time": tm.meal_time,
"meal_id": tm.meal_id,
"meal_name": tm.meal.name
})
return result
except Exception as e:
return {"status": "error", "message": str(e)}
@app.post("/templates/{template_id}/use")
async def use_template(template_id: int, person: str = Form(...),
start_date: str = Form(...), db: Session = Depends(get_db)):
"""Copy template meals to a person's plan starting from a specific date"""
try:
from datetime import datetime
start_date_obj = datetime.fromisoformat(start_date).date()
template_meals = db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).all()
print(f"DEBUG: Using template {template_id} for {person} on {start_date}")
print(f"DEBUG: Found {len(template_meals)} template meals")
# Check if any meals already exist for this date
existing_plans = db.query(Plan).filter(Plan.person == person, Plan.date == start_date_obj).count()
if existing_plans > 0:
return {"status": "confirm_overwrite", "message": f"There are already {existing_plans} meals planned for this date. Do you want to overwrite them?"}
# Copy all template meals to the specified date
for tm in template_meals:
print(f"DEBUG: Adding meal {tm.meal_id} ({tm.meal.name}) for {tm.meal_time}")
plan = Plan(person=person, date=start_date_obj, meal_id=tm.meal_id)
db.add(plan)
db.commit()
print(f"DEBUG: Successfully applied template")
return {"status": "success"}
except Exception as e:
print(f"DEBUG: Error applying template: {str(e)}")
db.rollback()
return {"status": "error", "message": str(e)}
@app.delete("/templates/{template_id}")
async def delete_template(template_id: int, db: Session = Depends(get_db)):
"""Delete a template and its meal assignments"""
try:
# Delete template meals first
db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).delete()
# Delete template
template = db.query(Template).filter(Template.id == template_id).first()
if template:
db.delete(template)
db.commit()
return {"status": "success"}
else:
return {"status": "error", "message": "Template not found"}
except Exception as e:
db.rollback()
return {"status": "error", "message": str(e)}
if __name__ == "__main__":
import uvicorn

View File

@@ -1,6 +1,24 @@
{% extends "base.html" %}
{% block content %}
<h3>2-Week Plan for {{ person }}</h3>
<div class="d-flex justify-content-between align-items-center mb-4">
<h3>Weekly Plan for {{ person }}</h3>
<div class="d-flex align-items-center">
<button class="btn btn-outline-secondary me-2" onclick="navigateWeek('{{ prev_week }}')">
<i class="bi bi-chevron-left"></i> Previous Week
</button>
<div class="input-group me-2" style="width: 200px;">
<input type="date" class="form-control" id="weekPicker" value="{{ week_start_date }}">
<button class="btn btn-outline-primary" onclick="jumpToWeek()">Go</button>
</div>
<button class="btn btn-outline-secondary" onclick="navigateWeek('{{ next_week }}')">
<i class="bi bi-chevron-right"></i> Next Week
</button>
</div>
</div>
<div class="alert alert-info mb-3">
<strong>Week: {{ week_range }}</strong>
</div>
<div class="table-responsive">
<table class="table table-bordered">
@@ -19,25 +37,28 @@
<tbody>
{% for day in days %}
<tr>
<td><strong>{{ day }}</strong></td>
<td>
{% for plan in plans[day] %}
<strong>{{ day.name }}</strong><br>
<small class="text-muted">{{ day.display }}</small>
</td>
<td>
{% for plan in plans[day.date.isoformat()] %}
<span class="badge bg-secondary me-1">{{ plan.meal.name }}</span>
{% endfor %}
{% if not plans[day] %}
{% if not plans[day.date.isoformat()] %}
<em class="text-muted">No meals</em>
{% endif %}
</td>
<td>{{ "%.0f"|format(daily_totals[day].calories or 0) }}</td>
<td>{{ "%.1f"|format(daily_totals[day].protein or 0) }}g<br><small class="text-muted">({{ daily_totals[day].protein_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day].carbs or 0) }}g<br><small class="text-muted">({{ daily_totals[day].carbs_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day].fat or 0) }}g<br><small class="text-muted">({{ daily_totals[day].fat_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day].net_carbs or 0) }}g</td>
<td>{{ "%.0f"|format(daily_totals[day.date.isoformat()].calories or 0) }}</td>
<td>{{ "%.1f"|format(daily_totals[day.date.isoformat()].protein or 0) }}g<br><small class="text-muted">({{ daily_totals[day.date.isoformat()].protein_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day.date.isoformat()].carbs or 0) }}g<br><small class="text-muted">({{ daily_totals[day.date.isoformat()].carbs_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day.date.isoformat()].fat or 0) }}g<br><small class="text-muted">({{ daily_totals[day.date.isoformat()].fat_pct or 0 }}%)</small></td>
<td>{{ "%.1f"|format(daily_totals[day.date.isoformat()].net_carbs or 0) }}g</td>
<td>
<button class="btn btn-sm btn-primary" onclick="editDay('{{ day }}', '{{ person }}')">
<button class="btn btn-sm btn-primary" onclick="editDay('{{ day.date.isoformat() }}', '{{ person }}')">
<i class="bi bi-pencil"></i> Edit
</button>
<button class="btn btn-sm btn-outline-success" onclick="quickAddMeal('{{ day }}')">
<button class="btn btn-sm btn-outline-success" onclick="quickAddMeal('{{ day.date.isoformat() }}')">
<i class="bi bi-plus"></i> Add
</button>
</td>
@@ -130,17 +151,36 @@
let currentEditingDay = null;
let currentEditingPerson = null;
// Week navigation function
function navigateWeek(weekStartDate) {
const url = new URL(window.location);
url.searchParams.set('week_start_date', weekStartDate);
window.location.href = url.toString();
}
// Jump to specific week
function jumpToWeek() {
const weekPicker = document.getElementById('weekPicker');
const selectedDate = weekPicker.value;
if (selectedDate) {
navigateWeek(selectedDate);
}
}
// Quick add meal function
function quickAddMeal(day) {
document.getElementById('quickAddDay').textContent = day;
document.getElementById('quickAddPlanDay').value = day;
function quickAddMeal(date) {
// Format date for display
const dateObj = new Date(date);
const options = { weekday: 'long', month: 'short', day: 'numeric' };
document.getElementById('quickAddDay').textContent = dateObj.toLocaleDateString('en-US', options);
document.getElementById('quickAddPlanDay').value = date;
new bootstrap.Modal(document.getElementById('quickAddMealModal')).show();
}
function submitQuickAddMeal() {
const form = document.getElementById('quickAddMealForm');
const formData = new FormData(form);
fetch('/plan/add', {
method: 'POST',
body: formData
@@ -160,26 +200,29 @@ function submitQuickAddMeal() {
}
// Edit day function
async function editDay(day, person) {
currentEditingDay = day;
async function editDay(date, person) {
currentEditingDay = date;
currentEditingPerson = person;
document.getElementById('editDayName').textContent = day;
// Format date for display
const dateObj = new Date(date);
const options = { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' };
document.getElementById('editDayName').textContent = dateObj.toLocaleDateString('en-US', options);
document.getElementById('editDayPerson').value = person;
document.getElementById('editDayValue').value = day;
// Load current meals for this day
await loadCurrentDayMeals(person, day);
document.getElementById('editDayValue').value = date;
// Load current meals for this date
await loadCurrentDayMeals(person, date);
new bootstrap.Modal(document.getElementById('editDayModal')).show();
}
// Load current meals for the day
async function loadCurrentDayMeals(person, day) {
// Load current meals for the date
async function loadCurrentDayMeals(person, date) {
try {
const response = await fetch(`/plan/${person}/${day}`);
const response = await fetch(`/plan/${person}/${date}`);
const meals = await response.json();
const container = document.getElementById('currentDayMeals');
if (meals.length === 0) {
container.innerHTML = '<em class="text-muted">No meals planned</em>';
@@ -193,7 +236,7 @@ async function loadCurrentDayMeals(person, day) {
</div>
`).join('');
}
// Update nutrition preview
updateDayNutritionPreview(meals);
} catch (error) {

View File

@@ -1,4 +1,353 @@
{% extends "base.html" %}
{% block content %}
<h1>Templates Page</h1>
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2><i class="bi bi-file-earmark-text"></i> Meal Templates</h2>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createTemplateModal">
<i class="bi bi-plus-circle"></i> Create Template
</button>
</div>
<div class="card">
<div class="card-header">
<h5 class="mb-0">Your Templates</h5>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped" id="templatesTable">
<thead>
<tr>
<th>Template Name</th>
<th>Meals Assigned</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Templates will be loaded here -->
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Create Template Modal -->
<div class="modal fade" id="createTemplateModal" tabindex="-1" aria-labelledby="createTemplateModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createTemplateModalLabel">Create New Template</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="createTemplateForm">
<div class="modal-body">
<div class="mb-3">
<label for="templateName" class="form-label">Template Name</label>
<input type="text" class="form-control" id="templateName" name="name" required>
</div>
<h6 class="mb-3">Assign Meals to Meal Times</h6>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="breakfast" class="form-label">Breakfast</label>
<select class="form-control meal-select" id="breakfast" name="breakfast">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="lunch" class="form-label">Lunch</label>
<select class="form-control meal-select" id="lunch" name="lunch">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="dinner" class="form-label">Dinner</label>
<select class="form-control meal-select" id="dinner" name="dinner">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="snack1" class="form-label">Snack 1</label>
<select class="form-control meal-select" id="snack1" name="snack1">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="snack2" class="form-label">Snack 2</label>
<select class="form-control meal-select" id="snack2" name="snack2">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="beverage1" class="form-label">Beverage 1</label>
<select class="form-control meal-select" id="beverage1" name="beverage1">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="beverage2" class="form-label">Beverage 2</label>
<select class="form-control meal-select" id="beverage2" name="beverage2">
<option value="">Select meal...</option>
{% for meal in meals %}
<option value="{{ meal.id }}">{{ meal.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 Template</button>
</div>
</form>
</div>
</div>
</div>
<!-- Use Template Modal -->
<div class="modal fade" id="useTemplateModal" tabindex="-1" aria-labelledby="useTemplateModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="useTemplateModalLabel">Use Template</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="useTemplateForm">
<div class="modal-body">
<p>Copy template meals to your plan for the selected date:</p>
<div class="mb-3">
<label for="startDate" class="form-label">Select Date</label>
<input type="date" class="form-control" id="startDate" name="start_date" required>
</div>
<div class="mb-3">
<label for="person" class="form-label">Person</label>
<select class="form-control" id="person" name="person" required>
<option value="Person A">Person A</option>
<option value="Person B">Person B</option>
</select>
</div>
<div id="overwriteWarning" class="alert alert-warning" style="display: none;">
<i class="bi bi-exclamation-triangle"></i>
<strong>Warning:</strong> There are already meals planned for this date.
Applying the template 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">Use Template</button>
</div>
</form>
</div>
</div>
</div>
<script>
let currentTemplateId = null;
document.addEventListener('DOMContentLoaded', function() {
loadTemplates();
// Handle template creation
document.getElementById('createTemplateForm').addEventListener('submit', function(e) {
e.preventDefault();
createTemplate();
});
// Handle template usage
document.getElementById('useTemplateForm').addEventListener('submit', function(e) {
e.preventDefault();
useTemplate();
});
});
function loadTemplates() {
fetch('/templates')
.then(response => response.text())
.then(html => {
// Extract templates data from the HTML response
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const templates = JSON.parse(doc.querySelector('script[data-templates]')?.textContent || '[]');
const tbody = document.querySelector('#templatesTable tbody');
tbody.innerHTML = '';
if (templates.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">No templates created yet. Click "Create Template" to get started.</td></tr>';
return;
}
templates.forEach(template => {
const row = document.createElement('tr');
row.innerHTML = `
<td><strong>${template.name}</strong></td>
<td>
${template.template_meals && template.template_meals.length > 0 ? template.template_meals.map(tm =>
`<span class="badge bg-secondary me-1">${tm.meal_time}: ${tm.meal.name}</span>`
).join('') : 'No meals assigned'}
</td>
<td>
<button class="btn btn-sm btn-outline-primary me-2" onclick="useTemplateModal(${template.id})">
<i class="bi bi-play-circle"></i> Use
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(${template.id})">
<i class="bi bi-trash"></i> Delete
</button>
</td>
`;
tbody.appendChild(row);
});
})
.catch(error => {
console.error('Error loading templates:', error);
});
}
function createTemplate() {
const form = document.getElementById('createTemplateForm');
const formData = new FormData(form);
// Build meal assignments string
const mealTimes = ['breakfast', 'lunch', 'dinner', 'snack1', 'snack2', 'beverage1', 'beverage2'];
const assignments = [];
mealTimes.forEach(mealTime => {
const mealId = formData.get(mealTime);
if (mealId) {
const displayName = mealTime.charAt(0).toUpperCase() + mealTime.slice(1).replace('1', ' 1').replace('2', ' 2');
assignments.push(`${displayName}:${mealId}`);
}
});
const data = {
name: formData.get('name'),
meal_assignments: assignments.join(',')
};
fetch('/templates/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('createTemplateModal')).hide();
form.reset();
loadTemplates();
} else {
alert('Error creating template: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error creating template');
});
}
function useTemplateModal(templateId) {
currentTemplateId = templateId;
new bootstrap.Modal(document.getElementById('useTemplateModal')).show();
}
function useTemplate() {
const form = document.getElementById('useTemplateForm');
const formData = new FormData(form);
const data = {
person: formData.get('person'),
start_day: formData.get('start_day')
};
fetch(`/templates/${currentTemplateId}/use`, {
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('useTemplateModal')).hide();
alert('Template applied to your plan successfully!');
} else {
alert('Error using template: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error using template');
});
}
function deleteTemplate(templateId) {
if (!confirm('Are you sure you want to delete this template?')) {
return;
}
fetch(`/templates/${templateId}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
loadTemplates();
} else {
alert('Error deleting template: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error deleting template');
});
}
</script>
<!-- Hidden script to pass templates data -->
<script type="application/json" data-templates>
{{ templates|tojson }}
</script>
{% endblock %}