Recipes phase 5
This commit is contained in:
@@ -0,0 +1,381 @@
|
||||
"""Owner-scoped HTTP recipe operations used by the MCP adapter."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.db.models import Q
|
||||
from django.http import JsonResponse
|
||||
|
||||
from food.api import (_date, _decimal, _idempotent, _json, _time, _uuid,
|
||||
api_view, error)
|
||||
from food.models import FoodProduct, MealType
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe, RecipeUse
|
||||
from .services.analysis import AnalysisError, analyze
|
||||
from .services.cooking import CookingError, complete, make_completion
|
||||
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
|
||||
from .services.variations import create_variation
|
||||
|
||||
|
||||
RECIPE_FIELDS = {'title', 'description', 'instructions_markdown', 'notes_markdown',
|
||||
'preparation_minutes', 'cooking_minutes', 'default_servings',
|
||||
'yield_amount', 'yield_unit', 'category', 'tags', 'status', 'is_favourite'}
|
||||
INGREDIENT_FIELDS = {'name', 'quantity', 'unit', 'amount_per_unit', 'amount_per_unit_unit',
|
||||
'inventory_product_id', 'nutrition_product_id', 'preparation_note',
|
||||
'is_optional', 'display_order'}
|
||||
|
||||
|
||||
def _unknown(data, allowed):
|
||||
extra = set(data) - allowed
|
||||
if extra:
|
||||
raise ValueError(f'Unknown fields: {", ".join(sorted(extra))}.')
|
||||
|
||||
|
||||
def _owned(request, identifier):
|
||||
return Recipe.objects.filter(owner=request.api_user, api_id=identifier).first()
|
||||
|
||||
|
||||
def _product(request, value):
|
||||
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(value)).first()
|
||||
if product is None:
|
||||
raise ValueError('Choose one of your own food products.')
|
||||
return product
|
||||
|
||||
|
||||
def _summary(recipe):
|
||||
return {'id': str(recipe.api_id), 'title': recipe.title, 'description': recipe.description,
|
||||
'category': recipe.category, 'tags': recipe.tags, 'status': recipe.status,
|
||||
'is_favourite': recipe.is_favourite, 'default_servings': str(recipe.default_servings),
|
||||
'total_minutes': recipe.total_minutes,
|
||||
'parent_id': str(recipe.parent.api_id) if recipe.parent_id else None,
|
||||
'updated_at': recipe.updated_at.isoformat()}
|
||||
|
||||
|
||||
def _ingredient_data(item):
|
||||
return {'id': item.pk, 'name': item.name, 'quantity': str(item.quantity), 'unit': item.unit,
|
||||
'amount_per_unit': str(item.amount_per_unit) if item.amount_per_unit is not None else None,
|
||||
'amount_per_unit_unit': item.amount_per_unit_unit or None,
|
||||
'inventory_product_id': str(item.inventory_product.api_id) if item.inventory_product_id else None,
|
||||
'nutrition_product_id': str(item.nutrition_product.api_id) if item.nutrition_product_id else None,
|
||||
'preparation_note': item.preparation_note, 'is_optional': item.is_optional,
|
||||
'display_order': item.display_order,
|
||||
'substitutions': [{'id': alternative.pk, 'name': alternative.name,
|
||||
'quantity': str(alternative.quantity), 'unit': alternative.unit,
|
||||
'product_id': str(alternative.product.api_id) if alternative.product_id else None}
|
||||
for alternative in item.substitutions.all()]}
|
||||
|
||||
|
||||
def _detail(recipe):
|
||||
data = _summary(recipe)
|
||||
data.update(instructions_markdown=recipe.instructions_markdown,
|
||||
notes_markdown=recipe.notes_markdown,
|
||||
preparation_minutes=recipe.preparation_minutes,
|
||||
cooking_minutes=recipe.cooking_minutes,
|
||||
yield_amount=str(recipe.yield_amount) if recipe.yield_amount is not None else None,
|
||||
yield_unit=recipe.yield_unit or None,
|
||||
markdown_revision=recipe.markdown_revision,
|
||||
ingredients=[_ingredient_data(item) for item in recipe.ingredients.all()],
|
||||
subrecipes=[{'id': item.pk, 'component_id': str(item.component.api_id),
|
||||
'title': item.component.title, 'quantity': str(item.quantity),
|
||||
'unit': item.unit, 'note': item.note, 'display_order': item.display_order}
|
||||
for item in recipe.subrecipes.all()],
|
||||
variations=[{'id': str(item.api_id), 'title': item.title}
|
||||
for item in recipe.variations.all()])
|
||||
return data
|
||||
|
||||
|
||||
def _set_recipe(request, recipe, data):
|
||||
_unknown(data, RECIPE_FIELDS)
|
||||
for field, value in data.items():
|
||||
if field in ('default_servings', 'yield_amount'):
|
||||
value = _decimal(value, field, positive=True) if value is not None else None
|
||||
elif field in ('preparation_minutes', 'cooking_minutes'):
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
||||
raise ValueError(f'{field} must be a non-negative integer.')
|
||||
elif field == 'is_favourite':
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError('is_favourite must be a boolean.')
|
||||
elif field == 'tags':
|
||||
if (not isinstance(value, list) or len(value) > 12 or
|
||||
any(not isinstance(tag, str) or not tag.strip() or len(tag) > 40 for tag in value)):
|
||||
raise ValueError('tags must contain up to 12 non-empty names of at most 40 characters.')
|
||||
value = list(dict.fromkeys(tag.strip() for tag in value))
|
||||
elif field == 'yield_unit' and value is None:
|
||||
value = ''
|
||||
elif not isinstance(value, str):
|
||||
raise ValueError(f'{field} must be a string.')
|
||||
setattr(recipe, field, value)
|
||||
recipe.full_clean()
|
||||
recipe.save()
|
||||
|
||||
|
||||
def _set_ingredient(request, item, data):
|
||||
_unknown(data, INGREDIENT_FIELDS)
|
||||
for field, value in data.items():
|
||||
if field in ('quantity', 'amount_per_unit'):
|
||||
value = _decimal(value, field, positive=True) if value is not None else None
|
||||
elif field in ('inventory_product_id', 'nutrition_product_id'):
|
||||
field = field.removesuffix('_id')
|
||||
value = _product(request, value) if value is not None else None
|
||||
elif field == 'is_optional':
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError('is_optional must be a boolean.')
|
||||
elif field == 'display_order':
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
||||
raise ValueError('display_order must be a non-negative integer.')
|
||||
elif not isinstance(value, str):
|
||||
raise ValueError(f'{field} must be a string.')
|
||||
setattr(item, field, value)
|
||||
item.full_clean()
|
||||
item.save()
|
||||
|
||||
|
||||
@api_view('food:read', ('GET',))
|
||||
def recipe_search(request):
|
||||
query = request.GET.get('query', '').strip()[:100]
|
||||
recipes = Recipe.objects.filter(owner=request.api_user).select_related('parent')
|
||||
if query:
|
||||
recipes = recipes.filter(Q(title__icontains=query) | Q(description__icontains=query) |
|
||||
Q(ingredients__name__icontains=query)).distinct()
|
||||
if request.GET.get('category'):
|
||||
recipes = recipes.filter(category=request.GET['category'][:80])
|
||||
try:
|
||||
limit = int(request.GET.get('limit', 20))
|
||||
except ValueError:
|
||||
return error('invalid_limit', 'limit must be an integer.')
|
||||
if not 1 <= limit <= 100:
|
||||
return error('invalid_limit', 'limit must be between 1 and 100.')
|
||||
return JsonResponse({'count': recipes.count(), 'recipes': [_summary(item) for item in recipes[:limit]]})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def recipe_create(request):
|
||||
data = _json(request)
|
||||
def action():
|
||||
if not data.get('title'):
|
||||
return error('title_required', 'Provide a recipe title.')
|
||||
recipe = Recipe(owner=request.api_user)
|
||||
try:
|
||||
_set_recipe(request, recipe, data)
|
||||
except (ValueError, ValidationError) as exc:
|
||||
return error('invalid_recipe', str(exc))
|
||||
return JsonResponse(_detail(recipe), status=201)
|
||||
return _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'},
|
||||
('GET', 'PATCH', 'DELETE'))
|
||||
def recipe_item(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
if request.method == 'GET':
|
||||
return JsonResponse(_detail(recipe))
|
||||
if request.method == 'PATCH':
|
||||
data = _json(request)
|
||||
if not data:
|
||||
return error('empty_update', 'Provide at least one field.')
|
||||
try:
|
||||
_set_recipe(request, recipe, data)
|
||||
except (ValueError, ValidationError) as exc:
|
||||
return error('invalid_recipe', str(exc))
|
||||
return JsonResponse(_detail(recipe))
|
||||
if recipe.used_in_recipes.exists():
|
||||
return error('recipe_in_use', 'Remove this recipe from its parent recipes first.', 409)
|
||||
photo = recipe.photo.name if recipe.photo else ''
|
||||
with transaction.atomic():
|
||||
recipe.delete()
|
||||
if photo:
|
||||
transaction.on_commit(lambda: recipe.photo.storage.delete(photo))
|
||||
return JsonResponse({'deleted': True, 'recipe_id': str(identifier)})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def recipe_variation(request, identifier):
|
||||
parent = _owned(request, identifier)
|
||||
if parent is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
data = _json(request)
|
||||
_unknown(data, {'title'})
|
||||
def action():
|
||||
title = data.get('title')
|
||||
if title is not None and (not isinstance(title, str) or not title.strip() or len(title) > 180):
|
||||
return error('invalid_title', 'Provide a title of at most 180 characters.')
|
||||
variation = create_variation(request.api_user, parent, title.strip() if title else None)
|
||||
return JsonResponse(_detail(variation), status=201)
|
||||
return _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def recipe_ingredient_create(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
data = _json(request)
|
||||
def action():
|
||||
item = RecipeIngredient(recipe=recipe)
|
||||
try:
|
||||
_set_ingredient(request, item, data)
|
||||
except (ValueError, ValidationError) as exc:
|
||||
return error('invalid_ingredient', str(exc))
|
||||
return JsonResponse(_ingredient_data(item), status=201)
|
||||
return _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view('food:write', ('PATCH', 'DELETE'))
|
||||
def recipe_ingredient_item(request, identifier, item_id):
|
||||
item = RecipeIngredient.objects.filter(recipe__api_id=identifier,
|
||||
recipe__owner=request.api_user, pk=item_id).first()
|
||||
if item is None:
|
||||
return error('ingredient_not_found', 'Ingredient not found.', 404)
|
||||
if request.method == 'DELETE':
|
||||
item.delete()
|
||||
return JsonResponse({'deleted': True, 'ingredient_id': item_id})
|
||||
try:
|
||||
_set_ingredient(request, item, _json(request))
|
||||
except (ValueError, ValidationError) as exc:
|
||||
return error('invalid_ingredient', str(exc))
|
||||
return JsonResponse(_ingredient_data(item))
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def recipe_subrecipe_create(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
data = _json(request)
|
||||
_unknown(data, {'component_id', 'quantity', 'unit', 'note', 'display_order'})
|
||||
component = Recipe.objects.filter(owner=request.api_user,
|
||||
api_id=_uuid(data.get('component_id'))).first()
|
||||
if component is None:
|
||||
return error('component_not_found', 'Component recipe not found.', 404)
|
||||
def action():
|
||||
item = RecipeSubrecipe(recipe=recipe, component=component,
|
||||
quantity=_decimal(data.get('quantity', '1'), 'quantity', positive=True),
|
||||
unit=data.get('unit', 'servings'), note=data.get('note', ''),
|
||||
display_order=data.get('display_order', 0))
|
||||
try:
|
||||
item.full_clean()
|
||||
item.save()
|
||||
except (ValueError, ValidationError, IntegrityError) as exc:
|
||||
return error('invalid_subrecipe', str(exc))
|
||||
return JsonResponse({'id': item.pk, 'component_id': str(component.api_id),
|
||||
'title': component.title, 'quantity': str(item.quantity), 'unit': item.unit}, status=201)
|
||||
return _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view('food:write', ('DELETE',))
|
||||
def recipe_subrecipe_delete(request, identifier, item_id):
|
||||
item = RecipeSubrecipe.objects.filter(recipe__api_id=identifier,
|
||||
recipe__owner=request.api_user, pk=item_id).first()
|
||||
if item is None:
|
||||
return error('subrecipe_not_found', 'Subrecipe link not found.', 404)
|
||||
item.delete()
|
||||
return JsonResponse({'deleted': True, 'subrecipe_id': item_id})
|
||||
|
||||
|
||||
def _analysis(request, recipe, data):
|
||||
_unknown(data, {'servings', 'include_optional', 'substitutions'})
|
||||
if not isinstance(data.get('include_optional', False), bool):
|
||||
raise ValueError('include_optional must be a boolean.')
|
||||
substitutions = data.get('substitutions', {})
|
||||
if not isinstance(substitutions, dict):
|
||||
raise ValueError('substitutions must be an object.')
|
||||
return analyze(recipe, request.api_user, data.get('servings'),
|
||||
include_optional=data.get('include_optional', False),
|
||||
substitutions=substitutions)
|
||||
|
||||
|
||||
def _analysis_data(result):
|
||||
return {'recipe_id': str(result['recipe'].api_id), 'servings': str(result['servings']),
|
||||
'stock_ready': result['stock_ready'], 'issues': result['issues'],
|
||||
'ingredients': [{'id': line['ingredient'].pk, 'name': line['name'],
|
||||
'quantity': str(line['quantity']), 'unit': line['unit'],
|
||||
'status': line['status'], 'reason': line['reason'],
|
||||
'source': line['source']} for line in result['lines']],
|
||||
'nutrition': {field: {'total': str(row['total']) if row['total'] is not None else None,
|
||||
'per_serving': str(row['per_serving']) if row['per_serving'] is not None else None,
|
||||
'complete': row['complete']}
|
||||
for field, row in result['nutrition'].items()},
|
||||
'products': [{'product_id': str(group['product'].api_id),
|
||||
'product_name': group['product'].product_name,
|
||||
'required': str(group['stock_amount']) if group.get('stock_amount') else None,
|
||||
'unit': group['unit'], 'status': group['status'],
|
||||
'available': str(group['plan']['total']) if group.get('plan') else None,
|
||||
'shortage': str(group['plan']['shortage']) if group.get('plan') else None,
|
||||
'deductions': [{'package_id': str(row['package'].api_id),
|
||||
'amount': str(row['amount']), 'unit': row['unit'],
|
||||
'before': str(row['before']), 'after': str(row['after'])}
|
||||
for row in (group.get('plan') or {}).get('deductions', [])]}
|
||||
for group in result['groups']]}
|
||||
|
||||
|
||||
@api_view('inventory:read', ('POST',))
|
||||
def recipe_stock_preview(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
try:
|
||||
result = _analysis(request, recipe, _json(request))
|
||||
except (ValueError, AnalysisError) as exc:
|
||||
return error('invalid_recipe_analysis', str(exc))
|
||||
data = _analysis_data(result)
|
||||
data['confirmation'] = make_confirmation(result) if result['stock_ready'] else None
|
||||
return JsonResponse(data)
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def recipe_stock_confirm(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
data = _json(request)
|
||||
_unknown(data, {'confirmation'})
|
||||
try:
|
||||
operation, created = confirm(request.api_user, recipe, data.get('confirmation', ''))
|
||||
except RecipeStockError as exc:
|
||||
return error('cannot_deduct_recipe', str(exc))
|
||||
return JsonResponse({'stock_use_id': str(operation.pk), 'recipe_id': str(recipe.api_id),
|
||||
'created': created, 'servings': str(operation.servings),
|
||||
'products_used': operation.lines.count()})
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def recipe_stock_undo(request, identifier):
|
||||
try:
|
||||
operation, reversed_now = reverse_use(request.api_user, identifier)
|
||||
except RecipeStockError as exc:
|
||||
return error('cannot_undo_recipe', str(exc))
|
||||
return JsonResponse({'stock_use_id': str(operation.pk), 'undone': reversed_now})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def recipe_log(request, identifier):
|
||||
recipe = _owned(request, identifier)
|
||||
if recipe is None:
|
||||
return error('recipe_not_found', 'Recipe not found.', 404)
|
||||
data = _json(request)
|
||||
_unknown(data, {'servings', 'consumed_servings', 'meal', 'date', 'time',
|
||||
'include_optional', 'substitutions'})
|
||||
if not request.headers.get('Idempotency-Key'):
|
||||
return error('idempotency_key_required', 'Provide an Idempotency-Key.')
|
||||
def action():
|
||||
try:
|
||||
result = _analysis(request, recipe, {key: data[key] for key in
|
||||
('servings', 'include_optional', 'substitutions') if key in data})
|
||||
run = complete(request.api_user, recipe, make_completion(result),
|
||||
log_food=True, deduct_stock=False,
|
||||
consumed_servings=data.get('consumed_servings'),
|
||||
meal=data.get('meal'), day=_date(data.get('date'), request.api_user),
|
||||
time=_time(data.get('time')))
|
||||
except (ValueError, AnalysisError, CookingError, ValidationError) as exc:
|
||||
return error('invalid_recipe_log', str(exc))
|
||||
entry = run.food_entry
|
||||
return JsonResponse({'entry_id': str(entry.api_id), 'recipe_id': str(recipe.api_id),
|
||||
'date': entry.date.isoformat(), 'meal': entry.meal,
|
||||
'consumed_servings': str(entry.amount),
|
||||
'nutrition': {field: str(getattr(entry, field)) if getattr(entry, field) is not None else None
|
||||
for field in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g')},
|
||||
'nutrition_complete': {field: row['complete'] for field, row in run.nutrition_snapshot.items()},
|
||||
'stock_deducted': False}, status=201)
|
||||
return _idempotent(request, data, action)
|
||||
Reference in New Issue
Block a user