mirror of
https://github.com/sstent/foodplanner.git
synced 2026-03-14 09:15:24 +00:00
added container and nomad
This commit is contained in:
47
Dockerfile
Normal file
47
Dockerfile
Normal file
@@ -0,0 +1,47 @@
|
||||
# Multi-stage Dockerfile for FoodPlanner
|
||||
|
||||
# Build stage: Install dependencies
|
||||
FROM python:3.11-slim AS builder
|
||||
|
||||
# Install system dependencies for building Python packages
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
gcc \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy requirements file
|
||||
COPY requirements.txt .
|
||||
|
||||
# Install Python dependencies into a virtual environment
|
||||
RUN python -m venv venv && \
|
||||
. venv/bin/activate && \
|
||||
pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Final stage: Copy application code and installed dependencies
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Install runtime dependencies (if any needed beyond Python base)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy the virtual environment from the builder stage
|
||||
COPY --from=builder /app/venv /app/venv
|
||||
|
||||
# Activate the virtual environment
|
||||
ENV PATH="/app/venv/bin:$PATH"
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Expose port (as defined in main.py)
|
||||
EXPOSE 8999
|
||||
|
||||
# Run the application with uvicorn
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0", "--port", "8999"]
|
||||
97
foodplanner.nomad.hcl
Normal file
97
foodplanner.nomad.hcl
Normal file
@@ -0,0 +1,97 @@
|
||||
job "foodplanner" {
|
||||
datacenters = ["dc1"]
|
||||
|
||||
type = "service"
|
||||
|
||||
group "app" {
|
||||
count = 1
|
||||
|
||||
network {
|
||||
port "http" {
|
||||
to = 8999
|
||||
}
|
||||
}
|
||||
|
||||
service {
|
||||
name = "foodplanner"
|
||||
port = "http"
|
||||
|
||||
check {
|
||||
type = "http"
|
||||
path = "/"
|
||||
interval = "10s"
|
||||
timeout = "2s"
|
||||
}
|
||||
}
|
||||
|
||||
# Prestart restore task
|
||||
task "restore" {
|
||||
driver = "docker"
|
||||
lifecycle {
|
||||
hook = "prestart"
|
||||
sidecar = false
|
||||
}
|
||||
config {
|
||||
image = "litestream/litestream:latest"
|
||||
args = [
|
||||
"restore",
|
||||
"-if-replica-exists",
|
||||
"-if-db-not-exists",
|
||||
"-o", "/alloc/tmp/meal_planner.db",
|
||||
"sftp://root:odroid@192.168.4.63/mnt/Shares/litestream/foodplanner.db"
|
||||
]
|
||||
volumes = [
|
||||
"/opt/nomad/data:/data"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
task "app" {
|
||||
driver = "docker"
|
||||
|
||||
config {
|
||||
image = "ghcr.io/sstent/foodplanner:main"
|
||||
ports = ["http"]
|
||||
|
||||
# Mount the SQLite database file to persist data
|
||||
# Adjust the source path as needed for your environment
|
||||
volumes = [
|
||||
"/alloc/tmp/meal_planner.db:/app/meal_planner.db"
|
||||
]
|
||||
}
|
||||
|
||||
resources {
|
||||
cpu = 500
|
||||
memory = 1024
|
||||
}
|
||||
|
||||
# Restart policy
|
||||
restart {
|
||||
attempts = 3
|
||||
interval = "10m"
|
||||
delay = "15s"
|
||||
mode = "fail"
|
||||
}
|
||||
}
|
||||
|
||||
# Litestream sidecar for continuous replication
|
||||
task "litestream" {
|
||||
driver = "docker"
|
||||
lifecycle {
|
||||
hook = "poststart" # runs after main task starts
|
||||
sidecar = true
|
||||
}
|
||||
config {
|
||||
image = "litestream/litestream:latest"
|
||||
args = [
|
||||
"replicate",
|
||||
"/alloc/tmp/meal_planner.db",
|
||||
"sftp://root:odroid@192.168.4.63/mnt/Shares/litestream/foodplanner.db"
|
||||
]
|
||||
volumes = [
|
||||
"/opt/nomad/data:/data"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
213
main.py
213
main.py
@@ -1339,6 +1339,147 @@ async def delete_template(template_id: int, db: Session = Depends(get_db)):
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/templates/edit")
|
||||
async def edit_template(template_id: int = Form(...), name: str = Form(...),
|
||||
meal_assignments: str = Form(...), db: Session = Depends(get_db)):
|
||||
"""Edit an existing template with new name and meal assignments"""
|
||||
try:
|
||||
# Get existing template
|
||||
template = db.query(Template).filter(Template.id == template_id).first()
|
||||
if not template:
|
||||
return {"status": "error", "message": "Template not found"}
|
||||
|
||||
# Update template name
|
||||
template.name = name
|
||||
|
||||
# Delete existing template meals
|
||||
db.query(TemplateMeal).filter(TemplateMeal.template_id == template_id).delete()
|
||||
|
||||
# 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.post("/templates/create_from_template")
|
||||
async def create_template_from_existing(source_template_id: int = Form(...),
|
||||
new_name: str = Form(...), db: Session = Depends(get_db)):
|
||||
"""Create a new template by copying an existing template's meal assignments"""
|
||||
try:
|
||||
# Get source template
|
||||
source_template = db.query(Template).filter(Template.id == source_template_id).first()
|
||||
if not source_template:
|
||||
return {"status": "error", "message": "Source template not found"}
|
||||
|
||||
# Create new template
|
||||
new_template = Template(name=new_name)
|
||||
db.add(new_template)
|
||||
db.flush() # Get new template ID
|
||||
|
||||
# Copy template meals from source
|
||||
source_meals = db.query(TemplateMeal).filter(TemplateMeal.template_id == source_template_id).all()
|
||||
for source_meal in source_meals:
|
||||
new_template_meal = TemplateMeal(
|
||||
template_id=new_template.id,
|
||||
meal_id=source_meal.meal_id,
|
||||
meal_time=source_meal.meal_time
|
||||
)
|
||||
db.add(new_template_meal)
|
||||
|
||||
db.commit()
|
||||
return {"status": "success", "template_id": new_template.id}
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/templates/upload")
|
||||
async def bulk_upload_templates(file: UploadFile = File(...), db: Session = Depends(get_db)):
|
||||
"""Handle bulk template upload from CSV"""
|
||||
try:
|
||||
contents = await file.read()
|
||||
decoded = contents.decode('utf-8').splitlines()
|
||||
reader = csv.DictReader(decoded)
|
||||
|
||||
stats = {'created': 0, 'updated': 0, 'errors': []}
|
||||
|
||||
for row_num, row in enumerate(reader, 2): # Row numbers start at 2 (1-based + header)
|
||||
try:
|
||||
user = row.get('User', '').strip()
|
||||
template_id = row.get('ID', '').strip()
|
||||
|
||||
if not user or not template_id:
|
||||
stats['errors'].append(f"Row {row_num}: Missing User or ID")
|
||||
continue
|
||||
|
||||
# Create template name in format <User>-<ID>
|
||||
template_name = f"{user}-{template_id}"
|
||||
|
||||
# Check if template already exists
|
||||
existing_template = db.query(Template).filter(Template.name == template_name).first()
|
||||
if existing_template:
|
||||
# Update existing template - remove existing meals
|
||||
db.query(TemplateMeal).filter(TemplateMeal.template_id == existing_template.id).delete()
|
||||
template = existing_template
|
||||
stats['updated'] += 1
|
||||
else:
|
||||
# Create new template
|
||||
template = Template(name=template_name)
|
||||
db.add(template)
|
||||
stats['created'] += 1
|
||||
|
||||
db.flush() # Get template ID
|
||||
|
||||
# Meal time mappings from CSV columns
|
||||
meal_columns = {
|
||||
'Beverage 1': 'Beverage 1',
|
||||
'Breakfast': 'Breakfast',
|
||||
'Lunch': 'Lunch',
|
||||
'Dinner': 'Dinner',
|
||||
'Snack 1': 'Snack 1',
|
||||
'Snack 2': 'Snack 2'
|
||||
}
|
||||
|
||||
# Process each meal column
|
||||
for csv_column, meal_time in meal_columns.items():
|
||||
meal_name = row.get(csv_column, '').strip()
|
||||
if meal_name:
|
||||
# Find meal by name
|
||||
meal = db.query(Meal).filter(Meal.name.ilike(meal_name)).first()
|
||||
if meal:
|
||||
# Create template meal
|
||||
template_meal = TemplateMeal(
|
||||
template_id=template.id,
|
||||
meal_id=meal.id,
|
||||
meal_time=meal_time
|
||||
)
|
||||
db.add(template_meal)
|
||||
else:
|
||||
stats['errors'].append(f"Row {row_num}: Meal '{meal_name}' not found for {meal_time}")
|
||||
|
||||
except (KeyError, ValueError) as e:
|
||||
stats['errors'].append(f"Row {row_num}: {str(e)}")
|
||||
|
||||
db.commit()
|
||||
return stats
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
# Weekly Menu tab
|
||||
@app.get("/weeklymenu", response_class=HTMLResponse)
|
||||
async def weeklymenu_page(request: Request, db: Session = Depends(get_db)):
|
||||
@@ -1371,9 +1512,33 @@ async def weeklymenu_page(request: Request, db: Session = Depends(get_db)):
|
||||
"templates": templates_list
|
||||
})
|
||||
|
||||
@app.get("/weeklymenu/{weekly_menu_id}")
|
||||
async def get_weekly_menu(weekly_menu_id: int, db: Session = Depends(get_db)):
|
||||
"""Get details for a specific weekly menu for editing"""
|
||||
try:
|
||||
weekly_menu = db.query(WeeklyMenu).filter(WeeklyMenu.id == weekly_menu_id).first()
|
||||
if not weekly_menu:
|
||||
return {"status": "error", "message": "Weekly menu not found"}
|
||||
|
||||
weekly_menu_days = db.query(WeeklyMenuDay).filter(WeeklyMenuDay.weekly_menu_id == weekly_menu_id).all()
|
||||
|
||||
# Create a dictionary mapping day_of_week to template_id
|
||||
template_assignments = {}
|
||||
for wmd in weekly_menu_days:
|
||||
template_assignments[wmd.day_of_week] = wmd.template_id
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"id": weekly_menu.id,
|
||||
"name": weekly_menu.name,
|
||||
"template_assignments": template_assignments
|
||||
}
|
||||
except Exception as e:
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/weeklymenu/create")
|
||||
async def create_weekly_menu(request: Request, name: str = Form(...),
|
||||
template_assignments: str = Form(...), db: Session = Depends(get_db)):
|
||||
template_assignments: str = Form(...), db: Session = Depends(get_db)):
|
||||
"""Create a new weekly menu with template assignments"""
|
||||
try:
|
||||
# Create weekly menu
|
||||
@@ -1401,6 +1566,52 @@ async def create_weekly_menu(request: Request, name: str = Form(...),
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/weeklymenu/edit")
|
||||
async def edit_weekly_menu(request: Request, weekly_menu_id: int = Form(...),
|
||||
name: str = Form(...), monday: str = Form(""),
|
||||
tuesday: str = Form(""), wednesday: str = Form(""),
|
||||
thursday: str = Form(""), friday: str = Form(""),
|
||||
saturday: str = Form(""), sunday: str = Form(""),
|
||||
db: Session = Depends(get_db)):
|
||||
"""Edit an existing weekly menu with new name and template assignments"""
|
||||
try:
|
||||
# Get existing weekly menu
|
||||
weekly_menu = db.query(WeeklyMenu).filter(WeeklyMenu.id == weekly_menu_id).first()
|
||||
if not weekly_menu:
|
||||
return {"status": "error", "message": "Weekly menu not found"}
|
||||
|
||||
# Update name
|
||||
weekly_menu.name = name
|
||||
|
||||
# Delete existing weekly menu days
|
||||
db.query(WeeklyMenuDay).filter(WeeklyMenuDay.weekly_menu_id == weekly_menu_id).delete()
|
||||
|
||||
# Create new template assignments
|
||||
day_assignments = {
|
||||
0: monday, # Monday
|
||||
1: tuesday, # Tuesday
|
||||
2: wednesday, # Wednesday
|
||||
3: thursday, # Thursday
|
||||
4: friday, # Friday
|
||||
5: saturday, # Saturday
|
||||
6: sunday # Sunday
|
||||
}
|
||||
|
||||
for day_of_week, template_id in day_assignments.items():
|
||||
if template_id and template_id.strip():
|
||||
weekly_menu_day = WeeklyMenuDay(
|
||||
weekly_menu_id=weekly_menu.id,
|
||||
day_of_week=day_of_week,
|
||||
template_id=int(template_id.strip())
|
||||
)
|
||||
db.add(weekly_menu_day)
|
||||
|
||||
db.commit()
|
||||
return {"status": "success", "weekly_menu_id": weekly_menu.id}
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
@app.post("/weeklymenu/{weekly_menu_id}/apply")
|
||||
async def apply_weekly_menu(weekly_menu_id: int, person: str = Form(...),
|
||||
week_start_date: str = Form(...), db: Session = Depends(get_db)):
|
||||
|
||||
@@ -38,6 +38,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mt-4">
|
||||
<div class="col-md-6">
|
||||
<h3>Template Import</h3>
|
||||
<form action="/templates/upload" method="post" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">CSV File</label>
|
||||
<input type="file" class="form-control" name="file" accept=".csv" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-secondary mb-4">Upload Templates CSV</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4" id="upload-results" style="display: none;">
|
||||
<div class="alert alert-success">
|
||||
<strong>Upload Results:</strong>
|
||||
|
||||
@@ -181,6 +181,144 @@
|
||||
</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">
|
||||
<input type="hidden" id="editTemplateId" name="template_id">
|
||||
<div class="modal-body">
|
||||
<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="editBreakfast" class="form-label">Breakfast</label>
|
||||
<select class="form-control meal-select" id="editBreakfast" 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="editLunch" class="form-label">Lunch</label>
|
||||
<select class="form-control meal-select" id="editLunch" 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="editDinner" class="form-label">Dinner</label>
|
||||
<select class="form-control meal-select" id="editDinner" 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="editSnack1" class="form-label">Snack 1</label>
|
||||
<select class="form-control meal-select" id="editSnack1" 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="editSnack2" class="form-label">Snack 2</label>
|
||||
<select class="form-control meal-select" id="editSnack2" 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="editBeverage1" class="form-label">Beverage 1</label>
|
||||
<select class="form-control meal-select" id="editBeverage1" 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="editBeverage2" class="form-label">Beverage 2</label>
|
||||
<select class="form-control meal-select" id="editBeverage2" 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>
|
||||
|
||||
<!-- Create from Template Modal -->
|
||||
<div class="modal fade" id="createFromTemplateModal" tabindex="-1" aria-labelledby="createFromTemplateModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="createFromTemplateModalLabel">Create New Template from Existing</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="createFromTemplateForm">
|
||||
<input type="hidden" id="sourceTemplateId" name="source_template_id">
|
||||
<div class="modal-body">
|
||||
<p>This will create a new template with the same meal assignments as the selected template.</p>
|
||||
<div class="mb-3">
|
||||
<label for="newTemplateName" class="form-label">New Template Name</label>
|
||||
<input type="text" class="form-control" id="newTemplateName" name="new_name" required placeholder="Enter name for the new template">
|
||||
</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>
|
||||
|
||||
<script>
|
||||
let currentTemplateId = null;
|
||||
|
||||
@@ -198,6 +336,18 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
e.preventDefault();
|
||||
useTemplate();
|
||||
});
|
||||
|
||||
// Handle template editing
|
||||
document.getElementById('editTemplateForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
editTemplate();
|
||||
});
|
||||
|
||||
// Handle create from template
|
||||
document.getElementById('createFromTemplateForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
createFromTemplate();
|
||||
});
|
||||
});
|
||||
|
||||
function loadTemplates() {
|
||||
@@ -230,6 +380,12 @@ function loadTemplates() {
|
||||
<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-secondary me-2" onclick="editTemplateModal(${template.id})">
|
||||
<i class="bi bi-pencil"></i> Edit
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-info me-2" onclick="createFromTemplateModal(${template.id})">
|
||||
<i class="bi bi-copy"></i> Create from This
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(${template.id})">
|
||||
<i class="bi bi-trash"></i> Delete
|
||||
</button>
|
||||
@@ -366,6 +522,141 @@ function confirmOverwrite(overwriteData) {
|
||||
});
|
||||
}
|
||||
|
||||
function editTemplateModal(templateId) {
|
||||
console.log('editTemplateModal called with templateId:', templateId);
|
||||
// Fetch template data
|
||||
fetch(`/templates/${templateId}`)
|
||||
.then(response => {
|
||||
console.log('Response status:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Response data:', data);
|
||||
// Check if this is an error response (has status field)
|
||||
if (data.status === 'error') {
|
||||
alert('Error loading template: ' + (data.message || 'Unknown error'));
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a successful response with template data
|
||||
if (data.id && data.name) {
|
||||
// Populate form
|
||||
document.getElementById('editTemplateId').value = templateId;
|
||||
document.getElementById('editTemplateName').value = data.name;
|
||||
|
||||
// Clear all selects first
|
||||
const mealTimes = ['Breakfast', 'Lunch', 'Dinner', 'Snack 1', 'Snack 2', 'Beverage 1', 'Beverage 2'];
|
||||
const selectIds = ['editBreakfast', 'editLunch', 'editDinner', 'editSnack1', 'editSnack2', 'editBeverage1', 'editBeverage2'];
|
||||
|
||||
selectIds.forEach(id => {
|
||||
document.getElementById(id).value = '';
|
||||
});
|
||||
|
||||
// Populate meal assignments
|
||||
if (data.meals && Array.isArray(data.meals)) {
|
||||
data.meals.forEach(meal => {
|
||||
const selectId = 'edit' + meal.meal_time.replace(' ', '');
|
||||
const select = document.getElementById(selectId);
|
||||
if (select) {
|
||||
select.value = meal.meal_id;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Show modal
|
||||
new bootstrap.Modal(document.getElementById('editTemplateModal')).show();
|
||||
} else {
|
||||
alert('Error: Invalid response format from server');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error loading template');
|
||||
});
|
||||
}
|
||||
|
||||
function createFromTemplateModal(templateId) {
|
||||
document.getElementById('sourceTemplateId').value = templateId;
|
||||
document.getElementById('newTemplateName').value = '';
|
||||
new bootstrap.Modal(document.getElementById('createFromTemplateModal')).show();
|
||||
}
|
||||
|
||||
function editTemplate() {
|
||||
const form = document.getElementById('editTemplateForm');
|
||||
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 = {
|
||||
template_id: formData.get('template_id'),
|
||||
name: formData.get('name'),
|
||||
meal_assignments: assignments.join(',')
|
||||
};
|
||||
|
||||
fetch('/templates/edit', {
|
||||
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('editTemplateModal')).hide();
|
||||
loadTemplates();
|
||||
} else {
|
||||
alert('Error updating template: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error updating template');
|
||||
});
|
||||
}
|
||||
|
||||
function createFromTemplate() {
|
||||
const form = document.getElementById('createFromTemplateForm');
|
||||
const formData = new FormData(form);
|
||||
|
||||
const data = {
|
||||
source_template_id: formData.get('source_template_id'),
|
||||
new_name: formData.get('new_name')
|
||||
};
|
||||
|
||||
fetch('/templates/create_from_template', {
|
||||
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('createFromTemplateModal')).hide();
|
||||
form.reset();
|
||||
loadTemplates();
|
||||
} else {
|
||||
alert('Error creating template: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error creating template');
|
||||
});
|
||||
}
|
||||
|
||||
function deleteTemplate(templateId) {
|
||||
if (!confirm('Are you sure you want to delete this template?')) {
|
||||
return;
|
||||
|
||||
@@ -181,6 +181,118 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Edit Weekly Menu Modal -->
|
||||
<div class="modal fade" id="editWeeklyMenuModal" tabindex="-1" aria-labelledby="editWeeklyMenuModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="editWeeklyMenuModalLabel">Edit Weekly Menu</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="editWeeklyMenuForm">
|
||||
<input type="hidden" id="editWeeklyMenuId" name="weekly_menu_id">
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label for="editWeeklyMenuName" class="form-label">Weekly Menu Name</label>
|
||||
<input type="text" class="form-control" id="editWeeklyMenuName" 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="editMonday" class="form-label">Monday</label>
|
||||
<select class="form-control template-select" id="editMonday" 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="editTuesday" class="form-label">Tuesday</label>
|
||||
<select class="form-control template-select" id="editTuesday" 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="editWednesday" class="form-label">Wednesday</label>
|
||||
<select class="form-control template-select" id="editWednesday" 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="editThursday" class="form-label">Thursday</label>
|
||||
<select class="form-control template-select" id="editThursday" 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="editFriday" class="form-label">Friday</label>
|
||||
<select class="form-control template-select" id="editFriday" 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="editSaturday" class="form-label">Saturday</label>
|
||||
<select class="form-control template-select" id="editSaturday" 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="editSunday" class="form-label">Sunday</label>
|
||||
<select class="form-control template-select" id="editSunday" 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">Save Changes</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentWeeklyMenuId = null;
|
||||
|
||||
@@ -193,6 +305,12 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
createWeeklyMenu();
|
||||
});
|
||||
|
||||
// Handle weekly menu editing
|
||||
document.getElementById('editWeeklyMenuForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
editWeeklyMenu();
|
||||
});
|
||||
|
||||
// Handle weekly menu application
|
||||
document.getElementById('applyWeeklyMenuForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
@@ -233,6 +351,9 @@ function loadWeeklyMenus() {
|
||||
<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-secondary me-2" onclick="editWeeklyMenuModal(${weeklyMenu.id})">
|
||||
<i class="bi bi-pencil"></i> Edit
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteWeeklyMenu(${weeklyMenu.id})">
|
||||
<i class="bi bi-trash"></i> Delete
|
||||
</button>
|
||||
@@ -391,6 +512,71 @@ function deleteWeeklyMenu(weeklyMenuId) {
|
||||
alert('Error deleting weekly menu');
|
||||
});
|
||||
}
|
||||
|
||||
function editWeeklyMenuModal(weeklyMenuId) {
|
||||
// Fetch weekly menu data
|
||||
fetch(`/weeklymenu/${weeklyMenuId}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.status === 'success') {
|
||||
// Populate the form
|
||||
document.getElementById('editWeeklyMenuId').value = data.id;
|
||||
document.getElementById('editWeeklyMenuName').value = data.name;
|
||||
|
||||
// Reset all selects
|
||||
const selects = ['editMonday', 'editTuesday', 'editWednesday', 'editThursday', 'editFriday', 'editSaturday', 'editSunday'];
|
||||
selects.forEach(selectId => {
|
||||
document.getElementById(selectId).value = '';
|
||||
});
|
||||
|
||||
// Set template assignments
|
||||
const assignments = data.template_assignments;
|
||||
if (assignments[0]) document.getElementById('editMonday').value = assignments[0];
|
||||
if (assignments[1]) document.getElementById('editTuesday').value = assignments[1];
|
||||
if (assignments[2]) document.getElementById('editWednesday').value = assignments[2];
|
||||
if (assignments[3]) document.getElementById('editThursday').value = assignments[3];
|
||||
if (assignments[4]) document.getElementById('editFriday').value = assignments[4];
|
||||
if (assignments[5]) document.getElementById('editSaturday').value = assignments[5];
|
||||
if (assignments[6]) document.getElementById('editSunday').value = assignments[6];
|
||||
|
||||
// Show modal
|
||||
new bootstrap.Modal(document.getElementById('editWeeklyMenuModal')).show();
|
||||
} else {
|
||||
alert('Error loading weekly menu: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error loading weekly menu');
|
||||
});
|
||||
}
|
||||
|
||||
function editWeeklyMenu() {
|
||||
const form = document.getElementById('editWeeklyMenuForm');
|
||||
const formData = new FormData(form);
|
||||
|
||||
fetch('/weeklymenu/edit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams(formData)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.status === 'success') {
|
||||
bootstrap.Modal.getInstance(document.getElementById('editWeeklyMenuModal')).hide();
|
||||
form.reset();
|
||||
loadWeeklyMenus();
|
||||
} else {
|
||||
alert('Error updating weekly menu: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Error updating weekly menu');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Hidden script to pass weekly menus data -->
|
||||
|
||||
Reference in New Issue
Block a user