Recipes phase 1
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
"""Owned, structured recipes. Calculations and cooking workflows arrive in later passes."""
|
||||
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
class Recipe(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
DRAFT = 'draft', 'Draft'
|
||||
PUBLISHED = 'published', 'Published'
|
||||
|
||||
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
related_name='recipes')
|
||||
title = models.CharField(max_length=180)
|
||||
description = models.TextField(blank=True)
|
||||
instructions_markdown = models.TextField(blank=True)
|
||||
notes_markdown = models.TextField(blank=True)
|
||||
photo = models.ImageField(upload_to='recipes/%Y/%m/', blank=True)
|
||||
preparation_minutes = models.PositiveIntegerField(default=0)
|
||||
cooking_minutes = models.PositiveIntegerField(default=0)
|
||||
default_servings = models.DecimalField(max_digits=7, decimal_places=2, default=2,
|
||||
validators=[MinValueValidator(Decimal('0.01'))])
|
||||
category = models.CharField(max_length=80, blank=True)
|
||||
tags = models.JSONField(default=list, blank=True)
|
||||
is_favourite = models.BooleanField(default=False)
|
||||
status = models.CharField(max_length=12, choices=Status.choices, default=Status.DRAFT)
|
||||
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
|
||||
related_name='variations')
|
||||
copied_from = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
|
||||
related_name='copies')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-updated_at', '-pk')
|
||||
constraints = [models.CheckConstraint(condition=Q(default_servings__gt=0),
|
||||
name='recipes_positive_servings')]
|
||||
|
||||
@property
|
||||
def total_minutes(self):
|
||||
return self.preparation_minutes + self.cooking_minutes
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
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:
|
||||
if self.parent_id == self.pk:
|
||||
raise ValidationError({'parent': 'A recipe cannot be its own variation.'})
|
||||
if self.owner_id and self.parent.owner_id != self.owner_id:
|
||||
raise ValidationError({'parent': 'Choose one of your own recipes.'})
|
||||
seen = {self.pk}
|
||||
cursor = self.parent
|
||||
while cursor:
|
||||
if cursor.pk in seen:
|
||||
raise ValidationError({'parent': 'Variations cannot form a cycle.'})
|
||||
seen.add(cursor.pk)
|
||||
cursor = cursor.parent
|
||||
if self.copied_from_id and self.owner_id and self.copied_from.owner_id != self.owner_id:
|
||||
raise ValidationError({'copied_from': 'Choose one of your own recipes.'})
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
|
||||
class RecipeIngredient(models.Model):
|
||||
class Unit(models.TextChoices):
|
||||
GRAM = 'g', 'g'
|
||||
KILOGRAM = 'kg', 'kg'
|
||||
MILLILITRE = 'ml', 'ml'
|
||||
LITRE = 'L', 'L'
|
||||
PIECE = 'pieces', 'pieces'
|
||||
TEASPOON = 'tsp', 'tsp'
|
||||
TABLESPOON = 'tbsp', 'tbsp'
|
||||
PORTION = 'portions', 'portions'
|
||||
|
||||
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
|
||||
name = models.CharField(max_length=180)
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=10, choices=Unit.choices)
|
||||
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')
|
||||
nutrition_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
|
||||
null=True, blank=True, related_name='recipe_nutrition_ingredients')
|
||||
preparation_note = models.CharField(max_length=255, blank=True)
|
||||
is_optional = models.BooleanField(default=False)
|
||||
|
||||
class Meta:
|
||||
ordering = ('display_order', 'pk')
|
||||
constraints = [models.CheckConstraint(condition=Q(quantity__gt=0),
|
||||
name='recipes_positive_ingredient_quantity')]
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.recipe_id:
|
||||
for field in ('inventory_product', 'nutrition_product'):
|
||||
product = getattr(self, field)
|
||||
if product and product.owner_id != self.recipe.owner_id:
|
||||
raise ValidationError({field: 'Choose one of your own food products.'})
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.quantity} {self.unit} {self.name}'
|
||||
|
||||
|
||||
class RecipeSubrecipe(models.Model):
|
||||
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='subrecipes')
|
||||
component = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name='used_in_recipes')
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3, default=1,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=16, default='servings', choices=[
|
||||
('servings', 'servings'), ('g', 'g'), ('ml', 'ml')])
|
||||
display_order = models.PositiveIntegerField(default=0)
|
||||
note = models.CharField(max_length=255, blank=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('display_order', 'pk')
|
||||
constraints = [models.UniqueConstraint(fields=('recipe', 'component'),
|
||||
name='recipes_unique_component')]
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.recipe_id and self.component_id:
|
||||
if self.recipe.owner_id != self.component.owner_id:
|
||||
raise ValidationError({'component': 'Choose one of your own recipes.'})
|
||||
if self.recipe_id == self.component_id:
|
||||
raise ValidationError({'component': 'A recipe cannot contain itself.'})
|
||||
seen = set()
|
||||
pending = [self.component_id]
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if current == self.recipe_id:
|
||||
raise ValidationError({'component': 'Subrecipes cannot form a cycle.'})
|
||||
if current not in seen:
|
||||
seen.add(current)
|
||||
pending.extend(RecipeSubrecipe.objects.filter(recipe_id=current)
|
||||
.exclude(pk=self.pk).values_list('component_id', flat=True))
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.recipe} includes {self.component}'
|
||||
|
||||
|
||||
class RecipeIngredientSubstitution(models.Model):
|
||||
ingredient = models.ForeignKey(RecipeIngredient, on_delete=models.CASCADE,
|
||||
related_name='substitutions')
|
||||
name = models.CharField(max_length=180)
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=10, choices=RecipeIngredient.Unit.choices)
|
||||
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
|
||||
null=True, blank=True, related_name='recipe_substitutions')
|
||||
display_order = models.PositiveIntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
ordering = ('display_order', 'pk')
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
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.'})
|
||||
Reference in New Issue
Block a user