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 %}
Keep ingredients structured and instructions in Markdown.