import uuid 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 NON_NEGATIVE = [MinValueValidator(0)] POSITIVE = [MinValueValidator(0.001)] class Unit(models.TextChoices): GRAM = 'g', 'g' MILLILITRE = 'ml', 'ml' class MealType(models.TextChoices): BREAKFAST = 'breakfast', 'Breakfast' LUNCH = 'lunch', 'Lunch' DINNER = 'dinner', 'Dinner' SNACKS = 'snacks', 'Snacks' class FoodProduct(models.Model): api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class Source(models.TextChoices): OPEN_FOOD_FACTS = 'openfoodfacts', 'Open Food Facts' MANUAL = 'manual', 'Manual' owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_products') barcode = models.CharField(max_length=64, blank=True, db_index=True) product_name = models.CharField(max_length=255) brand = models.CharField(max_length=255, blank=True) image_url = models.URLField(blank=True) package_quantity = models.CharField(max_length=100, blank=True) package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) package_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True) serving_size_text = models.CharField(max_length=100, blank=True) serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True) base_unit = models.CharField(max_length=2, choices=Unit.choices, default=Unit.GRAM) energy_kcal_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) carbohydrates_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) protein_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) saturated_fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) sugars_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) fibre_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) salt_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) source = models.CharField(max_length=16, choices=Source.choices, default=Source.MANUAL) raw_data = models.JSONField(default=dict, blank=True) fetched_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [models.UniqueConstraint(fields=('owner', 'barcode'), condition=~Q(barcode=''), name='food_unique_owner_barcode')] def __str__(self): return self.product_name class FoodLogEntry(models.Model): api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_log_entries') date = models.DateField(db_index=True) time = models.TimeField(null=True, blank=True) meal = models.CharField(max_length=9, choices=MealType.choices) product = models.ForeignKey(FoodProduct, on_delete=models.SET_NULL, null=True, blank=True, related_name='log_entries') product_name_snapshot = models.CharField(max_length=255) brand_snapshot = models.CharField(max_length=255, blank=True) barcode_snapshot = models.CharField(max_length=64, blank=True) portion_label_snapshot = models.CharField(max_length=100, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) unit = models.CharField(max_length=2, choices=Unit.choices) calories_kcal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) carbohydrates_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) protein_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) fat_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) fibre_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) sugars_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) salt_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) source = models.CharField(max_length=16, choices=FoodProduct.Source.choices, default=FoodProduct.Source.MANUAL) created_via = models.CharField(max_length=16, default='web') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('date', 'time', 'pk') def clean(self): super().clean() if self.product_id and self.user_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own food products.'}) def __str__(self): return f'{self.product_name_snapshot} on {self.date}' class FoodFavourite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_favourites') product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='favourites') created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=('user', 'product'), name='food_unique_favourite')] def clean(self): super().clean() if self.product_id and self.user_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own food products.'}) class FoodPortion(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_portions') product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='portions') label = models.CharField(max_length=100) amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) unit = models.CharField(max_length=2, choices=Unit.choices) is_default = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [ models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label'), models.UniqueConstraint(fields=('user', 'product'), condition=Q(is_default=True), name='food_one_default_portion'), ] def clean(self): super().clean() if self.product_id and self.user_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own food products.'}) if self.product_id and self.unit != self.product.base_unit: raise ValidationError({'unit': 'Use the same unit as the product nutrition basis.'}) class InventoryLocation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) sort_order = models.PositiveIntegerField(default=0) class Meta: constraints = [models.UniqueConstraint(fields=('user', 'name'), name='food_unique_inventory_location')] ordering = ('sort_order', 'name') def __str__(self): return self.name class InventoryCategory(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Meta: constraints = [models.UniqueConstraint(fields=('user', 'name'), name='food_unique_inventory_category')] ordering = ('name',) def __str__(self): return self.name class KitchenInventoryItem(models.Model): api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='kitchen_inventory') product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT, related_name='inventory_items') quantity = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)]) location = models.ForeignKey(InventoryLocation, on_delete=models.PROTECT) category = models.ForeignKey(InventoryCategory, on_delete=models.PROTECT, null=True, blank=True) notes = models.TextField(blank=True) opened = models.BooleanField(default=False) remaining_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) best_before = models.DateField(null=True, blank=True) archived_at = models.DateTimeField(null=True, blank=True) added_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def clean(self): super().clean() if self.remaining_amount is not None and (not self.product_id or self.quantity != 1 or not self.opened or not self.product.package_amount or self.remaining_amount > self.product.package_amount): raise ValidationError({'remaining_amount': 'Remaining contents require one opened package with a known package size.'}) if self.user_id and self.product_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own products.'}) if self.user_id and self.location_id and self.location.user_id != self.user_id: raise ValidationError({'location': 'Choose one of your own locations.'}) if self.user_id and self.category_id and self.category.user_id != self.user_id: raise ValidationError({'category': 'Choose one of your own categories.'}) class PersonalAccessToken(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_access_tokens') name = models.CharField(max_length=100) prefix = models.CharField(max_length=20, unique=True) token_hash = models.CharField(max_length=64) scopes = models.JSONField(default=list) created_at = models.DateTimeField(auto_now_add=True) last_used_at = models.DateTimeField(null=True, blank=True) expires_at = models.DateTimeField(null=True, blank=True) revoked_at = models.DateTimeField(null=True, blank=True) class FoodLogAttachment(models.Model): api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) log_entry = models.ForeignKey(FoodLogEntry, on_delete=models.CASCADE, related_name='attachments') image = models.ImageField(upload_to='food-attachments/%Y/%m/') original_filename = models.CharField(max_length=255) content_type = models.CharField(max_length=50) file_size = models.PositiveIntegerField() caption = models.CharField(max_length=255, blank=True) created_at = models.DateTimeField(auto_now_add=True) class ApiIdempotencyRecord(models.Model): token = models.ForeignKey(PersonalAccessToken, on_delete=models.CASCADE) key = models.CharField(max_length=128) request_hash = models.CharField(max_length=64) response = models.JSONField() created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')]