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))