Enhancements

This commit is contained in:
Joren de Graaf
2026-10-11 20:46:55 +02:00
parent cb12c23732
commit 000ec834b0
26 changed files with 813 additions and 30 deletions
+200 -8
View File
@@ -5,6 +5,7 @@ import json
import secrets
from django.conf import settings
from decimal import Decimal
from datetime import datetime
from functools import wraps
from uuid import UUID
@@ -17,12 +18,14 @@ from django.utils import timezone
from django.utils.dateparse import parse_date, parse_time
from django.views.decorators.csrf import csrf_exempt
from planner.models import UserSettings
from planner.timezones import localdate_for_user
from planner.models import UserSettings, WaterIntakeEntry
from planner.timezones import localdate_for_user, timezone_for_user
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
InventoryCategory, InventoryLocation, KitchenInventoryItem,
MealType, PersonalAccessToken, Unit)
from .services.logging import apply_product_snapshot
from .services.hydration import sync_food_hydration, validate_rules
from planner.services.hydration import daily_hydration
from .services.openfoodfacts import OpenFoodFactsError
from .services.product_resolution import (create_manual, external_matches, import_off,
local_matches, match_data)
@@ -170,6 +173,11 @@ def _entry_data(entry):
data.update(id=str(entry.api_id), date=entry.date.isoformat(),
time=entry.time.isoformat() if entry.time else None,
product_id=str(entry.product.api_id) if entry.product_id else None,
beverage_volume_ml=(str(entry.beverage_volume_ml) if entry.beverage_volume_ml is not None else None),
hydration_amount_ml=str(entry.hydration_amount_ml),
hydration_factor=str(entry.hydration_factor_snapshot),
hydration_kind=entry.hydration_kind or None,
hydration_source=entry.hydration_source or None,
attachments=[_attachment_data(item) for item in entry.attachments.all()],
created_at=entry.created_at.isoformat(), updated_at=entry.updated_at.isoformat())
for name in ('amount', *NUTRIENTS):
@@ -187,6 +195,8 @@ def _product_data(product):
if isinstance(data[name], Decimal):
data[name] = str(data[name])
data['id'] = str(product.api_id)
data.update(is_beverage=product.is_beverage, hydration_enabled=product.hydration_enabled,
hydration_factor=str(product.hydration_factor), hydration_source=product.hydration_source)
data['package_amount'] = str(product.package_amount) if product.package_amount is not None else None
data['package_unit'] = product.package_unit or None
data['portions'] = [{'label': p.label, 'amount': str(p.amount), 'unit': p.unit,
@@ -204,6 +214,7 @@ def _inventory_data(item):
'original_amount': str(item.original_amount) if item.original_amount is not None else None,
'unit': item.inventory_unit or 'packs', 'status': item.package_status,
'best_before': item.best_before.isoformat() if item.best_before else None,
'archived_at': item.archived_at.isoformat() if item.archived_at else None,
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
@@ -503,6 +514,7 @@ def _save_entry(request, data, entry=None):
for name in MANUAL_FIELDS:
if name in data:
setattr(entry, name, _decimal(data[name], name) if data[name] is not None else None)
sync_food_hydration(entry)
entry.full_clean()
entry.save()
return entry, None
@@ -635,16 +647,68 @@ def inventory_detail(request, identifier):
@api_view('inventory:write', ('PATCH', 'DELETE'))
def inventory_change(request, identifier):
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
archived_at__isnull=True).select_related('product', 'location', 'category').first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
if request.method == 'DELETE':
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
archived_at__isnull=True).first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
item.archived_at = timezone.now()
item.save(update_fields=('archived_at', 'updated_at'))
return JsonResponse({'deleted': True})
item, failure = _save_inventory(request, _json(request), item)
return failure or JsonResponse(_inventory_data(item))
data = _json(request)
try:
with transaction.atomic():
# Serialize absolute remaining-amount updates with stock consumption.
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
item = KitchenInventoryItem.objects.select_for_update().filter(
user=request.api_user, api_id=identifier, archived_at__isnull=True,
).select_related('product', 'location', 'category').first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
remaining = data.get('remaining_amount', item.remaining_amount)
if 'remaining_amount' in data and remaining is not None:
try:
remaining = _decimal(remaining, 'remaining_amount')
except ValueError as exc:
return _inventory_validation('remaining_amount', str(exc))
if item.original_amount is None or item.remaining_amount is None:
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
if remaining > item.original_amount:
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
if remaining != remaining.quantize(Decimal('.001')):
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
if remaining > item.remaining_amount:
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
if remaining < item.remaining_amount:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0],
'Change package identity or size separately from consumption.')
if data.get('opened') is False and remaining > 0:
return _inventory_validation('opened', 'A partly used package must be opened.')
from .services.inventory_consumption import StockError, consume
try:
consume(request.api_user, item.product, item.remaining_amount - remaining,
item.inventory_unit, package_id=item.api_id, source='mcp',
description=str(data.get('notes') or '')[:255])
except StockError as exc:
return _inventory_validation('remaining_amount', str(exc))
item.refresh_from_db()
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
elif 'remaining_amount' in data:
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
item, failure = _save_inventory(request, data, item)
return failure or JsonResponse(_inventory_data(item))
except (ValueError, ValidationError) as exc:
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
field, messages = next(iter(exc.message_dict.items()))
return _inventory_validation(field, '; '.join(messages))
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
def _inventory_validation(field, reason):
return error('invalid_inventory_update', 'Inventory update rejected.', 400,
{'field': field, 'reason': reason})
@api_view('food:write', ('POST',))
@@ -815,3 +879,131 @@ def inventory_undo(request, identifier):
return JsonResponse({'transaction_id': str(reversal.pk), 'reverses': str(reversal.reverses_id)})
except (StockError, ValueError) as exc:
return error('cannot_undo', str(exc))
def _water_data(entry):
return {'id': str(entry.api_id), 'amount_ml': str(entry.amount_ml),
'beverage_type': entry.beverage_type, 'recorded_at': entry.recorded_at.isoformat(),
'source': 'manual'}
def _water_amount(value):
amount = _decimal(value, 'amount_ml', positive=True)
if amount > 3000 or amount != amount.quantize(Decimal('.001')):
raise ValueError('Amount must be at most 3000 ml with up to three decimal places.')
return amount
def _water_timestamp(value, user):
if not value:
return timezone.now()
try:
parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
except ValueError:
raise ValueError('Use an ISO 8601 timestamp.') from None
if timezone.is_naive(parsed):
parsed = timezone.make_aware(parsed, timezone_for_user(user))
return parsed
@api_view('food:read', ('GET',))
def hydration_daily(request):
value = request.GET.get('date')
day = parse_date(value) if value else localdate_for_user(request.api_user)
if day is None or (value and day.isoformat() != value):
return error('invalid_date', 'Use YYYY-MM-DD.')
result = daily_hydration(request.api_user, day)
return JsonResponse({key: value.isoformat() if key == 'date' else str(value)
for key, value in result.items()})
@api_view('food:write', ('POST',))
def hydration_log(request):
data = _json(request)
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
allowed = {'amount_ml', 'beverage_type', 'recorded_at'}
if set(data) - allowed:
return error('invalid_fields', 'Unknown hydration fields.')
amount = _water_amount(data.get('amount_ml'))
beverage_type = str(data.get('beverage_type', 'water')).strip().lower()
if not beverage_type or len(beverage_type) > 32:
return error('invalid_beverage_type', 'Invalid beverage type.')
recorded_at = _water_timestamp(data.get('recorded_at'), request.api_user)
key = request.headers.get('Idempotency-Key', '')
def create():
if key:
previous = WaterIntakeEntry.objects.filter(user=request.api_user, idempotency_key=key).first()
if previous:
if previous.amount_ml != amount or previous.beverage_type != beverage_type or (
data.get('recorded_at') and previous.recorded_at != recorded_at):
return error('idempotency_conflict', 'Key was used for another hydration entry.', 409)
return JsonResponse(_water_data(previous))
entry = WaterIntakeEntry.objects.create(user=request.api_user, amount_ml=amount,
beverage_type=beverage_type, recorded_at=recorded_at, idempotency_key=key)
return JsonResponse(_water_data(entry), status=201)
return _idempotent(request, data, create)
@api_view('food:write', ('PATCH', 'DELETE'))
def hydration_manual_entry(request, identifier):
entry = WaterIntakeEntry.objects.filter(user=request.api_user, api_id=identifier).first()
if entry is None:
return error('hydration_entry_not_found', 'Manual hydration entry not found.', 404)
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
if request.method == 'DELETE':
entry.delete()
return JsonResponse({'deleted': True})
data = _json(request)
if set(data) - {'amount_ml', 'beverage_type', 'recorded_at'}:
return error('invalid_fields', 'Unknown hydration fields.')
if 'amount_ml' in data:
entry.amount_ml = _water_amount(data['amount_ml'])
if 'beverage_type' in data:
entry.beverage_type = str(data['beverage_type']).strip().lower()
if not entry.beverage_type or len(entry.beverage_type) > 32:
return error('invalid_beverage_type', 'Invalid beverage type.')
if 'recorded_at' in data:
entry.recorded_at = _water_timestamp(data['recorded_at'], request.api_user)
entry.full_clean()
entry.save()
return JsonResponse(_water_data(entry))
def _hydration_settings_data(settings):
return {'daily_water_goal_ml': settings.daily_water_goal_ml,
'auto_count_food_drinks': settings.auto_count_food_drinks,
'include_liquid_foods': settings.include_liquid_foods,
'show_hydration_breakdown': settings.show_hydration_breakdown,
'allow_manual_hydration_adjustments': settings.allow_manual_hydration_adjustments,
'hydration_beverage_rules': settings.hydration_beverage_rules}
@api_view({'GET': 'food:read', 'PATCH': 'food:write'}, ('GET', 'PATCH'))
def hydration_settings(request):
settings = UserSettings.objects.get_or_create(user=request.api_user)[0]
if request.method == 'GET':
return JsonResponse(_hydration_settings_data(settings))
data = _json(request)
allowed = set(_hydration_settings_data(settings))
if set(data) - allowed:
return error('invalid_fields', 'Unknown hydration settings.')
for field in ('auto_count_food_drinks', 'include_liquid_foods', 'show_hydration_breakdown',
'allow_manual_hydration_adjustments'):
if field in data:
if not isinstance(data[field], bool):
return error('invalid_setting', f'{field} must be true or false.')
setattr(settings, field, data[field])
if 'daily_water_goal_ml' in data:
goal = data['daily_water_goal_ml']
if isinstance(goal, bool) or not isinstance(goal, int) or not 250 <= goal <= 10000:
return error('invalid_goal', 'Daily goal must be 250 to 10000 ml.')
settings.daily_water_goal_ml = goal
if 'hydration_beverage_rules' in data:
settings.hydration_beverage_rules = validate_rules(data['hydration_beverage_rules'])
settings.full_clean()
settings.save()
return JsonResponse(_hydration_settings_data(settings))
+29
View File
@@ -51,6 +51,20 @@ GROCERIES = {'type': 'object', 'required': ['items'], 'properties': {
UPLOAD = {'type': 'object', 'required': ['image'], 'properties': {
'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'},
}}
HYDRATION_MANUAL = {'type': 'object', 'properties': {
'amount_ml': {'type': 'string', 'description': 'Positive decimal, at most 3000 ml'},
'beverage_type': {'type': 'string'},
'recorded_at': {'type': 'string', 'format': 'date-time',
'description': 'Defaults to now; naive values use the user time zone'},
}}
HYDRATION_SETTINGS = {'type': 'object', 'properties': {
'daily_water_goal_ml': {'type': 'integer', 'minimum': 250, 'maximum': 10000},
**{name: {'type': 'boolean'} for name in (
'auto_count_food_drinks', 'include_liquid_foods', 'show_hydration_breakdown',
'allow_manual_hydration_adjustments')},
'hydration_beverage_rules': {'type': 'object', 'description':
'Optional beverage type rules with enabled and factor (0 to 1) keys.'},
}}
@require_GET
@@ -90,6 +104,16 @@ def schema(request):
'/kitchen/consumption/preview/': {'post': operation('Preview package deductions without changing stock', 'inventory:read')},
'/kitchen/consumption/': {'post': operation('Consume stock atomically with Idempotency-Key', 'inventory:write')},
'/kitchen/consumption/{id}/undo/': {'post': operation('Undo a safe consumption transaction', 'inventory:write')},
'/hydration/daily/': {'get': operation('Combined manual and Food Diary fluid totals for a user local date', 'food:read')},
'/hydration/manual/': {'post': operation('Create standalone fluid entry with optional Idempotency-Key', 'food:write', HYDRATION_MANUAL)},
'/hydration/manual/{id}/': {
'patch': operation('Correct own manual fluid entry', 'food:write', HYDRATION_MANUAL),
'delete': operation('Delete own manual fluid entry', 'food:write'),
},
'/hydration/settings/': {
'get': operation('Read hydration settings', 'food:read'),
'patch': operation('Update hydration settings', 'food:write', HYDRATION_SETTINGS),
},
},
}
for path, methods in document['paths'].items():
@@ -106,6 +130,11 @@ def schema(request):
'description': 'Local calendar date; defaults to today in the user time zone.',
'schema': {'type': 'string', 'format': 'date'},
}]
document['paths']['/hydration/daily/']['get']['parameters'] = [{
'name': 'date', 'in': 'query', 'required': False,
'description': 'Local calendar date; defaults to today in the user time zone.',
'schema': {'type': 'string', 'format': 'date'},
}]
document['paths']['/food/products/lookup/']['get']['parameters'] = [
{'name': name, 'in': 'query', 'required': False, 'schema': schema} for name, schema in (
('query', {'type': 'string'}), ('barcode', {'type': 'string'}), ('brand', {'type': 'string'}),
+4
View File
@@ -21,4 +21,8 @@ urlpatterns = [
path('kitchen/consumption/preview/', api.inventory_preview),
path('kitchen/consumption/', api.inventory_consume),
path('kitchen/consumption/<uuid:identifier>/undo/', api.inventory_undo),
path('hydration/daily/', api.hydration_daily),
path('hydration/manual/', api.hydration_log),
path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry),
path('hydration/settings/', api.hydration_settings),
]
+10
View File
@@ -141,6 +141,16 @@ class FoodLogForm(forms.ModelForm):
return data
class FoodProductHydrationForm(forms.ModelForm):
class Meta:
model = FoodProduct
fields = ('is_beverage', 'hydration_enabled', 'hydration_factor')
labels = {'is_beverage': 'Count as a beverage',
'hydration_enabled': 'Include in hydration totals',
'hydration_factor': 'Fluid counting factor (0 to 1)'}
widgets = {'hydration_factor': forms.NumberInput(attrs={'min': 0, 'max': 1, 'step': '.001'})}
class InventoryItemForm(forms.ModelForm):
location_name = forms.CharField(max_length=100, label='Location', widget=forms.TextInput(attrs={'list': 'inventory-locations', 'autocomplete': 'off'}))
category_name = forms.CharField(max_length=100, required=False, label='My category', widget=forms.TextInput(attrs={'list': 'inventory-categories', 'autocomplete': 'off'}))
@@ -0,0 +1,28 @@
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('food', '0007_inventory_reversal_state')]
operations = [
migrations.AddField(model_name='foodproduct', name='is_beverage', field=models.BooleanField(default=False)),
migrations.AddField(model_name='foodproduct', name='hydration_enabled', field=models.BooleanField(default=True)),
migrations.AddField(model_name='foodproduct', name='hydration_factor', field=models.DecimalField(
decimal_places=3, default=1, max_digits=4,
validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(1)])),
migrations.AddField(model_name='foodproduct', name='hydration_source', field=models.CharField(
choices=[('manual', 'Manual'), ('product_metadata', 'Product metadata'), ('inferred', 'Inferred')],
default='inferred', max_length=16)),
migrations.AddField(model_name='foodlogentry', name='beverage_volume_ml', field=models.DecimalField(
blank=True, decimal_places=3, max_digits=10, null=True,
validators=[django.core.validators.MinValueValidator(0)])),
migrations.AddField(model_name='foodlogentry', name='hydration_amount_ml', field=models.DecimalField(
decimal_places=3, default=0, max_digits=10, validators=[django.core.validators.MinValueValidator(0)])),
migrations.AddField(model_name='foodlogentry', name='hydration_factor_snapshot', field=models.DecimalField(
decimal_places=3, default=0, max_digits=4, validators=[django.core.validators.MinValueValidator(0)])),
migrations.AddField(model_name='foodlogentry', name='hydration_kind', field=models.CharField(blank=True, max_length=24)),
migrations.AddField(model_name='foodlogentry', name='hydration_source', field=models.CharField(blank=True, max_length=16)),
]
@@ -0,0 +1,34 @@
import re
from decimal import Decimal
from django.db import migrations
PATTERNS = (
('water', r'water'), ('juice', r'juice|sap|limonade|lemonade'),
('milk', r'milk|melk|chocolademelk'),
('coffee', r'coffee|koffie|espresso|cappuccino|latte'),
('tea', r'tea|thee'), ('smoothie', r'smoothie|shake'),
('other_drink', r'soda|cola|drink|drank|bier|beer|wine|wijn'),
)
def backfill_food_drinks(apps, schema_editor):
Entry = apps.get_model('food', 'FoodLogEntry')
for entry in Entry.objects.filter(unit='ml', hydration_source='').iterator():
name = entry.product_name_snapshot.casefold()
kind = next((kind for kind, words in PATTERNS
if re.search(rf'(?<!\w)(?:{words})(?!\w)', name)), '')
if not kind:
Entry.objects.filter(pk=entry.pk).update(hydration_source='inferred')
continue
amount = Decimal(entry.amount)
Entry.objects.filter(pk=entry.pk).update(beverage_volume_ml=amount,
hydration_amount_ml=amount, hydration_factor_snapshot=Decimal('1'),
hydration_kind=kind, hydration_source='inferred')
Entry.objects.filter(hydration_source='').update(hydration_source='inferred')
class Migration(migrations.Migration):
dependencies = [('food', '0008_food_hydration'), ('planner', '0021_automatic_hydration')]
operations = [migrations.RunPython(backfill_food_drinks, migrations.RunPython.noop)]
+10 -1
View File
@@ -2,7 +2,7 @@ import uuid
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Q
from django.utils import timezone
@@ -38,6 +38,10 @@ class FoodProduct(models.Model):
package_quantity = models.CharField(max_length=100, blank=True)
package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
package_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True)
is_beverage = models.BooleanField(default=False)
hydration_enabled = models.BooleanField(default=True)
hydration_factor = models.DecimalField(max_digits=4, decimal_places=3, default=1, validators=[MinValueValidator(0), MaxValueValidator(1)])
hydration_source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('product_metadata', 'Product metadata'), ('inferred', 'Inferred')], default='inferred')
serving_size_text = models.CharField(max_length=100, blank=True)
serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True)
@@ -76,6 +80,11 @@ class FoodLogEntry(models.Model):
portion_label_snapshot = models.CharField(max_length=100, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
unit = models.CharField(max_length=2, choices=Unit.choices)
beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE)
hydration_factor_snapshot = models.DecimalField(max_digits=4, decimal_places=3, default=0, validators=NON_NEGATIVE)
hydration_kind = models.CharField(max_length=24, blank=True)
hydration_source = models.CharField(max_length=16, blank=True)
calories_kcal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
carbohydrates_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
protein_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
+97
View File
@@ -0,0 +1,97 @@
"""Snapshot a food entry's eligible drink volume when it is saved."""
import re
from decimal import Decimal, InvalidOperation
from planner.models import UserSettings
ZERO = Decimal('0')
ONE = Decimal('1')
ML = Decimal('0.001')
DRINK_WORDS = {
'water': r'water|sparkling water|mineral water',
'juice': r'juice|sap|limonade|lemonade',
'milk': r'milk|melk|chocolademelk|chocolate milk',
'coffee': r'coffee|koffie|espresso|cappuccino|latte',
'tea': r'tea|thee',
'smoothie': r'smoothie|shake',
'soup': r'soup|soep|bouillon|broth',
'other_drink': r'soda|cola|drink|drank|bier|beer|wine|wijn',
}
def beverage_kind(name, categories=''):
text = f'{name} {categories}'.casefold()
for kind, words in DRINK_WORDS.items():
if re.search(rf'(?<!\w)(?:{words})(?!\w)', text):
return kind
if re.search(r'(?<!\w)(?:beverages|drinks|boissons|dranken)(?!\w)', categories.casefold()):
return 'other_drink'
return ''
def validate_rules(rules):
if not isinstance(rules, dict) or set(rules) - set(DRINK_WORDS):
raise ValueError('Rules must use supported beverage types.')
clean = {}
for kind, rule in rules.items():
if not isinstance(rule, dict) or set(rule) - {'enabled', 'factor'}:
raise ValueError('Each beverage rule needs enabled and/or factor.')
item = {}
if 'enabled' in rule:
if not isinstance(rule['enabled'], bool):
raise ValueError('Rule enabled must be true or false.')
item['enabled'] = rule['enabled']
if 'factor' in rule:
try:
factor = Decimal(str(rule['factor']))
except (InvalidOperation, TypeError):
raise ValueError('Invalid hydration factor.') from None
if not factor.is_finite() or factor < 0 or factor > 1 or factor != factor.quantize(ML):
raise ValueError('Hydration factor must be between 0 and 1 with at most three decimals.')
item['factor'] = str(factor)
clean[kind] = item
return clean
def sync_food_hydration(entry):
"""Use saved classification on edits, so later product edits do not rewrite history."""
previous = None
if entry.pk:
previous = type(entry).objects.filter(pk=entry.pk, user=entry.user).only(
'hydration_source', 'hydration_kind', 'hydration_factor_snapshot').first()
if previous and previous.hydration_source:
kind, source, factor = (previous.hydration_kind, previous.hydration_source,
previous.hydration_factor_snapshot)
else:
product = entry.product if entry.product_id else None
name = product.product_name if product else entry.product_name_snapshot
categories = (str(product.raw_data.get('categories', '')) if product and
isinstance(product.raw_data, dict) else '')
kind = beverage_kind(name, categories)
source = 'product_metadata' if product and categories and kind else 'inferred'
if product and product.hydration_source == 'manual':
source = 'manual'
kind = kind or 'other_drink'
enabled = product.is_beverage and product.hydration_enabled
else:
enabled = bool(kind) and (product.hydration_enabled if product else True)
settings = UserSettings.objects.get_or_create(user=entry.user)[0]
if kind == 'soup' and not settings.include_liquid_foods and source != 'manual':
enabled = False
rule = settings.hydration_beverage_rules.get(kind, {})
if rule.get('enabled') is False:
enabled = False
factor = ((product.hydration_factor if product else ONE) *
Decimal(str(rule.get('factor', '1')))) if enabled else ZERO
factor = factor.quantize(ML)
if not enabled:
kind = kind if kind == 'soup' else ''
entry.hydration_kind = kind
entry.hydration_source = source
entry.hydration_factor_snapshot = factor
# Food Diary nutrition units do not imply density. Only millilitres qualify.
entry.beverage_volume_ml = entry.amount if entry.unit == 'ml' and factor > 0 else None
entry.hydration_amount_ml = (entry.beverage_volume_ml * factor).quantize(ML) if entry.beverage_volume_ml else ZERO
return entry
+1
View File
@@ -63,3 +63,4 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
@media(max-width:600px){.food-help-popover{top:auto!important;left:12px!important;right:12px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;max-height:min(70dvh,560px)}}
.inventory-product-card{display:grid;gap:.8rem}.inventory-product-heading{display:flex;align-items:center;gap:1rem;min-width:0}.inventory-product-heading img{width:68px;height:68px;object-fit:contain;background:white;border-radius:.6rem}.inventory-product-heading h2{margin:0}.inventory-product-heading p{margin:.25rem 0;overflow-wrap:anywhere}.inventory-packages summary,.inventory-use summary{cursor:pointer;min-height:44px;align-content:center;font-weight:650}.inventory-package-list{display:grid;gap:.65rem;margin:.6rem 0}.inventory-package{display:flex;align-items:center;gap:.8rem;padding:.65rem;border:1px solid var(--food-border);border-radius:.7rem;min-width:0}.inventory-package>div:last-child{min-width:0}.inventory-package p{margin:.2rem 0}.inventory-package small{color:var(--food-muted)}.inventory-package-fill{flex:none;position:relative;width:42px;height:64px;border:2px solid var(--food-muted);border-radius:.3rem;overflow:hidden;background:var(--food-progress-track)}.inventory-package-fill span{position:absolute;bottom:0;left:0;right:0;background:var(--food-green);transition:height .25s ease}.inventory-use-form{display:flex;flex-wrap:wrap;gap:.6rem;align-items:end}.inventory-use-form label{display:grid;gap:.25rem;flex:1;min-width:100px}.inventory-use-form input,.inventory-use-form select{max-width:100%;min-height:44px}.inventory-use-form button{min-height:44px}.inventory-preview{border:1px solid var(--food-border);border-radius:.7rem;padding:.8rem;margin-top:.7rem}.inventory-preview h3{margin:0}.inventory-preview form{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}.inventory-preview form button,.inventory-history button{min-height:44px}.inventory-preview [role=alert]{color:#e9aa72}.inventory-history ul{padding-left:1.2rem}.inventory-history li{margin:.4rem 0}.inventory-history li form{display:inline-block;margin-left:.5rem}@media(max-width:480px){.inventory-product-heading{align-items:flex-start}.inventory-use-form{display:grid;grid-template-columns:1fr 1fr}.inventory-use-form label:nth-child(3){grid-column:1/-1}.inventory-use-form button{grid-column:1/-1}}@media(prefers-reduced-motion:reduce){.inventory-package-fill span{transition:none}}
.food-entry-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.3rem;flex:none}.food-entry-actions a{display:inline-flex;align-items:center;min-height:44px;padding:.2rem .35rem}.food-entry-actions a:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}@media(max-width:480px){.food-entry{flex-wrap:wrap}.food-entry-actions{width:100%;justify-content:flex-start}}
@@ -14,7 +14,7 @@
{% endwith %}
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div>
</div>
<a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>
<div class="food-entry-actions"><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
</li>
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
</section>
@@ -0,0 +1,5 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Drink settings · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}">
<div class="food-form-page"><a href="{% url 'food:diary' %}">← Food diary</a><h1>Drink settings for {{ product.product_name }}</h1><p>Only Food Diary amounts logged in ml count. Existing entries keep their saved contribution.</p><form class="food-card" method="post">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save drink settings</button></form></div>
{% endblock %}
+143 -2
View File
@@ -13,9 +13,9 @@ from django.test import Client, TestCase, TransactionTestCase, override_settings
from django.db import connection
from django.utils import timezone
from planner.models import UserSettings
from planner.models import UserSettings, WaterIntakeEntry
from .api import create_token
from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
from .models import FoodLogEntry, FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
from .services.openfoodfacts import OpenFoodFactsError
@@ -87,6 +87,89 @@ class FoodApiTests(TestCase):
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '0'}).status_code, 400)
def test_drink_contribution_follows_food_entry_and_preserves_snapshot(self):
day = timezone.localdate()
tomorrow = day + timedelta(days=1)
drink = FoodProduct.objects.create(owner=self.a, product_name='Orange juice', base_unit='ml')
payload = {'meal': 'lunch', 'amount': '250', 'unit': 'ml', 'product_id': str(drink.api_id),
'date': day.isoformat()}
first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='juice-1')
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(self.call('post', '/api/v1/food/log/', payload,
HTTP_IDEMPOTENCY_KEY='juice-1').status_code, 200)
daily = lambda date: self.call('get', f'/api/v1/hydration/daily/?date={date}').json()
self.assertEqual(daily(day.isoformat())['food_ml'], '250.000')
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1)
identifier = first.json()['id']
drink.product_name = 'Orange food'
drink.hydration_factor = Decimal('.5')
drink.save()
changed = self.call('patch', f'/api/v1/food/log/{identifier}/',
{'amount': '300', 'date': tomorrow.isoformat()})
self.assertEqual(changed.status_code, 200, changed.content)
self.assertEqual(Decimal(daily(day.isoformat())['food_ml']), 0)
self.assertEqual(daily(tomorrow.isoformat())['food_ml'], '300.000')
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(Decimal(daily(tomorrow.isoformat())['food_ml']), 0)
def test_drink_units_settings_and_manual_hydration_crud(self):
drink = FoodProduct.objects.create(owner=self.a, product_name='Milk', base_unit='ml')
grams = self.call('post', '/api/v1/food/log/', {'meal': 'breakfast', 'amount': '200',
'unit': 'g', 'product_name': 'Milk'})
self.assertEqual(grams.status_code, 201, grams.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
{'auto_count_food_drinks': False}).status_code, 200)
ml = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '200',
'unit': 'ml', 'product_id': str(drink.api_id)})
self.assertEqual(ml.status_code, 201, ml.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.call('patch', '/api/v1/hydration/settings/', {'auto_count_food_drinks': True})
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['food_ml'], '200.000')
first = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
self.assertEqual(first.status_code, 201, first.content)
again = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
self.assertEqual(again.status_code, 200)
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.a).count(), 1)
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['total_ml'], '350.500')
identifier = first.json()['id']
self.assertEqual(self.call('patch', f'/api/v1/hydration/manual/{identifier}/',
{'amount_ml': '100'}).status_code, 200)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 100)
self.assertEqual(self.call('delete', f'/api/v1/hydration/manual/{identifier}/').status_code, 200)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 0)
def test_soup_setting_and_product_override_affect_new_entries_only(self):
soup = FoodProduct.objects.create(owner=self.a, product_name='Tomato soup', base_unit='ml')
payload = {'meal': 'lunch', 'amount': '200', 'unit': 'ml', 'product_id': str(soup.api_id)}
first = self.call('post', '/api/v1/food/log/', payload)
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
{'include_liquid_foods': True, 'hydration_beverage_rules': {'soup': {'factor': '0.5'}}}).status_code, 200)
second = self.call('post', '/api/v1/food/log/', payload)
self.assertEqual(second.status_code, 201, second.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 100)
self.assertEqual(self.call('get', f'/api/v1/food/log/{first.json()["id"]}/').json()['hydration_amount_ml'], '0.000')
self.client.force_login(self.a)
override = self.client.post(f'/food/product/{soup.pk}/hydration/',
{'is_beverage': 'on', 'hydration_enabled': 'on', 'hydration_factor': '1.000'})
self.assertEqual(override.status_code, 302, override.content)
soup.refresh_from_db()
self.assertEqual(soup.hydration_source, 'manual')
def test_hydration_daily_uses_user_local_manual_date(self):
UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles')
logged = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '250',
'recorded_at': '2026-01-01T01:00:00+00:00'})
self.assertEqual(logged.status_code, 201, logged.content)
previous = self.call('get', '/api/v1/hydration/daily/?date=2025-12-31').json()
next_day = self.call('get', '/api/v1/hydration/daily/?date=2026-01-01').json()
self.assertEqual(Decimal(previous['manual_ml']), 250)
self.assertEqual(Decimal(next_day['manual_ml']), 0)
def test_manual_and_inventory_crud(self):
manual = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Homemade satay', 'calories_kcal': '850'})
@@ -195,6 +278,64 @@ class FoodApiTests(TestCase):
self.assertEqual(valid.status_code, 201, valid.content)
self.assertEqual(valid.json()['remaining_amount'], '350')
def test_inventory_absolute_partial_updates_and_depletion(self):
meatballs = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
package_amount=Decimal('400'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
item = KitchenInventoryItem.objects.create(user=self.a, product=meatballs, location=location,
original_amount=Decimal('400'), remaining_amount=Decimal('400'), inventory_unit='g')
path = f'/api/v1/kitchen/items/{item.api_id}/'
first = self.call('patch', path, {'opened': True, 'remaining_amount': 280,
'notes': 'Used 120 g for dinner.'})
self.assertEqual(first.status_code, 200, first.content)
self.assertEqual(Decimal(first.json()['remaining_amount']), 280)
self.assertEqual(first.json()['notes'], 'Used 120 g for dinner.')
self.assertTrue(first.json()['opened'])
self.assertEqual(self.call('patch', path, {'remaining_amount': 280}).status_code, 200)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
second = self.call('patch', path, {'remaining_amount': 130})
self.assertEqual(second.status_code, 200, second.content)
self.assertEqual(Decimal(second.json()['remaining_amount']), 130)
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
['products'][0]['totals']['g'], '130.000')
too_much = self.call('patch', path, {'remaining_amount': 401})
self.assertEqual(too_much.status_code, 400)
self.assertEqual(too_much.json()['error']['details']['field'], 'remaining_amount')
negative = self.call('patch', path, {'remaining_amount': -1})
self.assertEqual(negative.status_code, 400)
self.assertEqual(negative.json()['error']['details']['field'], 'remaining_amount')
self.assertEqual(self.call('patch', path, {'notes': 'Still in fridge'}).json()['notes'], 'Still in fridge')
depleted = self.call('patch', path, {'opened': True, 'remaining_amount': 0,
'notes': 'Used final 130 g.'})
self.assertEqual(depleted.status_code, 200, depleted.content)
self.assertEqual(depleted.json()['status'], 'depleted')
self.assertIsNotNone(depleted.json()['archived_at'])
self.assertEqual(self.call('get', path).status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
['products'][0]['available'], False)
def test_inventory_depletes_only_one_identical_cup(self):
yoghurt = FoodProduct.objects.create(owner=self.a, product_name='Yoghurt cup',
package_amount=Decimal('175'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
cups = [KitchenInventoryItem.objects.create(user=self.a, product=yoghurt, location=location,
original_amount=Decimal('175'), remaining_amount=Decimal('175'), inventory_unit='g')
for _ in range(2)]
result = self.call('patch', f'/api/v1/kitchen/items/{cups[0].api_id}/',
{'opened': True, 'remaining_amount': 0, 'notes': 'Consumed one cup.'})
self.assertEqual(result.status_code, 200, result.content)
cups[0].refresh_from_db()
cups[1].refresh_from_db()
self.assertIsNotNone(cups[0].archived_at)
self.assertEqual(cups[1].remaining_amount, Decimal('175'))
self.assertIsNone(cups[1].archived_at)
stock = self.call('get', f'/api/v1/kitchen/stock/?product_id={yoghurt.api_id}').json()['products'][0]
self.assertEqual(stock['totals']['g'], '175.000')
self.assertEqual(len(stock['packages']), 1)
self.assertEqual(stock['packages'][0]['id'], str(cups[1].api_id))
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/',
{'remaining_amount': 0}).status_code, 404)
def test_inventory_stock_preview_consume_idempotency_undo_and_scopes(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Stock butter',
package_amount=Decimal('250'), package_unit='g')
+1
View File
@@ -29,5 +29,6 @@ urlpatterns = [
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
path('product/<int:pk>/hydration/', views.product_hydration, name='product-hydration'),
path('export/<str:period>/', views.export_csv, name='export'),
]
+19
View File
@@ -24,6 +24,7 @@ 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 planner.timezones import localdate_for_user
@@ -124,6 +125,7 @@ def _save_entry(form, user, day, product):
entry.user = user
entry.date = day
apply_product_snapshot(entry, product)
sync_food_hydration(entry)
entry.full_clean()
entry.save()
_save_custom_portion(form, user, product, entry)
@@ -135,6 +137,7 @@ def _diary_response(request, day):
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()}")
@@ -366,6 +369,7 @@ def edit_entry(request, pk):
for field, original in original_nutrients.items():
setattr(updated, field, (original * factor).quantize(Decimal('0.001')) if original is not None else None)
with transaction.atomic():
sync_food_hydration(updated)
updated.full_clean()
updated.save()
if product:
@@ -383,3 +387,18 @@ def delete_entry(request, pk):
day = entry.date
entry.delete()
return _diary_response(request, day)
@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})