added alembic database migrations, json import/export

This commit is contained in:
2025-09-28 07:59:23 -07:00
parent 26afbe976d
commit ed332b8701
7 changed files with 193 additions and 1103 deletions

View File

@@ -0,0 +1,39 @@
{% extends "admin/index.html" %}
{% block admin_content %}
<div class="card">
<div class="card-header">
<h5 class="mb-0">Database Backups</h5>
</div>
<div class="card-body">
<p>
Create a snapshot of the database or restore from a previous backup. Backups are stored in the <code>/backups</code> directory.
</p>
<div class="mb-3">
<form action="/admin/backups/create" method="post" class="d-inline">
<button type="submit" class="btn btn-primary">
<i class="bi bi-cloud-download"></i> Backup Now
</button>
</form>
</div>
<hr>
<h5>Restore from Backup</h5>
<form action="/admin/backups/restore" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="backup-file" class="form-label">Select backup file to restore</label>
<select class="form-select" id="backup-file" name="backup_file">
{% for backup in backups %}
<option value="{{ backup }}">{{ backup }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-success">
<i class="bi bi-cloud-upload"></i> Restore
</button>
</form>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,35 @@
{% extends "admin/index.html" %}
{% block admin_content %}
<div class="card">
<div class="card-header">
<h5 class="mb-0">Import/Export All Data</h5>
</div>
<div class="card-body">
<p>
This section allows you to export all your data (foods, meals, plans, etc.) into a single JSON file.
You can also import this data back, which will overwrite any existing data.
This is useful for backups or migrating to a new instance.
</p>
<div class="mb-3">
<a href="/export/all" class="btn btn-primary" download="meal_planner_backup.json">
<i class="bi bi-download"></i> Export All Data
</a>
</div>
<hr>
<h5>Import Data</h5>
<form id="import-form" action="/import/all" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="import-file" class="form-label">Select JSON file to import</label>
<input class="form-control" type="file" id="import-file" name="file" accept=".json">
</div>
<button type="submit" class="btn btn-success">
<i class="bi bi-upload"></i> Import and Overwrite
</button>
</form>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,18 @@
{% extends "base.html" %}
{% block content %}
<h2 class="mb-4">Admin</h2>
<ul class="nav nav-tabs" id="adminTab" role="tablist">
<li class="nav-item" role="presentation">
<a class="nav-link" id="imports-tab" href="/admin/imports">Imports</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="backups-tab" href="/admin/backups">Backups</a>
</li>
</ul>
<div class="tab-content mt-3">
{% block admin_content %}{% endblock %}
</div>
{% endblock %}

View File

@@ -67,11 +67,6 @@
<i class="bi bi-egg-fried"></i> Meals
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" onclick="location.href='/imports'">
<i class="bi bi-upload"></i> Imports
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" onclick="location.href='/plan'">
<i class="bi bi-calendar-week"></i> Plan
@@ -93,6 +88,11 @@
<i class="bi bi-calendar-check"></i> Tracker
</button>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" href="/admin">
<i class="bi bi-gear"></i> Admin
</a>
</li>
</ul>
<div class="tab-content mt-3">

View File

@@ -1,270 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-md-4">
<h3>Food Import</h3>
<form action="/foods/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 Foods CSV</button>
</form>
</div>
<div class="col-md-4">
<h3>OpenFoodFacts Search</h3>
<div class="mb-3">
<label class="form-label">Search for Food</label>
<input type="text" class="form-control" id="offSearch" placeholder="e.g., apple, banana, pizza">
</div>
<button type="button" class="btn btn-primary mb-4" onclick="searchOpenFoodFacts()">Search</button>
<div id="offResults" class="mt-3" style="display: none;">
<h6>Search Results:</h6>
<div id="offResultsList" class="list-group"></div>
</div>
</div>
<div class="col-md-4">
<h3>Meal Import</h3>
<form action="/meals/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 Meals CSV</button>
</form>
</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="row mt-4">
<div class="col-md-6">
<h3>Global Data Management</h3>
<div class="mb-3">
<button type="button" class="btn btn-info" onclick="exportAllData()">Export All Data</button>
</div>
<form action="/import/all" method="post" enctype="multipart/form-data" id="importAllForm">
<div class="mb-3">
<label class="form-label">Import All Data (JSON)</label>
<input type="file" class="form-control" name="file" accept=".json" required>
</div>
<button type="submit" class="btn btn-warning">Import All Data</button>
</form>
</div>
</div>
<div class="mt-4" id="upload-results" style="display: none;">
<div class="alert alert-success">
<strong>Upload Results:</strong>
<span id="created-count"></span> created,
<span id="updated-count"></span> updated
<div id="error-list" class="mt-2 text-danger"></div>
</div>
</div>
<script>
// CSV upload handling (copied from foods.html)
document.querySelectorAll('form').forEach(form => {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const submitBtn = form.querySelector('button[type="submit"]');
const resultsDiv = document.getElementById('upload-results');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Uploading...';
try {
const formData = new FormData(form);
const response = await fetch(form.action, {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const results = await response.json();
resultsDiv.style.display = 'block';
document.getElementById('created-count').textContent = results.created || 0;
document.getElementById('updated-count').textContent = results.updated || 0;
if (results.errors?.length > 0) {
document.getElementById('error-list').innerHTML =
`<strong>Errors (${results.errors.length}):</strong><br>` + results.errors.join('<br>');
} else {
document.getElementById('error-list').innerHTML = '';
}
if (results.created || results.updated) {
setTimeout(() => window.location.reload(), 2000);
}
} catch (error) {
resultsDiv.style.display = 'block';
resultsDiv.querySelector('.alert').className = 'alert alert-danger';
document.getElementById('error-list').innerHTML =
`<strong>Upload Failed:</strong> ${error.message}`;
} finally {
submitBtn.disabled = false;
submitBtn.textContent = submitBtn.textContent.replace('Uploading...', 'Upload CSV');
}
});
});
// OpenFoodFacts search functionality
async function searchOpenFoodFacts() {
const query = document.getElementById('offSearch').value.trim();
if (!query) {
alert('Please enter a search term');
return;
}
const resultsDiv = document.getElementById('offResults');
const resultsList = document.getElementById('offResultsList');
// Show loading
resultsDiv.style.display = 'block';
resultsList.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"></div> Searching...</div>';
try {
const response = await fetch(`/foods/search_openfoodfacts?query=${encodeURIComponent(query)}`);
const data = await response.json();
if (data.status === 'success') {
displayOpenFoodFactsResults(data.results);
} else {
resultsList.innerHTML = `<div class="alert alert-danger">Error: ${data.message}</div>`;
}
} catch (error) {
resultsList.innerHTML = `<div class="alert alert-danger">Error: ${error.message}</div>`;
}
}
function displayOpenFoodFactsResults(results) {
const resultsList = document.getElementById('offResultsList');
if (results.length === 0) {
resultsList.innerHTML = '<div class="alert alert-info">No results found</div>';
return;
}
let html = '';
results.forEach((food, index) => {
html += `
<div class="list-group-item">
<div class="d-flex justify-content-between align-items-start">
<div class="flex-grow-1">
<h6 class="mb-1">${food.name}</h6>
<p class="mb-1 text-muted small">
${food.serving_size}${food.serving_unit} |
${food.calories} cal |
P: ${food.protein}g, C: ${food.carbs}g, F: ${food.fat}g
</p>
${food.brand ? `<small class="text-muted">Brand: ${food.brand}</small>` : ''}
</div>
<button class="btn btn-sm btn-success" onclick="addOpenFoodFactsFood(${index})">
<i class="bi bi-plus-circle"></i> Add
</button>
</div>
</div>
`;
});
resultsList.innerHTML = html;
// Store results for later use
window.offSearchResults = results;
}
async function addOpenFoodFactsFood(index) {
const food = window.offSearchResults[index];
if (!food) return;
try {
const formData = new FormData();
Object.keys(food).forEach(key => {
if (key !== 'image_url' && key !== 'openfoodfacts_id' && key !== 'brand') {
formData.append(key, food[key]);
}
});
const response = await fetch('/foods/add_openfoodfacts', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.status === 'success') {
alert('Food added successfully!');
// Optionally reload the page or update UI
} else {
alert('Error adding food: ' + result.message);
}
} catch (error) {
alert('Error adding food: ' + error.message);
}
}
// Allow Enter key to trigger search
document.getElementById('offSearch').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
searchOpenFoodFacts();
}
});
function exportAllData() {
window.location.href = '/export/all';
}
document.getElementById('importAllForm').addEventListener('submit', async function(e) {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const fileInput = form.querySelector('input[type="file"]');
const file = fileInput.files[0];
if (file) {
if (confirm('Are you sure you want to import all data? This will overwrite existing data.')) {
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Importing...';
try {
const response = await fetch('/import/all', {
method: 'POST',
body: formData
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
}
alert('Import successful! The page will now reload.');
window.location.reload();
} catch (error) {
alert('Import failed: ' + error.message);
} finally {
submitBtn.disabled = false;
submitBtn.innerHTML = 'Import All Data';
}
}
} else {
alert('Please select a JSON file to import.');
}
});
</script>
{% endblock %}