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)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Create an independent variation from one owned recipe."""
|
||||
|
||||
from django.db import transaction
|
||||
|
||||
from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution,
|
||||
RecipeSubrecipe)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def create_variation(user, parent, title=None):
|
||||
if parent.owner_id != user.pk:
|
||||
raise ValueError('Recipe not found.')
|
||||
variation = Recipe.objects.create(
|
||||
owner=user, parent=parent, title=title or f'{parent.title[:160]} variation',
|
||||
description=parent.description, instructions_markdown=parent.instructions_markdown,
|
||||
notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes,
|
||||
cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings,
|
||||
yield_amount=parent.yield_amount, yield_unit=parent.yield_unit,
|
||||
category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT)
|
||||
for item in parent.ingredients.select_related('inventory_product', 'nutrition_product').prefetch_related('substitutions'):
|
||||
copied = RecipeIngredient.objects.create(
|
||||
recipe=variation, name=item.name, quantity=item.quantity, unit=item.unit,
|
||||
amount_per_unit=item.amount_per_unit, amount_per_unit_unit=item.amount_per_unit_unit,
|
||||
display_order=item.display_order, inventory_product=item.inventory_product,
|
||||
nutrition_product=item.nutrition_product, preparation_note=item.preparation_note,
|
||||
is_optional=item.is_optional)
|
||||
RecipeIngredientSubstitution.objects.bulk_create([
|
||||
RecipeIngredientSubstitution(
|
||||
ingredient=copied, name=alternative.name, quantity=alternative.quantity,
|
||||
unit=alternative.unit, amount_per_unit=alternative.amount_per_unit,
|
||||
amount_per_unit_unit=alternative.amount_per_unit_unit,
|
||||
product=alternative.product, display_order=alternative.display_order)
|
||||
for alternative in item.substitutions.all()])
|
||||
RecipeSubrecipe.objects.bulk_create([
|
||||
RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order, note=item.note)
|
||||
for item in parent.subrecipes.all()])
|
||||
return variation
|
||||
@@ -0,0 +1,168 @@
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
|
||||
from food.api import create_token
|
||||
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
|
||||
from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution,
|
||||
RecipeSubrecipe, RecipeUse)
|
||||
|
||||
|
||||
class RecipeApiTests(TestCase):
|
||||
def setUp(self):
|
||||
users = get_user_model()
|
||||
self.user = users.objects.create_user('recipe-api-owner')
|
||||
self.other = users.objects.create_user('recipe-api-other')
|
||||
_, self.secret = create_token(self.user, 'Recipe API',
|
||||
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
|
||||
_, self.food_read = create_token(self.user, 'Recipe read', ['food:read'])
|
||||
_, self.stock_read = create_token(self.user, 'Stock read', ['inventory:read'])
|
||||
self.product = FoodProduct.objects.create(owner=self.user, product_name='Oats',
|
||||
energy_kcal_100=Decimal('400'), protein_100=Decimal('10'),
|
||||
carbohydrates_100=Decimal('60'), fat_100=Decimal('5'), fibre_100=Decimal('8'))
|
||||
self.other_product = FoodProduct.objects.create(owner=self.other, product_name='Private oats')
|
||||
self.other_recipe = Recipe.objects.create(owner=self.other, title='Private recipe')
|
||||
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
|
||||
self.package = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
|
||||
location=location, original_amount=Decimal('300'),
|
||||
remaining_amount=Decimal('300'), inventory_unit='g')
|
||||
|
||||
def call(self, method, path, data=None, token=None, key=None):
|
||||
headers = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}'}
|
||||
if key:
|
||||
headers['HTTP_IDEMPOTENCY_KEY'] = key
|
||||
if data is not None:
|
||||
headers['content_type'] = 'application/json'
|
||||
data = json.dumps(data)
|
||||
return getattr(self.client, method)(f'/api/v1/{path}', data=data, **headers)
|
||||
|
||||
def create(self):
|
||||
response = self.call('post', 'recipes/create/',
|
||||
{'title': 'Oat bowl', 'default_servings': '2',
|
||||
'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl')
|
||||
self.assertEqual(response.status_code, 201, response.content)
|
||||
return response.json()['id']
|
||||
|
||||
def test_recipe_crud_variation_and_scopes(self):
|
||||
recipe_id = self.create()
|
||||
repeat = self.call('post', 'recipes/create/',
|
||||
{'title': 'Oat bowl', 'default_servings': '2',
|
||||
'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl')
|
||||
self.assertEqual(repeat.status_code, 200)
|
||||
self.assertEqual(repeat.json()['id'], recipe_id)
|
||||
self.assertEqual(self.call('post', 'recipes/create/',
|
||||
{'title': 'Other'}, key='create-oat-bowl').status_code, 409)
|
||||
self.assertEqual(self.call('get', 'recipes/?query=Oat').json()['count'], 1)
|
||||
self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['title'], 'Oat bowl')
|
||||
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/',
|
||||
{'title': 'Updated bowl', 'instructions_markdown': 'Toast oats.'}).json()['title'], 'Updated bowl')
|
||||
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/',
|
||||
{'title': 'No write'}, token=self.food_read).status_code, 403)
|
||||
self.assertEqual(self.call('get', f'recipes/{recipe_id}/', token=self.stock_read).status_code, 403)
|
||||
self.assertEqual(self.call('get', f'recipes/{self.other_recipe.api_id}/').status_code, 404)
|
||||
self.assertEqual(self.call('patch', f'recipes/{self.other_recipe.api_id}/',
|
||||
{'title': 'Stolen'}).status_code, 404)
|
||||
variation = self.call('post', f'recipes/{recipe_id}/variations/',
|
||||
{'title': 'Spicy bowl'}, key='variation-1')
|
||||
self.assertEqual(variation.status_code, 201, variation.content)
|
||||
variation_id = variation.json()['id']
|
||||
self.assertEqual(variation.json()['parent_id'], recipe_id)
|
||||
self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['variations'][0]['id'], variation_id)
|
||||
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/').status_code, 200)
|
||||
self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['parent_id'], None)
|
||||
|
||||
def test_ingredients_subrecipes_ownership_cycle_and_independent_variation(self):
|
||||
recipe_id = self.create()
|
||||
ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g',
|
||||
'inventory_product_id': str(self.product.api_id),
|
||||
'nutrition_product_id': str(self.product.api_id)}
|
||||
created = self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient, key='oats-ingredient')
|
||||
self.assertEqual(created.status_code, 201, created.content)
|
||||
item_id = created.json()['id']
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient,
|
||||
key='oats-ingredient').json()['id'], item_id)
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/',
|
||||
{**ingredient, 'inventory_product_id': str(self.other_product.api_id)}).status_code, 400)
|
||||
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/',
|
||||
{'quantity': '150'}).json()['quantity'], '150')
|
||||
RecipeIngredientSubstitution.objects.create(
|
||||
ingredient=RecipeIngredient.objects.get(pk=item_id), name='Buckwheat',
|
||||
quantity=Decimal('150'), unit='g', product=self.product)
|
||||
variation = self.call('post', f'recipes/{recipe_id}/variations/', {}, key='var-with-oats').json()
|
||||
variation_id = variation['id']
|
||||
self.assertEqual(variation['ingredients'][0]['quantity'], '150.000')
|
||||
self.assertEqual(variation['ingredients'][0]['substitutions'][0]['name'], 'Buckwheat')
|
||||
self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/', {'quantity': '100'})
|
||||
self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['ingredients'][0]['quantity'], '150.000')
|
||||
component = self.call('post', 'recipes/create/', {'title': 'Topping'}, key='topping').json()['id']
|
||||
link = self.call('post', f'recipes/{recipe_id}/subrecipes/',
|
||||
{'component_id': component, 'quantity': '1', 'unit': 'servings'}, key='link-topping')
|
||||
self.assertEqual(link.status_code, 201, link.content)
|
||||
self.assertEqual(self.call('post', f'recipes/{component}/subrecipes/',
|
||||
{'component_id': recipe_id}).status_code, 400)
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/subrecipes/',
|
||||
{'component_id': str(self.other_recipe.api_id)}).status_code, 404)
|
||||
self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 409)
|
||||
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/subrecipes/{link.json()["id"]}/').status_code, 200)
|
||||
self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 200)
|
||||
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/ingredients/{item_id}/').status_code, 200)
|
||||
|
||||
def test_inventory_preview_confirm_replay_undo_and_recipe_log_snapshot(self):
|
||||
recipe_id = self.create()
|
||||
ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g',
|
||||
'inventory_product_id': str(self.product.api_id),
|
||||
'nutrition_product_id': str(self.product.api_id)}
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient).status_code, 201)
|
||||
preview = self.call('post', f'recipes/{recipe_id}/stock/preview/',
|
||||
{'servings': '2'}, token=self.stock_read)
|
||||
self.assertEqual(preview.status_code, 200, preview.content)
|
||||
self.assertTrue(preview.json()['stock_ready'])
|
||||
self.assertEqual(preview.json()['products'][0]['deductions'][0]['amount'], '200.000')
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
||||
{'confirmation': preview.json()['confirmation']}, token=self.stock_read).status_code, 403)
|
||||
confirmation = {'confirmation': preview.json()['confirmation']}
|
||||
confirmed = self.call('post', f'recipes/{recipe_id}/stock/confirm/', confirmation)
|
||||
self.assertEqual(confirmed.status_code, 200, confirmed.content)
|
||||
self.assertTrue(confirmed.json()['created'])
|
||||
self.assertFalse(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
||||
confirmation).json()['created'])
|
||||
self.package.refresh_from_db()
|
||||
self.assertEqual(self.package.remaining_amount, Decimal('100'))
|
||||
self.assertEqual(RecipeUse.objects.count(), 1)
|
||||
logged = self.call('post', f'recipes/{recipe_id}/log/',
|
||||
{'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner',
|
||||
'date': '2026-10-12'}, key='recipe-meal-1')
|
||||
self.assertEqual(logged.status_code, 201, logged.content)
|
||||
self.assertEqual(logged.json()['nutrition']['calories_kcal'], '200.000')
|
||||
self.assertFalse(logged.json()['stock_deducted'])
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/',
|
||||
{'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner',
|
||||
'date': '2026-10-12'}, key='recipe-meal-1').status_code, 200)
|
||||
self.assertEqual(FoodLogEntry.objects.count(), 1)
|
||||
self.call('patch', f'recipes/{recipe_id}/', {'title': 'Edited bowl'})
|
||||
entry = FoodLogEntry.objects.get()
|
||||
self.assertEqual((entry.product_name_snapshot, entry.calories_kcal),
|
||||
('Oat bowl', Decimal('200')))
|
||||
self.assertEqual(self.call('post', f'recipes/stock-use/{confirmed.json()["stock_use_id"]}/undo/',
|
||||
{}).status_code, 200)
|
||||
self.package.refresh_from_db()
|
||||
self.assertEqual(self.package.remaining_amount, Decimal('300'))
|
||||
self.assertEqual(FoodLogEntry.objects.count(), 1)
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
||||
{'confirmation': 'invalid'}).status_code, 400)
|
||||
|
||||
def test_missing_stock_blocks_confirmation_but_not_meal(self):
|
||||
recipe_id = self.create()
|
||||
self.call('post', f'recipes/{recipe_id}/ingredients/',
|
||||
{'name': 'Oats', 'quantity': '400', 'unit': 'g',
|
||||
'nutrition_product_id': str(self.product.api_id),
|
||||
'inventory_product_id': str(self.product.api_id)})
|
||||
preview = self.call('post', f'recipes/{recipe_id}/stock/preview/', {}).json()
|
||||
self.assertFalse(preview['stock_ready'])
|
||||
self.assertIsNone(preview['confirmation'])
|
||||
self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/',
|
||||
{'consumed_servings': '1', 'meal': 'lunch'}, key='meal-with-shortage').status_code, 201)
|
||||
self.package.refresh_from_db()
|
||||
self.assertEqual(self.package.remaining_amount, Decimal('300'))
|
||||
+2
-24
@@ -20,6 +20,7 @@ from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, Reci
|
||||
from .services.analysis import AnalysisError, analyze
|
||||
from .services.cooking import CookingError, complete, instruction_steps, make_completion
|
||||
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
|
||||
from .services.variations import create_variation as clone_variation
|
||||
|
||||
|
||||
def _owned(user):
|
||||
@@ -363,30 +364,7 @@ def autosave_new(request):
|
||||
def create_variation(request, identifier):
|
||||
parent = get_object_or_404(_owned(request.user).prefetch_related('ingredients', 'subrecipes'),
|
||||
api_id=identifier)
|
||||
with transaction.atomic():
|
||||
variation = Recipe.objects.create(
|
||||
owner=request.user, parent=parent, title=f'{parent.title[:160]} variation',
|
||||
description=parent.description, instructions_markdown=parent.instructions_markdown,
|
||||
notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes,
|
||||
cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings,
|
||||
yield_amount=parent.yield_amount, yield_unit=parent.yield_unit,
|
||||
category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT,
|
||||
)
|
||||
RecipeIngredient.objects.bulk_create([
|
||||
RecipeIngredient(recipe=variation, name=item.name, quantity=item.quantity,
|
||||
unit=item.unit, amount_per_unit=item.amount_per_unit,
|
||||
amount_per_unit_unit=item.amount_per_unit_unit,
|
||||
display_order=item.display_order,
|
||||
inventory_product=item.inventory_product,
|
||||
nutrition_product=item.nutrition_product,
|
||||
preparation_note=item.preparation_note, is_optional=item.is_optional)
|
||||
for item in parent.ingredients.all()
|
||||
])
|
||||
RecipeSubrecipe.objects.bulk_create([
|
||||
RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order, note=item.note)
|
||||
for item in parent.subrecipes.all()
|
||||
])
|
||||
variation = clone_variation(request.user, parent)
|
||||
messages.success(request, 'Variation created. Edit it to make it your own.')
|
||||
return redirect('recipes:edit', identifier=variation.api_id)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user