Files
Django_TasksApp/main/food/models.py
T

300 lines
16 KiB
Python

import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Q
from django.utils import timezone
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)
is_beverage = models.BooleanField(default=False)
hydration_enabled = models.BooleanField(default=True)
hydration_factor = models.DecimalField(max_digits=4, decimal_places=3, default=1, validators=[MinValueValidator(0), MaxValueValidator(1)])
hydration_source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('product_metadata', 'Product metadata'), ('inferred', 'Inferred')], default='inferred')
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)
quantity = models.DecimalField(max_digits=7, decimal_places=2, default=1,
validators=[MinValueValidator(Decimal('0.01'))])
unit = models.CharField(max_length=8, choices=[*Unit.choices, ('servings', 'servings')])
beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE)
hydration_factor_snapshot = models.DecimalField(max_digits=4, decimal_places=3, default=0, validators=NON_NEGATIVE)
hydration_kind = models.CharField(max_length=24, blank=True)
hydration_source = models.CharField(max_length=16, blank=True)
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')
constraints = [models.CheckConstraint(condition=Q(quantity__gt=0), name='food_positive_log_quantity')]
def effective_nutrient(self, name):
value = getattr(self, name)
return value * self.quantity if value is not None else None
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)
original_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inventory_unit = models.CharField(max_length=8, blank=True)
opened_at = models.DateTimeField(null=True, blank=True)
purchase_batch = models.CharField(max_length=100, blank=True)
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.original_amount is None) != (self.remaining_amount is None):
raise ValidationError('Original and remaining quantities must be supplied together.')
was_count_only = self.pk and KitchenInventoryItem.objects.filter(pk=self.pk, original_amount__isnull=True).exists()
if self.original_amount is not None and ((self.pk is not None and self.quantity != 1 and not was_count_only) or
self.inventory_unit not in ('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions') or
self.remaining_amount > self.original_amount):
raise ValidationError('A package needs one valid unit and remaining quantity within its original quantity.')
if (self.original_amount is not None and self.remaining_amount is not None and
0 < self.remaining_amount < self.original_amount and not self.opened):
raise ValidationError({'opened': 'A partly used package must be opened.'})
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.'})
def save(self, *args, **kwargs):
if self.opened and self.opened_at is None:
self.opened_at = timezone.now()
super().save(*args, **kwargs)
@property
def percentage_remaining(self):
if self.original_amount:
return int(self.remaining_amount * 100 / self.original_amount)
return 100
@property
def package_status(self):
if self.remaining_amount == 0:
return 'depleted'
return 'opened' if self.opened else 'unopened'
class InventoryConsumption(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT)
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
unit = models.CharField(max_length=8)
source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')])
source_reference = models.CharField(max_length=255, blank=True)
description = models.CharField(max_length=255, blank=True)
idempotency_key = models.CharField(max_length=128, blank=True)
request_signature = models.CharField(max_length=64, blank=True)
reverses = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True, related_name='reversal')
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''), name='food_unique_consumption_key')]
class InventoryConsumptionLine(models.Model):
transaction = models.ForeignKey(InventoryConsumption, on_delete=models.CASCADE, related_name='lines')
package = models.ForeignKey(KitchenInventoryItem, on_delete=models.PROTECT, related_name='consumption_lines')
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
unit = models.CharField(max_length=8)
before_amount = models.DecimalField(max_digits=10, decimal_places=3)
after_amount = models.DecimalField(max_digits=10, decimal_places=3)
before_opened = models.BooleanField(default=False)
before_opened_at = models.DateTimeField(null=True, blank=True)
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')]