129 lines
6.2 KiB
Python
129 lines
6.2 KiB
Python
"""Signed cooking completion and historical Food Diary snapshots."""
|
|
|
|
import hashlib
|
|
import uuid
|
|
from decimal import Decimal, InvalidOperation
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.core import signing
|
|
from django.db import transaction
|
|
from django.utils import timezone
|
|
|
|
from food.models import FoodLogEntry, MealType
|
|
from planner.timezones import timezone_for_user
|
|
from recipes.models import RecipeCookingRun
|
|
|
|
from .analysis import parse_servings
|
|
from .stock_use import RecipeStockError, confirm as confirm_stock, make_confirmation
|
|
|
|
|
|
SALT = 'recipes.cooking.v1'
|
|
THREE_PLACES = Decimal('0.001')
|
|
|
|
|
|
class CookingError(ValueError):
|
|
pass
|
|
|
|
|
|
def instruction_steps(markdown):
|
|
"""Treat Markdown paragraphs and list items as navigable cooking steps."""
|
|
import re
|
|
|
|
steps = []
|
|
for block in re.split(r'\n\s*\n', (markdown or '').strip()):
|
|
if not block.strip():
|
|
continue
|
|
lines = block.splitlines()
|
|
if all(re.match(r'^\s*(?:\d+[.)]|[-*+])\s+', line) for line in lines):
|
|
steps.extend(re.sub(r'^\s*(?:\d+[.)]|[-*+])\s+', '', line).strip() for line in lines)
|
|
else:
|
|
steps.append(block.strip())
|
|
return steps
|
|
|
|
|
|
def make_completion(analysis):
|
|
nutrition = {field: {'per_serving': str(row['per_serving']) if row['per_serving'] is not None else None,
|
|
'complete': row['complete']}
|
|
for field, row in analysis['nutrition'].items()}
|
|
ingredients = [{'name': line['name'], 'quantity': str(line['quantity']),
|
|
'unit': line['unit'], 'source': line['source']}
|
|
for line in analysis['lines'] if line['status'] != 'optional']
|
|
return signing.dumps({
|
|
'operation_id': str(uuid.uuid4()), 'recipe_id': str(analysis['recipe'].api_id),
|
|
'title': analysis['recipe'].title, 'prepared_servings': str(analysis['servings']),
|
|
'nutrition': nutrition, 'ingredients': ingredients,
|
|
'stock_confirmation': make_confirmation(analysis) if analysis['stock_ready'] else '',
|
|
}, salt=SALT)
|
|
|
|
|
|
def complete(user, recipe, token, *, log_food, deduct_stock, consumed_servings=None,
|
|
meal=None, day=None, time=None):
|
|
try:
|
|
payload = signing.loads(token, salt=SALT, max_age=3600)
|
|
operation_id = uuid.UUID(payload['operation_id'])
|
|
prepared = parse_servings(payload['prepared_servings'], recipe.default_servings)
|
|
except (signing.BadSignature, ValueError, KeyError, TypeError, AttributeError) as error:
|
|
raise CookingError('This cooking confirmation expired. Review the recipe again.') from error
|
|
if recipe.owner_id != user.pk or payload.get('recipe_id') != str(recipe.api_id):
|
|
raise CookingError('This cooking confirmation does not belong to this recipe.')
|
|
if not log_food and not deduct_stock:
|
|
raise CookingError('Choose at least one completion action.')
|
|
if deduct_stock and not payload.get('stock_confirmation'):
|
|
raise CookingError('Inventory is not ready. Review stock before deducting it.')
|
|
if log_food:
|
|
if meal not in MealType.values or day is None:
|
|
raise CookingError('Choose a valid meal and date.')
|
|
try:
|
|
consumed = Decimal(str(consumed_servings))
|
|
except (InvalidOperation, TypeError, ValueError):
|
|
raise CookingError('Enter a valid consumed portion.') from None
|
|
if (not consumed.is_finite() or consumed < Decimal('0.001') or consumed > prepared or
|
|
consumed != consumed.quantize(THREE_PLACES)):
|
|
raise CookingError('Consumed servings must be positive and no more than prepared servings.')
|
|
else:
|
|
consumed = None
|
|
signature = hashlib.sha256(token.encode()).hexdigest()
|
|
with transaction.atomic():
|
|
get_user_model().objects.select_for_update().get(pk=user.pk)
|
|
run = RecipeCookingRun.objects.select_for_update().filter(pk=operation_id).first()
|
|
if run:
|
|
if run.user_id != user.pk or run.request_signature != signature:
|
|
raise CookingError('This cooking confirmation was already used for another request.')
|
|
if ((log_food and not run.food_logged_at and run.stock_used_at) or
|
|
(deduct_stock and not run.stock_used_at and run.food_logged_at)):
|
|
raise CookingError('Start a new cooking completion for another action.')
|
|
if ((log_food and run.food_logged_at and run.consumed_servings != consumed) or
|
|
(deduct_stock and not run.stock_used_at and run.food_logged_at)):
|
|
raise CookingError('This confirmation was already used with different choices.')
|
|
else:
|
|
run = RecipeCookingRun.objects.create(
|
|
id=operation_id, user=user, recipe=recipe,
|
|
recipe_title_snapshot=payload['title'], prepared_servings=prepared,
|
|
request_signature=signature, nutrition_snapshot=payload['nutrition'],
|
|
ingredient_snapshot=payload['ingredients'])
|
|
if deduct_stock and not run.stock_used_at:
|
|
try:
|
|
stock_use, _ = confirm_stock(user, recipe, payload['stock_confirmation'])
|
|
except RecipeStockError as error:
|
|
raise CookingError(str(error)) from error
|
|
run.stock_use = stock_use
|
|
run.stock_used_at = timezone.now()
|
|
if log_food and not run.food_logged_at:
|
|
values = {}
|
|
for field, row in payload['nutrition'].items():
|
|
per_serving = row['per_serving']
|
|
values[field] = (Decimal(per_serving) * consumed).quantize(THREE_PLACES) if per_serving is not None else None
|
|
local_now = timezone.localtime(timezone.now(), timezone_for_user(user))
|
|
entry = FoodLogEntry(
|
|
user=user, date=day, time=time or local_now.time().replace(second=0, microsecond=0),
|
|
meal=meal, product_name_snapshot=payload['title'],
|
|
portion_label_snapshot='Recipe serving', amount=consumed,
|
|
unit='servings', source='manual', created_via='recipe', **values)
|
|
entry.full_clean()
|
|
entry.save()
|
|
run.food_entry = entry
|
|
run.consumed_servings = consumed
|
|
run.food_logged_at = timezone.now()
|
|
run.save()
|
|
return run
|