94 lines
4.3 KiB
Python
94 lines
4.3 KiB
Python
"""Confirmed, idempotent recipe stock deductions built on the inventory service."""
|
|
|
|
import hashlib
|
|
import uuid
|
|
|
|
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.services.inventory_consumption import StockError, consume, undo
|
|
from recipes.models import RecipeUse, RecipeUseLine
|
|
|
|
from .analysis import AnalysisError, analyze
|
|
|
|
|
|
SALT = 'recipes.stock-use.v1'
|
|
|
|
|
|
class RecipeStockError(ValueError):
|
|
pass
|
|
|
|
|
|
def make_confirmation(analysis):
|
|
return signing.dumps({'operation_id': str(uuid.uuid4()),
|
|
'recipe_id': str(analysis['recipe'].api_id),
|
|
'servings': str(analysis['servings']),
|
|
'include_optional': analysis['include_optional'],
|
|
'substitutions': analysis['selected_substitutions'],
|
|
'fingerprint': analysis['fingerprint']}, salt=SALT)
|
|
|
|
|
|
def confirm(user, recipe, token):
|
|
try:
|
|
payload = signing.loads(token, salt=SALT, max_age=1800)
|
|
operation_id = uuid.UUID(payload['operation_id'])
|
|
except (signing.BadSignature, ValueError, KeyError, TypeError, AttributeError):
|
|
raise RecipeStockError('This preview expired or is invalid. Review the stock again.') from None
|
|
if payload.get('recipe_id') != str(recipe.api_id) or recipe.owner_id != user.pk:
|
|
raise RecipeStockError('This confirmation does not belong to this recipe.')
|
|
signature = hashlib.sha256(token.encode()).hexdigest()
|
|
with transaction.atomic():
|
|
get_user_model().objects.select_for_update().get(pk=user.pk)
|
|
previous = RecipeUse.objects.filter(pk=operation_id).first()
|
|
if previous:
|
|
if previous.user_id != user.pk or previous.request_signature != signature:
|
|
raise RecipeStockError('This confirmation was already used for another request.')
|
|
return previous, False
|
|
try:
|
|
current = analyze(recipe, user, payload['servings'],
|
|
include_optional=payload['include_optional'],
|
|
substitutions=payload['substitutions'], lock=True)
|
|
except (AnalysisError, KeyError, TypeError) as error:
|
|
raise RecipeStockError(str(error)) from None
|
|
if not current['stock_ready']:
|
|
raise RecipeStockError('Required stock is unavailable. Review the updated preview.')
|
|
if current['fingerprint'] != payload['fingerprint']:
|
|
raise RecipeStockError('The recipe or stock changed. Review the updated preview.')
|
|
operation = RecipeUse.objects.create(id=operation_id, user=user, recipe=recipe,
|
|
recipe_title_snapshot=recipe.title,
|
|
servings=current['servings'],
|
|
request_signature=signature,
|
|
plan_snapshot=current['snapshot'])
|
|
try:
|
|
for index, group in enumerate(current['groups']):
|
|
consumption = consume(
|
|
user, group['product'], group['stock_amount'], group['unit'],
|
|
source='recipe', source_reference=str(operation.id),
|
|
description=f'Recipe: {recipe.title}',
|
|
idempotency_key=f'recipe:{operation.id}:{index}',
|
|
)
|
|
RecipeUseLine.objects.create(recipe_use=operation, consumption=consumption)
|
|
except StockError as error:
|
|
raise RecipeStockError(str(error)) from None
|
|
return operation, True
|
|
|
|
|
|
def reverse_use(user, operation_id):
|
|
with transaction.atomic():
|
|
get_user_model().objects.select_for_update().get(pk=user.pk)
|
|
operation = RecipeUse.objects.select_for_update().filter(pk=operation_id, user=user).first()
|
|
if operation is None:
|
|
raise RecipeStockError('Recipe stock use not found.')
|
|
if operation.undone_at:
|
|
return operation, False
|
|
try:
|
|
for line in operation.lines.select_related('consumption').order_by('-pk'):
|
|
undo(user, line.consumption_id)
|
|
except StockError as error:
|
|
raise RecipeStockError(str(error)) from None
|
|
operation.undone_at = timezone.now()
|
|
operation.save(update_fields=('undone_at',))
|
|
return operation, True
|