diff --git a/main/recipes/forms.py b/main/recipes/forms.py index e4d7c0b..76ab2b0 100644 --- a/main/recipes/forms.py +++ b/main/recipes/forms.py @@ -4,7 +4,7 @@ from django.core.files.uploadedfile import UploadedFile from PIL import Image, UnidentifiedImageError from food.models import FoodProduct -from .models import Recipe, RecipeIngredient, RecipeSubrecipe +from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe class RecipeForm(forms.ModelForm): @@ -16,11 +16,13 @@ class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ('title', 'description', 'category', 'preparation_minutes', - 'cooking_minutes', 'default_servings', 'status', 'parent', + 'cooking_minutes', 'default_servings', 'yield_amount', 'yield_unit', 'status', 'parent', 'instructions_markdown', 'notes_markdown', 'photo') labels = {'instructions_markdown': 'Instructions (Markdown)', 'notes_markdown': 'Personal notes (Markdown)', - 'default_servings': 'Servings', 'parent': 'Variation of'} + 'default_servings': 'Servings', 'parent': 'Variation of', + 'yield_amount': 'Recipe yield amount', 'yield_unit': 'Yield unit'} + help_texts = {'yield_amount': 'Optional: total cooked weight or volume for using this recipe as a subrecipe.'} widgets = { 'description': forms.Textarea(attrs={'rows': 3}), 'instructions_markdown': forms.Textarea(attrs={'rows': 10}), @@ -74,9 +76,11 @@ class RecipeForm(forms.ModelForm): class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient - fields = ('name', 'quantity', 'unit', 'preparation_note', 'is_optional', + fields = ('name', 'quantity', 'unit', 'amount_per_unit', 'amount_per_unit_unit', + 'preparation_note', 'is_optional', 'inventory_product', 'nutrition_product', 'display_order') widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), + 'amount_per_unit': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'display_order': forms.NumberInput(attrs={'min': 0})} @@ -120,3 +124,16 @@ RecipeSubrecipeFormSet = inlineformset_factory( Recipe, RecipeSubrecipe, form=RecipeSubrecipeForm, formset=OwnedSubrecipeFormSet, fk_name='recipe', extra=1, can_delete=True, ) + + +class RecipeSubstitutionForm(forms.ModelForm): + class Meta: + model = RecipeIngredientSubstitution + fields = ('name', 'quantity', 'unit', 'product', 'amount_per_unit', + 'amount_per_unit_unit', 'display_order') + widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), + 'amount_per_unit': forms.NumberInput(attrs={'min': '.001', 'step': '.001'})} + + def __init__(self, *args, user, **kwargs): + super().__init__(*args, **kwargs) + self.fields['product'].queryset = FoodProduct.objects.filter(owner=user).order_by('product_name') diff --git a/main/recipes/migrations/0003_recipe_yield_amount_recipe_yield_unit_and_more.py b/main/recipes/migrations/0003_recipe_yield_amount_recipe_yield_unit_and_more.py new file mode 100644 index 0000000..d3ba797 --- /dev/null +++ b/main/recipes/migrations/0003_recipe_yield_amount_recipe_yield_unit_and_more.py @@ -0,0 +1,75 @@ +# Generated by Django 6.1.1 on 2026-10-11 23:56 + +import django.core.validators +import django.db.models.deletion +import uuid +from decimal import Decimal +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0009_backfill_food_hydration'), + ('recipes', '0002_recipe_markdown_revision'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='recipe', + name='yield_amount', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]), + ), + migrations.AddField( + model_name='recipe', + name='yield_unit', + field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2), + ), + migrations.AddField( + model_name='recipeingredient', + name='amount_per_unit', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]), + ), + migrations.AddField( + model_name='recipeingredient', + name='amount_per_unit_unit', + field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2), + ), + migrations.AddField( + model_name='recipeingredientsubstitution', + name='amount_per_unit', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]), + ), + migrations.AddField( + model_name='recipeingredientsubstitution', + name='amount_per_unit_unit', + field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2), + ), + migrations.CreateModel( + name='RecipeUse', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('recipe_title_snapshot', models.CharField(max_length=180)), + ('servings', models.DecimalField(decimal_places=2, max_digits=7)), + ('request_signature', models.CharField(max_length=64)), + ('plan_snapshot', models.JSONField(default=dict)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('undone_at', models.DateTimeField(blank=True, null=True)), + ('recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_uses', to='recipes.recipe')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ('-created_at',), + }, + ), + migrations.CreateModel( + name='RecipeUseLine', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('consumption', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='recipe_use_line', to='food.inventoryconsumption')), + ('recipe_use', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='recipes.recipeuse')), + ], + ), + ] diff --git a/main/recipes/models.py b/main/recipes/models.py index 18a799a..ce750ea 100644 --- a/main/recipes/models.py +++ b/main/recipes/models.py @@ -28,6 +28,9 @@ class Recipe(models.Model): cooking_minutes = models.PositiveIntegerField(default=0) default_servings = models.DecimalField(max_digits=7, decimal_places=2, default=2, validators=[MinValueValidator(Decimal('0.01'))]) + yield_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, + validators=[MinValueValidator(Decimal('0.001'))]) + yield_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True) category = models.CharField(max_length=80, blank=True) tags = models.JSONField(default=list, blank=True) is_favourite = models.BooleanField(default=False) @@ -50,6 +53,8 @@ class Recipe(models.Model): def clean(self): super().clean() + if bool(self.yield_amount) != bool(self.yield_unit): + raise ValidationError({'yield_amount': 'Provide both an amount and a unit for recipe yield.'}) if not isinstance(self.tags, list) or any(not isinstance(tag, str) for tag in self.tags): raise ValidationError({'tags': 'Tags must be a list of names.'}) if self.parent_id: @@ -87,6 +92,9 @@ class RecipeIngredient(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=3, validators=[MinValueValidator(Decimal('0.001'))]) unit = models.CharField(max_length=10, choices=Unit.choices) + amount_per_unit = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, + validators=[MinValueValidator(Decimal('0.001'))]) + amount_per_unit_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True) display_order = models.PositiveIntegerField(default=0) inventory_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True, related_name='recipe_inventory_ingredients') @@ -102,6 +110,10 @@ class RecipeIngredient(models.Model): def clean(self): super().clean() + if bool(self.amount_per_unit) != bool(self.amount_per_unit_unit): + raise ValidationError({'amount_per_unit': 'Provide both an amount and unit for one piece or measure.'}) + if self.amount_per_unit and self.unit not in ('pieces', 'portions', 'tsp', 'tbsp'): + raise ValidationError({'amount_per_unit': 'Only count or measure units need this conversion.'}) if self.recipe_id: for field in ('inventory_product', 'nutrition_product'): product = getattr(self, field) @@ -156,6 +168,9 @@ class RecipeIngredientSubstitution(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=3, validators=[MinValueValidator(Decimal('0.001'))]) unit = models.CharField(max_length=10, choices=RecipeIngredient.Unit.choices) + amount_per_unit = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, + validators=[MinValueValidator(Decimal('0.001'))]) + amount_per_unit_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True) product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True, related_name='recipe_substitutions') display_order = models.PositiveIntegerField(default=0) @@ -165,5 +180,32 @@ class RecipeIngredientSubstitution(models.Model): def clean(self): super().clean() + if bool(self.amount_per_unit) != bool(self.amount_per_unit_unit): + raise ValidationError({'amount_per_unit': 'Provide both an amount and unit for one piece or measure.'}) + if self.amount_per_unit and self.unit not in ('pieces', 'portions', 'tsp', 'tbsp'): + raise ValidationError({'amount_per_unit': 'Only count or measure units need this conversion.'}) if self.product_id and self.ingredient_id and self.product.owner_id != self.ingredient.recipe.owner_id: raise ValidationError({'product': 'Choose one of your own food products.'}) + + +class RecipeUse(models.Model): + """One confirmed, reversible multi-product stock operation.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + recipe = models.ForeignKey(Recipe, on_delete=models.SET_NULL, null=True, related_name='stock_uses') + recipe_title_snapshot = models.CharField(max_length=180) + servings = models.DecimalField(max_digits=7, decimal_places=2) + request_signature = models.CharField(max_length=64) + plan_snapshot = models.JSONField(default=dict) + created_at = models.DateTimeField(auto_now_add=True) + undone_at = models.DateTimeField(null=True, blank=True) + + class Meta: + ordering = ('-created_at',) + + +class RecipeUseLine(models.Model): + recipe_use = models.ForeignKey(RecipeUse, on_delete=models.CASCADE, related_name='lines') + consumption = models.OneToOneField('food.InventoryConsumption', on_delete=models.PROTECT, + related_name='recipe_use_line') diff --git a/main/recipes/services/__init__.py b/main/recipes/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/recipes/services/analysis.py b/main/recipes/services/analysis.py new file mode 100644 index 0000000..129c04d --- /dev/null +++ b/main/recipes/services/analysis.py @@ -0,0 +1,223 @@ +"""Exact recipe scaling, conservative product matching, nutrition and stock preview.""" + +import hashlib +import json +from decimal import Decimal, InvalidOperation, ROUND_HALF_UP + +from food.models import FoodProduct +from food.services.inventory_consumption import StockError, preview +from food.services.logging import NUTRIENTS + + +THREE_PLACES = Decimal('0.001') +NUTRIENT_FIELDS = NUTRIENTS[:5] +UNITS = {'g': ('mass', Decimal(1), 'g'), 'kg': ('mass', Decimal(1000), 'g'), + 'ml': ('volume', Decimal(1), 'ml'), 'L': ('volume', Decimal(1000), 'ml'), + 'pieces': ('pieces', Decimal(1), 'pieces'), + 'portions': ('portions', Decimal(1), 'portions')} + + +class AnalysisError(ValueError): + pass + + +def parse_servings(value, default): + try: + servings = Decimal(str(default if value in (None, '') else value)) + except (InvalidOperation, TypeError, ValueError): + raise AnalysisError('Enter a valid number of servings.') from None + if (not servings.is_finite() or servings < Decimal('.01') or + servings > Decimal('99999.99') or servings != servings.quantize(Decimal('.01'))): + raise AnalysisError('Servings must be between 0.01 and 99,999.99 with at most two decimal places.') + return servings + + +def physical_amount(quantity, unit, amount_per_unit=None, amount_per_unit_unit=''): + """Return an exact amount in a compatible base unit; never guess density.""" + if amount_per_unit is not None and unit in ('pieces', 'portions', 'tsp', 'tbsp'): + return quantity * amount_per_unit, amount_per_unit_unit + if unit in UNITS: + _, factor, base_unit = UNITS[unit] + return quantity * factor, base_unit + return None, None + + +def _stock_quantity(value, unit): + rounded = value.quantize(THREE_PLACES, rounding=ROUND_HALF_UP) + if rounded <= 0: + raise AnalysisError('The scaled stock amount is smaller than 0.001.') + if unit in ('pieces', 'portions') and rounded != rounded.to_integral_value(): + raise AnalysisError('A fractional count cannot be deducted from stock.') + return rounded + + +def analyze(recipe, user, servings, *, include_optional=False, substitutions=None, lock=False): + servings = parse_servings(servings, recipe.default_servings) + if recipe.owner_id != user.pk: + raise AnalysisError('Recipe not found.') + selected = {str(key): str(value) for key, value in (substitutions or {}).items() if value} + used_selections = set() + products = list(FoodProduct.objects.filter(owner=user)) + unique_names = {} + for product in products: + key = product.product_name.strip().casefold() + unique_names.setdefault(key, []).append(product) + + def match(name): + candidates = unique_names.get(name.strip().casefold(), []) + return candidates[0] if len(candidates) == 1 else None + + lines, groups, issues = [], {}, [] + totals = {target: Decimal(0) for _, target in NUTRIENT_FIELDS} + known = {target: False for _, target in NUTRIENT_FIELDS} + complete = {target: True for _, target in NUTRIENT_FIELDS} + stock_issue = False + + def add_ingredient(ingredient, scale, source): + nonlocal stock_issue + substitution_options = list(ingredient.substitutions.all()) + selected_id = selected.get(str(ingredient.pk)) + alternative = None + if selected_id: + used_selections.add(str(ingredient.pk)) + alternative = next((item for item in substitution_options if str(item.pk) == selected_id), None) + if alternative is None: + raise AnalysisError('Choose a substitution belonging to this ingredient.') + chosen = alternative or ingredient + name = chosen.name + quantity = chosen.quantity * scale + unit = chosen.unit + item = {'ingredient': ingredient, 'name': name, 'quantity': quantity, 'unit': unit, + 'source': source, 'optional': ingredient.is_optional, + 'substitutions': substitution_options, 'selected_substitution': selected_id or '', + 'status': 'unknown', 'reason': '', 'product': None, 'stock_percent': 0} + lines.append(item) + if ingredient.is_optional and not include_optional: + item['status'] = 'optional' + item['reason'] = 'Excluded from this estimate.' + return + auto = match(name) + if alternative: + inventory_product = alternative.product or auto + nutrition_product = alternative.product or auto + else: + inventory_product = ingredient.inventory_product or ingredient.nutrition_product or auto + nutrition_product = ingredient.nutrition_product or ingredient.inventory_product or auto + amount, base_unit = physical_amount(quantity, unit, chosen.amount_per_unit, + chosen.amount_per_unit_unit) + if amount is None: + item['reason'] = 'Add an explicit amount per measure in the recipe editor.' + issues.append(f'{name}: {item["reason"]}') + stock_issue = True + elif not inventory_product or inventory_product.owner_id != user.pk: + item['reason'] = 'No unambiguous inventory product match.' + issues.append(f'{name}: {item["reason"]}') + stock_issue = True + else: + item['product'] = inventory_product + key = (inventory_product.pk, base_unit) + group = groups.setdefault(key, {'product': inventory_product, 'unit': base_unit, + 'amount': Decimal(0), 'lines': []}) + group['amount'] += amount + group['lines'].append(item) + for source_field, target_field in NUTRIENT_FIELDS: + value = getattr(nutrition_product, source_field) if nutrition_product else None + if (amount is None or not nutrition_product or nutrition_product.owner_id != user.pk or + base_unit != nutrition_product.base_unit or value is None): + complete[target_field] = False + else: + totals[target_field] += value * amount / Decimal(100) + known[target_field] = True + + def walk(current, scale, ancestors): + nonlocal stock_issue + if current.pk in ancestors: + issues.append('Circular subrecipe reference detected.') + stock_issue = True + for target in complete: + complete[target] = False + return + ancestors = ancestors | {current.pk} + for ingredient in current.ingredients.select_related('inventory_product', 'nutrition_product').prefetch_related('substitutions__product'): + add_ingredient(ingredient, scale, '' if current.pk == recipe.pk else current.title) + for relation in current.subrecipes.select_related('component'): + component = relation.component + if component.owner_id != user.pk: + issues.append(f'{component.title}: subrecipe is not owned by you.') + stock_issue = True + for target in complete: + complete[target] = False + continue + if relation.unit == 'servings': + component_scale = relation.quantity * scale / component.default_servings + elif component.yield_amount and component.yield_unit == relation.unit: + component_scale = relation.quantity * scale / component.yield_amount + else: + issues.append(f'{component.title}: set a matching recipe yield to use {relation.unit}.') + stock_issue = True + for target in complete: + complete[target] = False + continue + walk(component, component_scale, ancestors) + + walk(recipe, servings / recipe.default_servings, set()) + if set(selected) - used_selections: + raise AnalysisError('A selected substitution is not part of this recipe.') + for group in groups.values(): + try: + group['stock_amount'] = _stock_quantity(group['amount'], group['unit']) + group['plan'] = preview(user, group['product'], group['stock_amount'], group['unit'], lock=lock) + for deduction in group['plan']['deductions']: + capacity = deduction['package'].original_amount or deduction['before'] + deduction['before_percent'] = min(100, int(deduction['before'] * 100 / capacity)) + deduction['after_percent'] = min(100, int(deduction['after'] * 100 / capacity)) + available = group['plan']['total'] + shortage = group['plan']['shortage'] + group['status'] = ('available' if shortage == 0 else 'partial' if available else 'missing') + group['percent'] = min(100, int(available * 100 / group['stock_amount'])) + except (StockError, AnalysisError) as error: + group['status'] = 'unknown' + group['plan'] = None + group['percent'] = 0 + issues.append(f'{group["product"].product_name}: {error}') + stock_issue = True + for line in group['lines']: + line['status'] = group['status'] + line['stock_percent'] = group['percent'] + if group['status'] == 'partial': + line['reason'] = 'Some stock is missing.' + elif group['status'] == 'missing': + line['reason'] = 'No compatible stock in inventory.' + + nutrition = {target: {'total': totals[target] if known[target] else None, + 'per_serving': totals[target] / servings if known[target] else None, + 'complete': complete[target] and known[target]} + for _, target in NUTRIENT_FIELDS} + nutrition_rows = [ + {'label': label, 'unit': unit, **nutrition[target]} + for target, label, unit in (('calories_kcal', 'Calories', 'kcal'), + ('carbohydrates_g', 'Carbohydrates', 'g'), + ('protein_g', 'Protein', 'g'), + ('fat_g', 'Fat', 'g'), ('fibre_g', 'Fibre', 'g')) + ] + stock_ready = bool(groups) and not stock_issue and all(group['status'] == 'available' + for group in groups.values()) + snapshot = {'recipe_id': str(recipe.api_id), 'servings': str(servings), + 'include_optional': include_optional, 'substitutions': selected, + 'ingredients': [{'id': line['ingredient'].pk, 'name': line['name'], + 'quantity': str(line['quantity']), 'unit': line['unit'], + 'product_id': line['product'].pk if line['product'] else None, + 'status': line['status']} for line in lines], + 'groups': [{'product_id': group['product'].pk, 'amount': str(group['amount']), + 'stock_amount': str(group.get('stock_amount', '')), + 'unit': group['unit'], + 'deductions': [{'package_id': str(d['package'].api_id), + 'before': str(d['before']), 'after': str(d['after'])} + for d in (group['plan'] or {}).get('deductions', [])]} + for group in groups.values()]} + fingerprint = hashlib.sha256(json.dumps(snapshot, sort_keys=True).encode()).hexdigest() + return {'recipe': recipe, 'servings': servings, 'include_optional': include_optional, + 'selected_substitutions': selected, 'lines': lines, 'groups': list(groups.values()), + 'nutrition': nutrition, 'nutrition_rows': nutrition_rows, + 'issues': issues, 'stock_ready': stock_ready, + 'fingerprint': fingerprint, 'snapshot': snapshot} diff --git a/main/recipes/services/stock_use.py b/main/recipes/services/stock_use.py new file mode 100644 index 0000000..e9734d7 --- /dev/null +++ b/main/recipes/services/stock_use.py @@ -0,0 +1,93 @@ +"""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 diff --git a/main/recipes/static/recipes/recipes.css b/main/recipes/static/recipes/recipes.css index 64928e2..2a1aded 100644 --- a/main/recipes/static/recipes/recipes.css +++ b/main/recipes/static/recipes/recipes.css @@ -17,3 +17,6 @@ body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#43 body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-main{border-color:var(--recipe-line);background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-ww-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-preview{background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .ProseMirror,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container .CodeMirror{color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents *{color:inherit}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-toolbar-icons{filter:invert(.85)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar button:hover{background:#405347}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item{color:var(--recipe-muted)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item.active{background:var(--recipe-surface);color:var(--recipe-ink)} @media(max-width:767px){.recipes-markdown-editor .toastui-editor-defaultUI-toolbar{overflow-x:auto}.recipes-markdown-editor .toastui-editor-toolbar-group{flex:none}.recipes-form-actions{flex-wrap:wrap}.recipes-save-status{width:100%;margin-left:0}} .recipes-related-component{padding:7px 0;border-top:1px solid var(--recipe-line)}.recipes-related-component summary{color:var(--recipe-accent);font-size:.79rem;cursor:pointer}.recipes-related-component .recipes-markdown-source{margin-top:9px;padding:9px;border-radius:8px;background:var(--recipe-soft)} +.recipes-serving-form{display:flex;align-items:center;flex-wrap:wrap;gap:10px;margin-top:17px;padding:12px;border:1px solid var(--recipe-line);border-radius:10px;background:var(--recipe-soft);font-size:.8rem}.recipes-serving-form>label:first-child{font-weight:700}.recipes-serving-form input[type=number]{width:88px;min-height:40px;padding:7px;border:1px solid var(--recipe-line);border-radius:7px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-serving-form .recipes-checkbox{margin-left:auto}.recipes-serving-form .recipes-outline-button{min-height:40px}.recipes-stock-label{display:inline-block;color:var(--recipe-muted);font-size:.72rem;font-weight:700}.recipes-stock-label--available{color:#25714c}.recipes-stock-label--partial{color:#a36a19}.recipes-stock-label--missing{color:#b6413b}.recipes-stock-label--unknown{color:var(--recipe-muted)}.recipes-stock-label--optional{color:var(--recipe-muted)}.recipes-nutrition{margin:0}.recipes-nutrition>div{display:flex;align-items:start;justify-content:space-between;gap:7px;padding:8px 0;border-bottom:1px solid var(--recipe-line);font-size:.78rem}.recipes-nutrition>div:last-child{border:0}.recipes-nutrition dt{color:var(--recipe-muted)}.recipes-nutrition dd{margin:0;text-align:right;font-weight:700}.recipes-nutrition dd small{display:block;color:var(--recipe-muted);font-size:.7rem;font-weight:400}.recipes-stock-group{padding:9px 0;border-top:1px solid var(--recipe-line)}.recipes-stock-group>div:first-child{display:flex;justify-content:space-between;gap:7px;font-size:.78rem}.recipes-stock-group strong{overflow-wrap:anywhere}.recipes-stock-group small{display:block;margin:3px 0 7px;color:var(--recipe-muted);font-size:.72rem}.recipes-fill{height:8px;overflow:hidden;border-radius:999px;background:#d9e1d8}.recipes-fill span{display:block;height:100%;border-radius:inherit;background:#39845f}.recipes-preview-link{display:block;margin-top:12px;text-align:center}body[data-theme=dark] .recipes-stock-label--available{color:#9bdbab}body[data-theme=dark] .recipes-stock-label--partial{color:#f0bf6c}body[data-theme=dark] .recipes-stock-label--missing{color:#f3a09b}body[data-theme=dark] .recipes-fill{background:#3b4c40}body[data-theme=dark] .recipes-fill span{background:#6bb482} +.recipes-stock-preview{max-width:1000px}.recipes-stock-preview>.recipes-panel{margin-bottom:14px}.recipes-stock-preview h2,.recipes-substitution-list h2{margin:0 0 14px;font-family:Fraunces,Georgia,serif;font-size:1.25rem}.recipes-preview-options{display:flex;align-items:end;flex-wrap:wrap;gap:14px}.recipes-preview-options>label:first-child{display:grid;gap:5px;font-size:.8rem;font-weight:700}.recipes-preview-options input[type=number],.recipes-preview-options select{min-height:42px;padding:8px;border:1px solid var(--recipe-line);border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-preview-options input[type=number]{width:100px}.recipes-preview-options .recipes-checkbox{align-self:center}.recipes-preview-choices{display:flex;flex-wrap:wrap;gap:10px;width:100%}.recipes-preview-choices label{display:grid;gap:5px;min-width:220px;font-size:.8rem}.recipes-preview-group{padding:15px 0;border-top:1px solid var(--recipe-line)}.recipes-preview-group h3{display:flex;align-items:center;gap:10px;margin:0 0 4px}.recipes-preview-group p{margin:0 0 10px;color:var(--recipe-muted);font-size:.82rem}.recipes-preview-issues{padding-left:1.3rem;color:#a36a19;font-size:.82rem}.recipes-package{margin:8px 0;padding:11px;border:1px solid var(--recipe-line);border-radius:9px;background:var(--recipe-soft)}.recipes-package__heading{display:flex;justify-content:space-between;gap:12px;font-size:.83rem}.recipes-package small{display:block;margin:4px 0 8px;color:var(--recipe-muted)}.recipes-preview-confirm p{font-size:.84rem}.recipes-substitution-list{margin-top:18px}.recipes-substitution-list>div{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 0;border-top:1px solid var(--recipe-line)}.recipes-substitute-link{margin:8px 0 0;font-size:.8rem}.recipes-substitute-link a,.recipes-stock-preview .recipes-panel a{color:var(--recipe-accent)} +@media(max-width:767px){.recipes-serving-form .recipes-checkbox{margin-left:0}.recipes-serving-form .recipes-outline-button{width:100%}.recipes-preview-options .recipes-outline-button{width:100%}.recipes-preview-choices,.recipes-preview-choices label{width:100%;min-width:0}.recipes-package__heading{flex-wrap:wrap}} diff --git a/main/recipes/templates/recipes/form.html b/main/recipes/templates/recipes/form.html index bfc5a23..547eb62 100644 --- a/main/recipes/templates/recipes/form.html +++ b/main/recipes/templates/recipes/form.html @@ -1,7 +1,7 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %} {% block page_class %}recipes-page-content{% endblock %} -{% block content %} +{% block content %}
← Back to recipes

{% if creating %}New recipe{% else %}Edit recipe{% endif %}

Keep ingredients structured and instructions in Markdown.

{% csrf_token %} {% if creating %}{% endif %} diff --git a/main/recipes/templates/recipes/ingredient_row.html b/main/recipes/templates/recipes/ingredient_row.html index 1ad6e63..6f6582d 100644 --- a/main/recipes/templates/recipes/ingredient_row.html +++ b/main/recipes/templates/recipes/ingredient_row.html @@ -1,6 +1,7 @@
{% for hidden in ingredient.hidden_fields %}{{ hidden }}{% endfor %}
{{ ingredient.name }}{{ ingredient.name.errors }}
{{ ingredient.quantity }}{{ ingredient.quantity.errors }}
{{ ingredient.unit }}{{ ingredient.unit.errors }}
-
Ingredient details
{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}
{{ ingredient.display_order }}{{ ingredient.display_order.errors }}
{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}
{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}
{% if ingredient.DELETE %}{% endif %}
+
Ingredient details
{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}
{{ ingredient.display_order }}{{ ingredient.display_order.errors }}
{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}
{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}
{{ ingredient.amount_per_unit }}{{ ingredient.amount_per_unit.errors }}Use only when the recipe unit needs an explicit weight or volume conversion.
{{ ingredient.amount_per_unit_unit }}{{ ingredient.amount_per_unit_unit.errors }}
{% if ingredient.DELETE %}{% endif %}
+ {% if ingredient.instance.pk %}{% endif %} {% if ingredient.non_field_errors %}{% endif %}
diff --git a/main/recipes/templates/recipes/library.html b/main/recipes/templates/recipes/library.html index 72fc1ae..29baec0 100644 --- a/main/recipes/templates/recipes/library.html +++ b/main/recipes/templates/recipes/library.html @@ -2,7 +2,7 @@ {% block title %}Recipes · Tasknest{% endblock %} {% block page_class %}recipes-page-content{% endblock %} {% block content %} - +
{% endblock %} diff --git a/main/recipes/templates/recipes/stock_preview.html b/main/recipes/templates/recipes/stock_preview.html new file mode 100644 index 0000000..44892c1 --- /dev/null +++ b/main/recipes/templates/recipes/stock_preview.html @@ -0,0 +1,12 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Review stock · {{ recipe.title }} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %} +
+
← Back to {{ recipe.title }}

Review inventory use

Stock changes only after you confirm below.

+ {% if error %}{% endif %} +

Recipe amounts

{% for line in analysis.lines %}{% if line.substitutions %}{% endif %}{% endfor %}
+

Ingredient checks

    {% for line in analysis.lines %}
  • {{ line.name }}{% if line.source %}From {{ line.source }}{% endif %}{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}{% if line.ingredient.pk %}Add a substitute{% endif %}{{ line.quantity|floatformat:-3 }} {{ line.unit }}
  • {% empty %}
  • No ingredients added yet.
  • {% endfor %}

Edit ingredient quantities and product matches

+

Package deductions

{% if analysis.issues %}
    {% for issue in analysis.issues %}
  • {{ issue }}
  • {% endfor %}
{% endif %}{% for group in analysis.groups %}

{{ group.product.product_name }} {{ group.status|capfirst }}

{{ group.stock_amount|floatformat:-3 }} {{ group.unit }} needed{% if group.plan %} · {{ group.plan.total|floatformat:-3 }} {{ group.unit }} available{% if group.plan.shortage %} · {{ group.plan.shortage|floatformat:-3 }} {{ group.unit }} missing{% endif %}{% endif %}

{% if group.plan %}{% for deduction in group.plan.deductions %}
Package {{ deduction.package.api_id|stringformat:'s'|slice:':8' }}{{ deduction.before|floatformat:-3 }} → {{ deduction.after|floatformat:-3 }} {{ deduction.unit }}
Use {{ deduction.amount|floatformat:-3 }} {{ deduction.unit }}{% if deduction.package.best_before %} · Best before {{ deduction.package.best_before }}{% endif %}
{% empty %}

No compatible packages.

{% endfor %}{% endif %}
{% empty %}

Match ingredients to inventory products to see a package plan.

{% endfor %}
+

Confirm inventory use

{% if confirmation %}

This deducts the listed amounts from Kitchen Inventory. It does not log food in your diary.

{% csrf_token %}
{% else %}

Resolve missing stock or unknown matches, then update the preview before confirming.

{% endif %}
+
{% endblock %} diff --git a/main/recipes/templates/recipes/substitution_form.html b/main/recipes/templates/recipes/substitution_form.html new file mode 100644 index 0000000..26478a3 --- /dev/null +++ b/main/recipes/templates/recipes/substitution_form.html @@ -0,0 +1,4 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Add substitute · {{ ingredient.name }} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %}
← Back to recipe editor

Substitutes for {{ ingredient.name }}

Alternative quantities are measured for the recipe’s default servings.

{% csrf_token %}

Add substitute

{% for field in form %}
{{ field }}{% if field.errors %}{% endif %}
{% endfor %}
{% if ingredient.substitutions.all %}

Existing substitutes

{% for item in ingredient.substitutions.all %}
{{ item.name }} · {{ item.quantity|floatformat:-3 }} {{ item.unit }}
{% csrf_token %}
{% endfor %}
{% endif %}
{% endblock %} diff --git a/main/recipes/test_stock.py b/main/recipes/test_stock.py new file mode 100644 index 0000000..6c05195 --- /dev/null +++ b/main/recipes/test_stock.py @@ -0,0 +1,203 @@ +from decimal import Decimal +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from food.models import (FoodProduct, InventoryConsumption, InventoryLocation, + KitchenInventoryItem) +from food.services.inventory_consumption import StockError, consume as inventory_consume + +from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse +from .services.analysis import analyze, physical_amount +from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use + + +class RecipeStockTests(TestCase): + def setUp(self): + users = get_user_model() + self.user = users.objects.create_user(username='recipe-stock-owner') + self.other = users.objects.create_user(username='recipe-stock-other') + self.client.force_login(self.user) + self.location = InventoryLocation.objects.create(user=self.user, name='Pantry') + self.butter = FoodProduct.objects.create( + owner=self.user, product_name='Butter', base_unit='g', + energy_kcal_100=Decimal('700'), carbohydrates_100=Decimal('1'), + protein_100=Decimal('1'), fat_100=Decimal('80'), fibre_100=Decimal('0')) + self.recipe = Recipe.objects.create(owner=self.user, title='Butter noodles', default_servings=2) + + def package(self, product=None, amount='250', remaining=None, unit='g', opened=False): + amount = Decimal(amount) + return KitchenInventoryItem.objects.create( + user=self.user, product=product or self.butter, location=self.location, + original_amount=amount, remaining_amount=Decimal(remaining) if remaining is not None else amount, + inventory_unit=unit, opened=opened) + + def ingredient(self, recipe=None, name='Butter', quantity='150', unit='g', product=None, **kwargs): + return RecipeIngredient.objects.create( + recipe=recipe or self.recipe, name=name, quantity=Decimal(quantity), unit=unit, + inventory_product=product or self.butter, nutrition_product=product or self.butter, **kwargs) + + def test_scaling_nutrition_cross_package_confirmation_retry_and_undo(self): + self.ingredient(quantity='150') + self.ingredient(name='Extra butter', quantity='50') + opened = self.package(amount='250', remaining='100', opened=True) + unopened = self.package() + result = analyze(self.recipe, self.user, '2') + self.assertTrue(result['stock_ready']) + self.assertEqual(result['groups'][0]['stock_amount'], Decimal('200')) + self.assertEqual(result['nutrition']['calories_kcal']['total'], Decimal('1400')) + self.assertEqual(result['nutrition']['calories_kcal']['per_serving'], Decimal('700')) + self.assertEqual(result['nutrition']['fibre_g']['total'], Decimal('0')) + self.assertEqual([row['amount'] for row in result['groups'][0]['plan']['deductions']], + [Decimal('100'), Decimal('100')]) + opened.refresh_from_db(); unopened.refresh_from_db() + self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('100'), Decimal('250'))) + token = make_confirmation(result) + operation, created = confirm(self.user, self.recipe, token) + self.assertTrue(created) + self.assertEqual(operation.lines.count(), 1) + opened.refresh_from_db(); unopened.refresh_from_db() + self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('0'), Decimal('150'))) + self.assertTrue(opened.archived_at) + repeat, created = confirm(self.user, self.recipe, token) + self.assertFalse(created) + self.assertEqual(repeat.pk, operation.pk) + self.assertEqual(InventoryConsumption.objects.filter(user=self.user, reverses__isnull=True).count(), 1) + self.assertTrue(reverse_use(self.user, operation.pk)[1]) + self.assertFalse(reverse_use(self.user, operation.pk)[1]) + opened.refresh_from_db(); unopened.refresh_from_db() + self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('100'), Decimal('250'))) + + def test_shortage_and_unknown_match_block_consumption(self): + self.ingredient() + self.package(amount='100') + result = analyze(self.recipe, self.user, '2') + self.assertFalse(result['stock_ready']) + self.assertEqual(result['groups'][0]['status'], 'partial') + self.assertEqual(result['groups'][0]['plan']['shortage'], Decimal('50')) + with self.assertRaises(RecipeStockError): + confirm(self.user, self.recipe, make_confirmation(result)) + self.assertFalse(RecipeUse.objects.exists()) + self.assertEqual(KitchenInventoryItem.objects.get().remaining_amount, Decimal('100')) + RecipeIngredient.objects.create(recipe=self.recipe, name='Unmatched', quantity=1, unit='g') + result = analyze(self.recipe, self.user, '2') + self.assertEqual(result['lines'][-1]['status'], 'unknown') + self.assertFalse(result['nutrition']['protein_g']['complete']) + self.assertEqual(result['nutrition']['protein_g']['total'], Decimal('1.5')) + + def test_metric_count_and_explicit_measure_conversions(self): + self.ingredient(quantity='.2', unit='kg') + self.package(amount='250') + milk = FoodProduct.objects.create(owner=self.user, product_name='Milk', base_unit='ml', + protein_100=Decimal('3')) + self.ingredient(name='Milk', quantity='.25', unit='L', product=milk) + carton = self.package(product=milk, amount='1', unit='L') + self.ingredient(name='Butter spoon', quantity='2', unit='tbsp', + amount_per_unit=Decimal('10'), amount_per_unit_unit='g') + result = analyze(self.recipe, self.user, '2') + self.assertTrue(result['stock_ready']) + self.assertEqual([(group['product'].product_name, group['stock_amount'], group['unit']) + for group in result['groups']], + [('Butter', Decimal('220'), 'g'), ('Milk', Decimal('250'), 'ml')]) + self.assertEqual(result['nutrition']['protein_g']['total'], Decimal('9.7')) + confirm(self.user, self.recipe, make_confirmation(result)) + carton.refresh_from_db() + self.assertEqual(carton.remaining_amount, Decimal('.750')) + self.assertEqual(physical_amount(Decimal(2), 'pieces'), (Decimal(2), 'pieces')) + self.assertEqual(physical_amount(Decimal(2), 'tsp'), (None, None)) + + def test_nested_subrecipe_counts_direct_ingredients_once_and_uses_yield(self): + self.package(amount='250') + self.ingredient(quantity='50') + sauce = Recipe.objects.create(owner=self.user, title='Sauce', default_servings=2, + yield_amount=Decimal('200'), yield_unit='g') + self.ingredient(recipe=sauce, quantity='100') + RecipeSubrecipe.objects.create(recipe=self.recipe, component=sauce, + quantity=Decimal('50'), unit='g') + result = analyze(self.recipe, self.user, '2') + self.assertEqual(result['groups'][0]['stock_amount'], Decimal('75')) + self.assertEqual(result['nutrition']['fat_g']['total'], Decimal('60')) + self.assertEqual(len(result['lines']), 2) + self.assertTrue(result['stock_ready']) + sauce.yield_amount = None + sauce.yield_unit = '' + sauce.save() + incomplete = analyze(self.recipe, self.user, '2') + self.assertFalse(incomplete['stock_ready']) + self.assertFalse(incomplete['nutrition']['fat_g']['complete']) + + def test_fractional_counts_and_ambiguous_names_are_unknown(self): + self.package(amount='6', unit='pieces') + item = self.ingredient(quantity='1', unit='pieces') + result = analyze(self.recipe, self.user, '1') + self.assertFalse(result['stock_ready']) + self.assertEqual(result['lines'][0]['status'], 'unknown') + item.delete() + FoodProduct.objects.create(owner=self.user, product_name='Butter') + RecipeIngredient.objects.create(recipe=self.recipe, name='Butter', quantity=1, unit='g') + result = analyze(self.recipe, self.user, '2') + self.assertEqual(result['lines'][0]['status'], 'unknown') + + def test_substitution_changes_stock_and_nutrition_without_mutating_recipe(self): + original = self.ingredient() + oil = FoodProduct.objects.create(owner=self.user, product_name='Olive oil', base_unit='g', + fat_100=Decimal('100')) + alternative = RecipeIngredientSubstitution.objects.create( + ingredient=original, name='Olive oil', quantity=Decimal('100'), unit='g', product=oil) + self.package(product=oil, amount='200') + default = analyze(self.recipe, self.user, '2') + self.assertFalse(default['stock_ready']) + selected = analyze(self.recipe, self.user, '2', substitutions={str(original.pk): str(alternative.pk)}) + self.assertTrue(selected['stock_ready']) + self.assertEqual(selected['nutrition']['fat_g']['total'], Decimal('100')) + self.assertEqual(original.quantity, Decimal('150')) + self.assertEqual(selected['groups'][0]['product'], oil) + + def test_stale_preview_and_multi_product_failure_leave_stock_unchanged(self): + self.ingredient(quantity='50') + butter_package = self.package(amount='100') + milk = FoodProduct.objects.create(owner=self.user, product_name='Milk', base_unit='ml') + self.ingredient(name='Milk', quantity='100', unit='ml', product=milk) + milk_package = self.package(product=milk, amount='200', unit='ml') + result = analyze(self.recipe, self.user, '2') + token = make_confirmation(result) + inventory_consume(self.user, milk, 10, 'ml') + with self.assertRaises(RecipeStockError): + confirm(self.user, self.recipe, token) + butter_package.refresh_from_db() + self.assertEqual(butter_package.remaining_amount, Decimal('100')) + fresh = analyze(self.recipe, self.user, '2') + def fail_second(user, product, amount, unit, **kwargs): + if product.pk == milk.pk: + raise StockError('Injected second-product failure.') + return inventory_consume(user, product, amount, unit, **kwargs) + with patch('recipes.services.stock_use.consume', side_effect=fail_second): + with self.assertRaises(RecipeStockError): + confirm(self.user, self.recipe, make_confirmation(fresh)) + butter_package.refresh_from_db(); milk_package.refresh_from_db() + self.assertEqual(butter_package.remaining_amount, Decimal('100')) + self.assertEqual(milk_package.remaining_amount, Decimal('190')) + self.assertFalse(RecipeUse.objects.exists()) + + def test_web_preview_requires_explicit_confirm_and_respects_owner(self): + self.ingredient(quantity='50') + package = self.package(amount='100') + preview_url = reverse('recipes:stock-preview', args=[self.recipe.api_id]) + response = self.client.get(preview_url) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Confirm and deduct stock') + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('100')) + token = response.context['confirmation'] + confirm_url = reverse('recipes:stock-confirm', args=[self.recipe.api_id]) + self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 302) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('50')) + self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 302) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('50')) + self.client.force_login(self.other) + self.assertEqual(self.client.get(preview_url).status_code, 404) + self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 404) diff --git a/main/recipes/urls.py b/main/recipes/urls.py index 61dfd8c..6b04a5e 100644 --- a/main/recipes/urls.py +++ b/main/recipes/urls.py @@ -12,6 +12,13 @@ urlpatterns = [ path('/edit/', views.edit, name='edit'), path('/autosave/', views.autosave, name='autosave'), path('/variations/new/', views.create_variation, name='create-variation'), + path('/stock/', views.stock_preview, name='stock-preview'), + path('/stock/confirm/', views.stock_confirm, name='stock-confirm'), + path('stock-use//undo/', views.stock_undo, name='stock-undo'), + path('/ingredients//substitutions/new/', + views.substitution_add, name='substitution-add'), + path('/ingredients//substitutions//delete/', + views.substitution_delete, name='substitution-delete'), path('/delete/', views.delete, name='delete'), path('/favourite/', views.toggle_favourite, name='favourite'), path('/photo/', views.photo, name='photo'), diff --git a/main/recipes/views.py b/main/recipes/views.py index 8910ddd..5922867 100644 --- a/main/recipes/views.py +++ b/main/recipes/views.py @@ -11,8 +11,11 @@ from django.urls import reverse from django.views.decorators.http import require_http_methods, require_POST from PIL import Image -from .forms import RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet -from .models import Recipe, RecipeIngredient, RecipeSubrecipe +from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet, + RecipeSubstitutionForm) +from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse +from .services.analysis import AnalysisError, analyze +from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use def _owned(user): @@ -39,6 +42,17 @@ def _library(request, selected=None): recipes = recipes[:100] if selected is None and recipes: selected = recipes[0] + analysis = None + analysis_error = '' + last_use = None + if selected: + try: + analysis = analyze(selected, request.user, request.GET.get('servings'), + include_optional=request.GET.get('optional') == '1') + except AnalysisError as error: + analysis_error = str(error) + analysis = analyze(selected, request.user, selected.default_servings) + last_use = RecipeUse.objects.filter(user=request.user, recipe=selected, undone_at__isnull=True).first() categories = list(_owned(request.user).exclude(category='').order_by('category') .values_list('category', flat=True).distinct()) tags = sorted({tag for values in _owned(request.user).values_list('tags', flat=True) @@ -47,6 +61,7 @@ def _library(request, selected=None): 'recipes': recipes, 'selected': selected, 'query': query, 'category': category, 'tag': tag, 'favourite': favourite, 'categories': categories, 'tags': tags, 'explicit_detail': explicit_detail, + 'analysis': analysis, 'analysis_error': analysis_error, 'last_use': last_use, }) @@ -62,6 +77,79 @@ def detail(request, identifier): return _library(request, recipe) +@login_required +def stock_preview(request, identifier): + recipe = get_object_or_404(_owned(request.user), api_id=identifier) + selected = {key[4:]: value for key, value in request.GET.items() if key.startswith('sub_') and value} + try: + result = analyze(recipe, request.user, request.GET.get('servings'), + include_optional=request.GET.get('optional') == '1', + substitutions=selected) + error = '' + except AnalysisError as exc: + error = str(exc) + result = analyze(recipe, request.user, recipe.default_servings) + return render(request, 'recipes/stock_preview.html', { + 'recipe': recipe, 'analysis': result, 'error': error, + 'confirmation': make_confirmation(result) if result['stock_ready'] and not error else '', + }) + + +@login_required +@require_POST +def stock_confirm(request, identifier): + recipe = get_object_or_404(_owned(request.user), api_id=identifier) + try: + operation, created = confirm(request.user, recipe, request.POST.get('confirmation', '')) + messages.success(request, 'Recipe ingredients deducted from inventory.' if created + else 'This recipe stock use was already recorded.') + return redirect(f'{reverse("recipes:detail", args=[recipe.api_id])}?servings={operation.servings}') + except RecipeStockError as exc: + messages.error(request, str(exc)) + return redirect('recipes:stock-preview', identifier=recipe.api_id) + + +@login_required +@require_POST +def stock_undo(request, identifier): + operation = get_object_or_404(RecipeUse, pk=identifier, user=request.user) + try: + _, reversed_now = reverse_use(request.user, operation.pk) + messages.success(request, 'Recipe stock use reversed.' if reversed_now + else 'This stock use was already reversed.') + except RecipeStockError as exc: + messages.error(request, str(exc)) + return redirect('recipes:detail', identifier=operation.recipe.api_id) if operation.recipe else redirect('recipes:list') + + +@login_required +@require_http_methods(['GET', 'POST']) +def substitution_add(request, identifier, ingredient_id): + ingredient = get_object_or_404(RecipeIngredient, pk=ingredient_id, + recipe__api_id=identifier, recipe__owner=request.user) + form = RecipeSubstitutionForm(request.POST or None, user=request.user) + if request.method == 'POST' and form.is_valid(): + substitution = form.save(commit=False) + substitution.ingredient = ingredient + substitution.full_clean() + substitution.save() + messages.success(request, 'Substitution added.') + return redirect('recipes:edit', identifier=identifier) + return render(request, 'recipes/substitution_form.html', {'recipe': ingredient.recipe, + 'ingredient': ingredient, 'form': form}) + + +@login_required +@require_POST +def substitution_delete(request, identifier, ingredient_id, substitution_id): + item = get_object_or_404(RecipeIngredientSubstitution, pk=substitution_id, + ingredient_id=ingredient_id, ingredient__recipe__api_id=identifier, + ingredient__recipe__owner=request.user) + item.delete() + messages.success(request, 'Substitution removed.') + return redirect('recipes:edit', identifier=identifier) + + def _edit(request, recipe=None, allow_draft_resume=False): creating = recipe is None or recipe.pk is None recipe = recipe or Recipe(owner=request.user) @@ -196,11 +284,14 @@ def create_variation(request, identifier): 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, display_order=item.display_order, + 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)