mirror of
https://github.com/sstent/foodplanner.git
synced 2026-01-25 11:11:36 +00:00
fixing templates tab
This commit is contained in:
@@ -56,11 +56,13 @@ job "foodplanner" {
|
||||
# Mount the SQLite database file to persist data
|
||||
# Adjust the source path as needed for your environment
|
||||
volumes = [
|
||||
"/alloc/data/:/app/data/",
|
||||
"/mnt/Public/configs/FoodPlanner_backups:/app/backups/",
|
||||
]
|
||||
}
|
||||
|
||||
env {
|
||||
DATABASE_PATH = "/alloc/tmp"
|
||||
DATABASE_URL = "sqlite:////alloc/tmp/meal_planner.db"
|
||||
}
|
||||
resources {
|
||||
cpu = 500
|
||||
memory = 1024
|
||||
@@ -89,9 +91,6 @@ job "foodplanner" {
|
||||
"/alloc/tmp/meal_planner.db",
|
||||
"sftp://root:odroid@192.168.4.63/mnt/Shares/litestream/foodplanner.db"
|
||||
]
|
||||
volumes = [
|
||||
"/opt/nomad/data:/data"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
203
main.py
203
main.py
@@ -2106,7 +2106,8 @@ async def test_route():
|
||||
@app.get("/templates", response_class=HTMLResponse)
|
||||
async def templates_page(request: Request, db: Session = Depends(get_db)):
|
||||
templates_list = db.query(Template).all()
|
||||
return templates.TemplateResponse("templates.html", {"request": request, "templates": templates_list})
|
||||
meals = db.query(Meal).all()
|
||||
return templates.TemplateResponse("templates.html", {"request": request, "templates": templates_list, "meals": meals})
|
||||
|
||||
@app.post("/templates/upload")
|
||||
async def bulk_upload_templates(file: UploadFile = File(...), db: Session = Depends(get_db)):
|
||||
@@ -2180,4 +2181,204 @@ async def bulk_upload_templates(file: UploadFile = File(...), db: Session = Depe
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/templates/create")
|
||||
async def create_template(request: Request, db: Session = Depends(get_db)):
|
||||
"""Create a new template with meal assignments."""
|
||||
try:
|
||||
form_data = await request.form()
|
||||
template_name = form_data.get("name")
|
||||
meal_assignments_str = form_data.get("meal_assignments")
|
||||
|
||||
if not template_name:
|
||||
return {"status": "error", "message": "Template name is required"}
|
||||
|
||||
# Check if template already exists
|
||||
existing_template = db.query(Template).filter(Template.name == template_name).first()
|
||||
if existing_template:
|
||||
return {"status": "error", "message": f"Template with name '{template_name}' already exists"}
|
||||
|
||||
# Create new template
|
||||
template = Template(name=template_name)
|
||||
db.add(template)
|
||||
db.flush()
|
||||
|
||||
# Process meal assignments
|
||||
if meal_assignments_str:
|
||||
assignments = meal_assignments_str.split(',')
|
||||
for assignment in assignments:
|
||||
meal_time, meal_id_str = assignment.split(':')
|
||||
meal_id = int(meal_id_str)
|
||||
|
||||
meal = db.query(Meal).filter(Meal.id == meal_id).first()
|
||||
if meal:
|
||||
template_meal = TemplateMeal(
|
||||
template_id=template.id,
|
||||
meal_id=meal.id,
|
||||
meal_time=meal_time
|
||||
)
|
||||
db.add(template_meal)
|
||||
else:
|
||||
logging.warning(f"Meal with ID {meal_id} not found for template '{template_name}'")
|
||||
|
||||
db.commit()
|
||||
return {"status": "success", "message": "Template created successfully"}
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logging.error(f"Error creating template: {e}")
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.get("/templates/{template_id}")
|
||||
async def get_template_details(template_id: int, db: Session = Depends(get_db)):
|
||||
"""Get details for a single template"""
|
||||
try:
|
||||
template = db.query(Template).filter(Template.id == template_id).first()
|
||||
if not template:
|
||||
return {"status": "error", "message": "Template not found"}
|
||||
|
||||
template_meals_details = []
|
||||
for tm in template.template_meals:
|
||||
template_meals_details.append({
|
||||
"meal_id": tm.meal_id,
|
||||
"meal_time": tm.meal_time,
|
||||
"meal_name": tm.meal.name # Include meal name for display
|
||||
})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"template": {
|
||||
"id": template.id,
|
||||
"name": template.name,
|
||||
"template_meals": template_meals_details
|
||||
}
|
||||
}
|
||||
except Exception as e:
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.put("/templates/{template_id}")
|
||||
async def update_template(template_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
"""Update an existing template with new meal assignments."""
|
||||
try:
|
||||
form_data = await request.form()
|
||||
template_name = form_data.get("name")
|
||||
meal_assignments_str = form_data.get("meal_assignments")
|
||||
|
||||
template = db.query(Template).filter(Template.id == template_id).first()
|
||||
if not template:
|
||||
return {"status": "error", "message": "Template not found"}
|
||||
|
||||
if not template_name:
|
||||
return {"status": "error", "message": "Template name is required"}
|
||||
|
||||
# Check for duplicate name if changed
|
||||
if template_name != template.name:
|
||||
existing_template = db.query(Template).filter(Template.name == template_name).first()
|
||||
if existing_template:
|
||||
return {"status": "error", "message": f"Template with name '{template_name}' already exists"}
|
||||
|
||||
template.name = template_name
|
||||
|
||||
# Clear existing template meals
|
||||
db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).delete()
|
||||
db.flush()
|
||||
|
||||
# Process new meal assignments
|
||||
if meal_assignments_str:
|
||||
assignments = meal_assignments_str.split(',')
|
||||
for assignment in assignments:
|
||||
meal_time, meal_id_str = assignment.split(':')
|
||||
meal_id = int(meal_id_str)
|
||||
|
||||
meal = db.query(Meal).filter(Meal.id == meal_id).first()
|
||||
if meal:
|
||||
template_meal = TemplateMeal(
|
||||
template_id=template.id,
|
||||
meal_id=meal.id,
|
||||
meal_time=meal_time
|
||||
)
|
||||
db.add(template_meal)
|
||||
else:
|
||||
logging.warning(f"Meal with ID {meal_id} not found for template '{template_name}'")
|
||||
|
||||
db.commit()
|
||||
return {"status": "success", "message": "Template updated successfully"}
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logging.error(f"Error updating template: {e}")
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/templates/{template_id}/use")
|
||||
async def use_template(template_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
"""Apply a template to a specific date for a person."""
|
||||
try:
|
||||
form_data = await request.form()
|
||||
person = form_data.get("person")
|
||||
date_str = form_data.get("start_date") # Renamed from start_day to start_date
|
||||
|
||||
if not person or not date_str:
|
||||
return {"status": "error", "message": "Person and date are required"}
|
||||
|
||||
from datetime import datetime
|
||||
target_date = datetime.fromisoformat(date_str).date()
|
||||
|
||||
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()
|
||||
if not template_meals:
|
||||
return {"status": "error", "message": "Template has no meals"}
|
||||
|
||||
# Check for existing tracked day
|
||||
tracked_day = db.query(TrackedDay).filter(
|
||||
TrackedDay.person == person,
|
||||
TrackedDay.date == target_date
|
||||
).first()
|
||||
|
||||
if not tracked_day:
|
||||
tracked_day = TrackedDay(person=person, date=target_date, is_modified=True)
|
||||
db.add(tracked_day)
|
||||
db.flush()
|
||||
else:
|
||||
# Clear existing meals for the tracked day
|
||||
db.query(TrackedMeal).filter(TrackedMeal.tracked_day_id == tracked_day.id).delete()
|
||||
tracked_day.is_modified = True
|
||||
|
||||
for template_meal in template_meals:
|
||||
tracked_meal = TrackedMeal(
|
||||
tracked_day_id=tracked_day.id,
|
||||
meal_id=template_meal.meal_id,
|
||||
meal_time=template_meal.meal_time,
|
||||
quantity=1.0 # Default quantity when applying template
|
||||
)
|
||||
db.add(tracked_meal)
|
||||
|
||||
db.commit()
|
||||
return {"status": "success", "message": "Template applied successfully"}
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logging.error(f"Error applying template: {e}")
|
||||
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:
|
||||
template = db.query(Template).filter(Template.id == template_id).first()
|
||||
if not template:
|
||||
return {"status": "error", "message": "Template not found"}
|
||||
|
||||
# Delete associated template meals
|
||||
db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).delete()
|
||||
|
||||
db.delete(template)
|
||||
db.commit()
|
||||
|
||||
return {"status": "success"}
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logging.error(f"Error deleting template: {e}")
|
||||
return {"status": "error", "message": str(e)}
|
||||
@@ -1,20 +1,509 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Templates</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-4">
|
||||
<h1>Templates</h1>
|
||||
<p>This is the templates page.</p>
|
||||
<ul>
|
||||
{% for template in templates %}
|
||||
<li>{{ template.name }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% 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-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>
|
||||
</body>
|
||||
</html>
|
||||
</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>
|
||||
|
||||
<!-- Edit Template Modal -->
|
||||
<div class="modal fade" id="editTemplateModal" tabindex="-1" aria-labelledby="editTemplateModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="editTemplateModalLabel">Edit Template</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="editTemplateForm">
|
||||
<div class="modal-body">
|
||||
<input type="hidden" id="editTemplateId" name="id">
|
||||
<div class="mb-3">
|
||||
<label for="editTemplateName" class="form-label">Template Name</label>
|
||||
<input type="text" class="form-control" id="editTemplateName" 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="edit_breakfast" class="form-label">Breakfast</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_lunch" class="form-label">Lunch</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_dinner" class="form-label">Dinner</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_snack1" class="form-label">Snack 1</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_snack2" class="form-label">Snack 2</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_beverage1" class="form-label">Beverage 1</label>
|
||||
<select class="form-control meal-select" id="edit_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="edit_beverage2" class="form-label">Beverage 2</label>
|
||||
<select class="form-control meal-select" id="edit_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">Update 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();
|
||||
});
|
||||
|
||||
document.getElementById('editTemplateForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
updateTemplate();
|
||||
});
|
||||
});
|
||||
|
||||
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="editTemplate(${template.id})">
|
||||
<i class="bi bi-pencil"></i> Edit
|
||||
</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');
|
||||
});
|
||||
}
|
||||
|
||||
async function editTemplate(templateId) {
|
||||
try {
|
||||
const response = await fetch(`/templates/${templateId}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
const template = data.template;
|
||||
document.getElementById('editTemplateId').value = template.id;
|
||||
document.getElementById('editTemplateName').value = template.name;
|
||||
|
||||
// Clear previous selections
|
||||
const mealSelects = document.querySelectorAll('#editTemplateForm .meal-select');
|
||||
mealSelects.forEach(select => select.value = '');
|
||||
|
||||
// Set current meal assignments
|
||||
template.template_meals.forEach(tm => {
|
||||
const select = document.getElementById(`edit_${tm.meal_time.toLowerCase().replace(' ', '')}`);
|
||||
if (select) {
|
||||
select.value = tm.meal_id;
|
||||
}
|
||||
});
|
||||
|
||||
new bootstrap.Modal(document.getElementById('editTemplateModal')).show();
|
||||
} else {
|
||||
alert('Error loading template details: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
alert('Error loading template details.');
|
||||
}
|
||||
}
|
||||
|
||||
function updateTemplate() {
|
||||
const form = document.getElementById('editTemplateForm');
|
||||
const formData = new FormData(form);
|
||||
const templateId = formData.get('id');
|
||||
|
||||
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/${templateId}`, {
|
||||
method: 'PUT',
|
||||
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('editTemplateModal')).hide();
|
||||
loadTemplates();
|
||||
} else {
|
||||
alert('Error updating template: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error updating 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 %}
|
||||
Reference in New Issue
Block a user