529 lines
24 KiB
Python
529 lines
24 KiB
Python
from decimal import Decimal
|
|
import calendar
|
|
import csv
|
|
from datetime import date, timedelta
|
|
import logging
|
|
import re
|
|
import uuid
|
|
from urllib.parse import urlencode
|
|
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.contrib.auth import get_user_model
|
|
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
|
|
from django.contrib import messages
|
|
from django.db.models import Q, F
|
|
from django.template.loader import render_to_string
|
|
from django.utils.html import format_html
|
|
from django.db.models import Max
|
|
from django.db import transaction
|
|
from django.shortcuts import get_object_or_404, redirect, render
|
|
from django.urls import reverse
|
|
from django.utils.translation import get_language_from_request
|
|
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
|
from django.views.decorators.cache import never_cache
|
|
|
|
from .forms import FoodLogEditForm, FoodLogForm, ManualFoodForm
|
|
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType
|
|
from .services.diary import diary_context, selected_date
|
|
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
|
|
from .services.products import local_products
|
|
from .services.logging import apply_product_snapshot
|
|
from .services.hydration import sync_food_hydration
|
|
from .services.inventory_consumption import FACTORS, StockError, consume, stock
|
|
from planner.timezones import localdate_for_user
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
EXPORT_FIELDS = (
|
|
'date', 'time', 'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot',
|
|
'portion_label_snapshot', 'amount', 'unit', 'calories_kcal', 'carbohydrates_g',
|
|
'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g', 'source',
|
|
)
|
|
EXPORT_HEADERS = (
|
|
'date', 'time', 'meal', 'product_name', 'brand', 'barcode', 'portion_label',
|
|
'amount', 'unit', 'calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g',
|
|
'fibre_g', 'sugars_g', 'salt_g', 'source',
|
|
)
|
|
|
|
|
|
class _CsvSink:
|
|
def write(self, value):
|
|
return value
|
|
|
|
|
|
def _csv_value(value):
|
|
if value is None:
|
|
return ''
|
|
if isinstance(value, Decimal):
|
|
return format(value.normalize(), 'f')
|
|
if isinstance(value, str) and value.lstrip().startswith(('=', '+', '-', '@')):
|
|
return "'" + value
|
|
return str(value)
|
|
|
|
|
|
@login_required
|
|
def export_csv(request, period):
|
|
today = localdate_for_user(request.user)
|
|
if period == 'week':
|
|
first = today - timedelta(days=today.weekday())
|
|
last = first + timedelta(days=6)
|
|
iso_year, iso_week, _ = today.isocalendar()
|
|
filename = f'food-{iso_year}-W{iso_week:02d}.csv'
|
|
elif period == 'month':
|
|
first = today.replace(day=1)
|
|
last = today.replace(day=calendar.monthrange(today.year, today.month)[1])
|
|
filename = f'food-{today:%Y-%m}.csv'
|
|
else:
|
|
raise Http404('Unknown export period.')
|
|
rows = (FoodLogEntry.objects.filter(user=request.user, date__range=(first, last))
|
|
.order_by('date', 'time', 'pk').values_list(*EXPORT_FIELDS).iterator(chunk_size=500))
|
|
writer = csv.writer(_CsvSink())
|
|
|
|
def output():
|
|
yield writer.writerow(EXPORT_HEADERS)
|
|
for row in rows:
|
|
yield writer.writerow([_csv_value(value) for value in row])
|
|
|
|
response = StreamingHttpResponse(output(), content_type='text/csv; charset=utf-8')
|
|
response['Content-Disposition'] = f'attachment; filename="{filename}"'
|
|
return response
|
|
|
|
|
|
def _day(request):
|
|
try:
|
|
return selected_date(request), None
|
|
except ValueError as error:
|
|
return None, HttpResponseBadRequest(str(error))
|
|
|
|
|
|
def _portion_options(form, product):
|
|
if not product:
|
|
return []
|
|
options = []
|
|
for value, label in form.fields['portion'].choices:
|
|
amount = ''
|
|
if value == 'base':
|
|
amount = '100'
|
|
elif value == 'serving':
|
|
amount = str(product.serving_amount)
|
|
elif value.startswith('portion:'):
|
|
amount = str(form.portions[value.partition(':')[2]].amount)
|
|
options.append({'value': value, 'label': label, 'amount': amount})
|
|
return options
|
|
|
|
|
|
def _save_custom_portion(form, user, product, entry):
|
|
if form.cleaned_data.get('portion') != 'custom' or not form.cleaned_data.get('save_portion'):
|
|
return
|
|
if form.cleaned_data.get('make_default'):
|
|
FoodPortion.objects.filter(user=user, product=product, is_default=True).update(is_default=False)
|
|
portion = FoodPortion(user=user, product=product,
|
|
label=form.cleaned_data['new_portion_label'].strip(), amount=entry.amount,
|
|
unit=entry.unit, is_default=form.cleaned_data.get('make_default', False))
|
|
portion.full_clean()
|
|
portion.save()
|
|
|
|
|
|
def _save_entry(form, user, day, product, submission_id=None):
|
|
entry = form.save(commit=False)
|
|
entry.user = user
|
|
entry.date = day
|
|
if submission_id is not None:
|
|
entry.api_id = submission_id
|
|
apply_product_snapshot(entry, product)
|
|
sync_food_hydration(entry)
|
|
entry.full_clean()
|
|
entry.save()
|
|
_save_custom_portion(form, user, product, entry)
|
|
return entry
|
|
|
|
|
|
def _diary_response(request, day):
|
|
if request.headers.get('HX-Request') == 'true':
|
|
response = render(request, 'food/partials/diary_content.html',
|
|
diary_context(request.user, day, get_language_from_request(request)))
|
|
response['HX-Push-Url'] = f"{reverse('food:diary')}?date={day.isoformat()}"
|
|
response['HX-Trigger'] = 'hydrationChanged'
|
|
return response
|
|
return redirect(f"{reverse('food:diary')}?date={day.isoformat()}")
|
|
|
|
|
|
@login_required
|
|
def diary(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
return render(request, 'food/diary.html',
|
|
diary_context(request.user, day, get_language_from_request(request)))
|
|
|
|
|
|
@login_required
|
|
@never_cache
|
|
@require_GET
|
|
def attachment_file(request, identifier):
|
|
attachment = get_object_or_404(FoodLogAttachment, api_id=identifier, log_entry__user=request.user)
|
|
response = FileResponse(attachment.image.open('rb'), content_type=attachment.content_type)
|
|
response['Content-Disposition'] = 'inline'
|
|
response['X-Content-Type-Options'] = 'nosniff'
|
|
return response
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def add_food(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
product_id = request.GET.get('product') or request.POST.get('product')
|
|
product = get_object_or_404(FoodProduct, pk=product_id, owner=request.user) if product_id else None
|
|
query = request.GET.get('q', '').strip()[:100]
|
|
tab = request.GET.get('tab', 'overview')
|
|
if tab not in ('overview', 'recent', 'favourites', 'mine'):
|
|
tab = 'overview'
|
|
products = local_products(request.user, query)
|
|
favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True))
|
|
recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False)
|
|
.values('product_id').annotate(last_used=Max('created_at'))
|
|
.order_by('-last_used').values_list('product_id', flat=True)[:30])
|
|
recent_rank = {product_id: index for index, product_id in enumerate(recent_ids)}
|
|
if query:
|
|
normalized = ' '.join(query.split()).casefold()
|
|
def rank(item):
|
|
name = ' '.join(item.product_name.split()).casefold()
|
|
return (0 if item.barcode == normalized else 1 if name == normalized else
|
|
2 if item.pk in favourite_ids and name.startswith(normalized) else
|
|
3 if item.pk in favourite_ids else 4 if item.pk in recent_rank else 5,
|
|
recent_rank.get(item.pk, 999), name)
|
|
products = sorted(products[:500], key=rank)[:40]
|
|
tab = 'mine'
|
|
elif tab == 'favourites':
|
|
products = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:30])
|
|
elif tab == 'mine':
|
|
products = list(products.order_by('product_name')[:40])
|
|
elif tab == 'recent':
|
|
by_id = products.in_bulk(recent_ids)
|
|
products = [by_id[pk] for pk in recent_ids if pk in by_id]
|
|
else:
|
|
by_id = products.in_bulk(recent_ids)
|
|
favourites = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:20])
|
|
recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20]
|
|
products = favourites + recents
|
|
for item in products:
|
|
item.is_favourite = item.pk in favourite_ids
|
|
if product:
|
|
product.is_favourite = product.pk in favourite_ids
|
|
inventory_options = []
|
|
inventory_packages = []
|
|
inventory_total_original = Decimal(0)
|
|
inventory_total_available = Decimal(0)
|
|
if product:
|
|
for item in stock(request.user, product):
|
|
if item.original_amount is None or item.inventory_unit not in FACTORS:
|
|
continue
|
|
dimension, factor = FACTORS[item.inventory_unit]
|
|
if dimension != FACTORS[product.base_unit][0] or item.remaining_amount <= 0:
|
|
continue
|
|
inventory_packages.append({'id': str(item.api_id), 'original': item.original_amount,
|
|
'remaining': item.remaining_amount, 'unit': item.inventory_unit,
|
|
'remaining_base': item.remaining_amount * factor,
|
|
'location': item.location.name, 'opened': item.opened})
|
|
inventory_total_original += item.original_amount * factor
|
|
inventory_total_available += item.remaining_amount * factor
|
|
inventory_options.append((str(item.api_id),
|
|
f'{item.location.name}: {item.remaining_amount:g} of {item.original_amount:g} {item.inventory_unit} left'))
|
|
form = FoodLogForm(request.POST or None, product=product, inventory_options=inventory_options,
|
|
initial={'meal': meal, 'unit': product.base_unit if product else 'g'}) if product else None
|
|
submission_id = (request.POST.get('submission_id') or str(uuid.uuid4())) if request.method == 'POST' else str(uuid.uuid4())
|
|
if request.method == 'POST':
|
|
if not product:
|
|
return HttpResponseBadRequest('Choose a product.')
|
|
if form.is_valid():
|
|
try:
|
|
submission_uuid = uuid.UUID(submission_id)
|
|
except (ValueError, TypeError, AttributeError):
|
|
form.add_error(None, 'Reload this form and try again.')
|
|
else:
|
|
try:
|
|
with transaction.atomic():
|
|
get_user_model().objects.select_for_update().get(pk=request.user.pk)
|
|
previous = FoodLogEntry.objects.filter(user=request.user, api_id=submission_uuid).first()
|
|
if previous:
|
|
if (previous.date == day and previous.product_id == product.pk and
|
|
previous.meal == form.cleaned_data['meal'] and
|
|
previous.amount == form.cleaned_data['amount'] and
|
|
previous.unit == form.cleaned_data['unit']):
|
|
return _diary_response(request, day)
|
|
form.add_error(None, 'This submission was already used for a different entry.')
|
|
else:
|
|
entry = _save_entry(form, request.user, day, product, submission_uuid)
|
|
package_id = form.cleaned_data.get('inventory_package')
|
|
if package_id:
|
|
consume(request.user, product, entry.amount, entry.unit,
|
|
package_id=package_id, source='manual',
|
|
source_reference=str(entry.api_id),
|
|
idempotency_key=f'food-log:{entry.api_id}')
|
|
return _diary_response(request, day)
|
|
except StockError as exc:
|
|
form.add_error('inventory_package', str(exc))
|
|
portion_options = _portion_options(form, product) if form else []
|
|
template = 'food/partials/add_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/add.html'
|
|
return render(request, template, {'day': day, 'meal': meal, 'products': products[:40],
|
|
'product': product, 'form': form, 'query': query, 'tab': tab,
|
|
'favourite_ids': favourite_ids, 'favourites': favourites if not query and tab == 'overview' else [],
|
|
'recents': recents if not query and tab == 'overview' else [],
|
|
'is_favourite': product.pk in favourite_ids if product else False, 'portion_options': portion_options,
|
|
'inventory_packages': inventory_packages, 'submission_id': submission_id,
|
|
'inventory_total_original': inventory_total_original, 'inventory_total_available': inventory_total_available})
|
|
|
|
|
|
@login_required
|
|
@require_POST
|
|
def toggle_favourite(request, pk):
|
|
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
|
favourite, created = FoodFavourite.objects.get_or_create(user=request.user, product=product)
|
|
if not created:
|
|
favourite.delete()
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.POST.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
if request.headers.get('HX-Request') == 'true':
|
|
if request.POST.get('tab') == 'overview' and request.POST.get('is_list') == '1':
|
|
favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True))
|
|
recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False)
|
|
.values('product_id').annotate(last_used=Max('created_at'))
|
|
.order_by('-last_used').values_list('product_id', flat=True)[:30])
|
|
favourites = list(FoodProduct.objects.filter(owner=request.user, pk__in=favourite_ids).order_by('product_name')[:20])
|
|
by_id = FoodProduct.objects.filter(owner=request.user).in_bulk(recent_ids)
|
|
recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20]
|
|
for item in favourites + recents:
|
|
item.is_favourite = item.pk in favourite_ids
|
|
return render(request, 'food/partials/favourite_update.html', {
|
|
'product': product, 'is_favourite': created, 'day': day, 'meal': meal,
|
|
'tab': 'overview', 'is_list': True, 'favourites': favourites, 'recents': recents,
|
|
})
|
|
if request.POST.get('tab') == 'favourites' and request.POST.get('is_list') == '1' and not created:
|
|
return HttpResponse('')
|
|
return render(request, 'food/partials/favourite_button.html', {'product': product,
|
|
'is_favourite': created, 'day': day, 'meal': meal,
|
|
'tab': request.POST.get('tab'), 'is_list': request.POST.get('is_list') == '1'})
|
|
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def external_search(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
query = (request.GET.get('q') or request.POST.get('q') or '').strip()[:100]
|
|
try:
|
|
page = int(request.GET.get('page', '1'))
|
|
except ValueError:
|
|
return HttpResponseBadRequest('Invalid page.')
|
|
results = []
|
|
notice = ''
|
|
if request.method == 'POST':
|
|
try:
|
|
results = cached_search(request.user, query, page)
|
|
except (OpenFoodFactsError, ValueError) as error:
|
|
logger.info('Food external search unavailable: %s', error)
|
|
notice = str(error)
|
|
return render(request, 'food/external_search.html', {'day': day, 'meal': meal, 'query': query,
|
|
'results': results, 'notice': notice, 'page': page})
|
|
|
|
|
|
@login_required
|
|
@require_POST
|
|
def import_product(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.POST.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
barcode = request.POST.get('barcode', '').strip()
|
|
try:
|
|
product = cached_product(request.user, barcode)
|
|
except (OpenFoodFactsError, ValueError) as error:
|
|
messages.warning(request, f'{error} Recent, favourite, and saved products are still available.')
|
|
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}")
|
|
if not product:
|
|
return redirect(f"{reverse('food:not-found')}?{urlencode({'date': day.isoformat(), 'meal': meal, 'barcode': barcode})}")
|
|
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
|
|
|
|
|
|
@login_required
|
|
def scanner(request):
|
|
if request.GET.get('mode') == 'inventory':
|
|
return redirect('food:scanner-inventory')
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.GET.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
return render(request, 'food/scanner.html', {'day': day, 'meal': meal, 'inventory_mode': False})
|
|
|
|
|
|
@login_required
|
|
def product_not_found(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.GET.get('meal') or MealType.BREAKFAST
|
|
barcode = request.GET.get('barcode', '').strip()
|
|
if meal not in MealType.values or not re.fullmatch(r'[0-9]{1,64}', barcode):
|
|
return HttpResponseBadRequest('Invalid barcode or meal.')
|
|
return render(request, 'food/not_found.html', {'day': day, 'meal': meal, 'barcode': barcode})
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def manual_food(request):
|
|
day, error = _day(request)
|
|
if error:
|
|
return error
|
|
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
|
|
if meal not in MealType.values:
|
|
return HttpResponseBadRequest('Invalid meal.')
|
|
barcode = request.GET.get('barcode', '').strip()
|
|
if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode):
|
|
return HttpResponseBadRequest('Invalid barcode.')
|
|
form = ManualFoodForm(request.POST or None, user=request.user, initial={'barcode': barcode})
|
|
if request.method == 'POST' and form.is_valid():
|
|
product = form.save(commit=False)
|
|
product.owner = request.user
|
|
product.save()
|
|
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
|
|
return render(request, 'food/manual.html', {'form': form, 'day': day, 'meal': meal})
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def edit_entry(request, pk):
|
|
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
|
|
product = entry.product
|
|
original_amount = entry.amount
|
|
original_nutrients = {field: getattr(entry, field) for field in
|
|
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')}
|
|
form = FoodLogEditForm(request.POST or None, instance=entry, product=product)
|
|
if request.method == 'POST' and form.is_valid():
|
|
updated = form.save(commit=False)
|
|
factor = updated.amount / original_amount
|
|
for field, original in original_nutrients.items():
|
|
if form.cleaned_data['edit_nutrition']:
|
|
value = form.cleaned_data[field]
|
|
else:
|
|
value = (original * factor).quantize(Decimal('0.001')) if original is not None else None
|
|
setattr(updated, field, value)
|
|
with transaction.atomic():
|
|
sync_food_hydration(updated)
|
|
updated.full_clean()
|
|
updated.save()
|
|
if updated.created_via == 'recipe':
|
|
run = getattr(updated, 'recipe_cooking_run', None)
|
|
if run:
|
|
run.consumed_servings = updated.amount
|
|
run.save(update_fields=('consumed_servings',))
|
|
if product:
|
|
_save_custom_portion(form, request.user, product, updated)
|
|
return _diary_response(request, entry.date)
|
|
for name in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g'):
|
|
setattr(entry, f'effective_{name}', entry.effective_nutrient(name))
|
|
template = 'food/partials/edit_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/edit.html'
|
|
return render(request, template, {'entry': entry, 'form': form, 'product': product,
|
|
'portion_options': _portion_options(form, product)})
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def edit_product(request, pk):
|
|
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
|
form = ManualFoodForm(request.POST or None, instance=product, user=request.user)
|
|
if request.method == 'POST' and form.is_valid():
|
|
product = form.save(commit=False)
|
|
nutrition_fields = {'energy_kcal_100', 'carbohydrates_100', 'protein_100',
|
|
'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'}
|
|
if product.source == FoodProduct.Source.OPEN_FOOD_FACTS and nutrition_fields.intersection(form.changed_data):
|
|
product.raw_data = {**(product.raw_data if isinstance(product.raw_data, dict) else {}),
|
|
'manual_nutrition_override': True}
|
|
product.save()
|
|
messages.success(request, 'Product saved. Existing diary entries keep their recorded nutrition.')
|
|
return redirect('food:product-edit', pk=product.pk)
|
|
return render(request, 'food/product_edit.html', {'form': form, 'product': product})
|
|
|
|
|
|
@login_required
|
|
@require_POST
|
|
def delete_entry(request, pk):
|
|
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
|
|
day = entry.date
|
|
entry.delete()
|
|
return _diary_response(request, day)
|
|
|
|
|
|
@login_required
|
|
@require_POST
|
|
def increment_entry(request, pk):
|
|
return _change_entry_quantity(request, pk, Decimal('1.00'))
|
|
|
|
|
|
@login_required
|
|
@require_POST
|
|
def decrement_entry(request, pk):
|
|
return _change_entry_quantity(request, pk, Decimal('-1.00'))
|
|
|
|
|
|
def _change_entry_quantity(request, pk, delta):
|
|
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
|
|
with transaction.atomic():
|
|
entries = FoodLogEntry.objects.filter(pk=entry.pk, user=request.user)
|
|
if delta < 0:
|
|
entries = entries.filter(quantity__gt=1)
|
|
changed = entries.update(quantity=F('quantity') + delta)
|
|
entry.refresh_from_db()
|
|
if not changed:
|
|
return HttpResponse('Quantity cannot be reduced further. Reload the diary.', status=409)
|
|
if request.headers.get('HX-Request') != 'true':
|
|
return _diary_response(request, entry.date)
|
|
context = diary_context(request.user, entry.date, get_language_from_request(request))
|
|
for meal in context['meals']:
|
|
for item in meal['entries']:
|
|
if item.pk == entry.pk:
|
|
entry = item
|
|
break
|
|
html = render_to_string('food/partials/entry.html', {'entry': entry}, request=request)
|
|
summary = render_to_string('food/partials/nutrition_summary.html', context, request=request)
|
|
meal = next(meal for meal in context['meals'] if meal['key'] == entry.meal)
|
|
heading = render_to_string('food/partials/meal_heading.html', {'meal': meal, 'day': entry.date}, request=request)
|
|
response = HttpResponse(html + summary.replace('id="food-nutrition-summary"', 'id="food-nutrition-summary" hx-swap-oob="outerHTML"', 1)
|
|
+ heading.replace('id="food-meal-heading-', 'hx-swap-oob="outerHTML" id="food-meal-heading-', 1)
|
|
+ format_html('<div id="food-quantity-status" hx-swap-oob="innerHTML">{} quantity updated to {} portions.</div>', entry.product_name_snapshot, entry.quantity.normalize()))
|
|
response['HX-Trigger'] = 'hydrationChanged'
|
|
return response
|
|
|
|
|
|
@login_required
|
|
@require_http_methods(['GET', 'POST'])
|
|
def product_hydration(request, pk):
|
|
from .forms import FoodProductHydrationForm
|
|
|
|
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
|
form = FoodProductHydrationForm(request.POST or None, instance=product)
|
|
if request.method == 'POST' and form.is_valid():
|
|
product = form.save(commit=False)
|
|
product.hydration_source = 'manual'
|
|
product.save()
|
|
return redirect('food:diary')
|
|
return render(request, 'food/product_hydration.html', {'product': product, 'form': form})
|