507 lines
29 KiB
Python
507 lines
29 KiB
Python
import uuid
|
|
from decimal import Decimal, ROUND_HALF_UP
|
|
|
|
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)
|
|
pieces_per_package = models.PositiveIntegerField(null=True, blank=True)
|
|
remaining_pieces = models.PositiveIntegerField(null=True, blank=True)
|
|
piece_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
|
inner_packs_per_package = models.PositiveIntegerField(null=True, blank=True)
|
|
pieces_per_inner_pack = models.PositiveIntegerField(null=True, blank=True)
|
|
inner_pack_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
|
inner_pack_label = models.CharField(max_length=40, blank=True)
|
|
piece_label = models.CharField(max_length=40, 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.pieces_per_package is not None:
|
|
if not self.pieces_per_package or (self.pk and self.quantity != 1) or self.original_amount is None:
|
|
raise ValidationError({'pieces_per_package': 'Track one package with a known contents amount.'})
|
|
if self.remaining_pieces is None or self.remaining_pieces > self.pieces_per_package:
|
|
raise ValidationError({'remaining_pieces': 'Enter a piece count within the package capacity.'})
|
|
if self.remaining_pieces < self.pieces_per_package and not self.opened and self.remaining_pieces > 0:
|
|
raise ValidationError({'opened': 'A partly used package must be opened.'})
|
|
if self.inventory_unit == 'pieces':
|
|
if self.original_amount != self.pieces_per_package or self.remaining_amount != self.remaining_pieces:
|
|
raise ValidationError({'original_amount': 'Piece stock must match the package piece counts.'})
|
|
if self.piece_amount is not None:
|
|
raise ValidationError({'piece_amount': 'A separate piece amount is only used for weighed packages.'})
|
|
elif self.inventory_unit in ('mg', 'g', 'kg', 'ml', 'L'):
|
|
if self.piece_amount is not None and self.piece_amount <= 0:
|
|
raise ValidationError({'piece_amount': 'Enter a positive amount per piece.'})
|
|
if self.remaining_pieces == 0 and self.remaining_amount != 0:
|
|
raise ValidationError({'remaining_amount': 'A package with no pieces must have no remaining amount.'})
|
|
else:
|
|
raise ValidationError({'inventory_unit': 'Piece contents require pieces, mass, or volume.'})
|
|
elif self.remaining_pieces is not None or self.piece_amount is not None:
|
|
raise ValidationError({'pieces_per_package': 'Enter pieces per package first.'})
|
|
nested_values = (self.inner_packs_per_package, self.pieces_per_inner_pack)
|
|
if any(value is not None for value in nested_values):
|
|
if any(value is None or value < 1 for value in nested_values):
|
|
raise ValidationError({'inner_packs_per_package': 'Enter both inner packs per package and pieces per inner pack.'})
|
|
if self.pieces_per_package != self.inner_packs_per_package * self.pieces_per_inner_pack:
|
|
raise ValidationError({'pieces_per_package': 'Total pieces must equal inner packs times pieces per inner pack.'})
|
|
if self.piece_amount is not None:
|
|
raise ValidationError({'piece_amount': 'Nested packages derive piece weight from the inner-pack amount.'})
|
|
if self.inventory_unit == 'pieces':
|
|
if self.inner_pack_amount is not None:
|
|
raise ValidationError({'inner_pack_amount': 'Piece-only packages do not use a measured inner-pack amount.'})
|
|
elif self.inventory_unit in ('mg', 'g', 'kg', 'ml', 'L'):
|
|
if self.inner_pack_amount is None:
|
|
raise ValidationError({'inner_pack_amount': 'Enter the measured amount in one inner pack.'})
|
|
if self.original_amount != self.inner_pack_amount * self.inner_packs_per_package:
|
|
raise ValidationError({'original_amount': 'Outer package amount must equal inner-pack amount times inner packs.'})
|
|
full_packs, loose_pieces = divmod(self.remaining_pieces, self.pieces_per_inner_pack)
|
|
expected_remaining = self.inner_pack_amount * full_packs
|
|
if loose_pieces:
|
|
expected_remaining += (self.inner_pack_amount * loose_pieces / self.pieces_per_inner_pack).quantize(
|
|
Decimal('.001'), rounding=ROUND_HALF_UP)
|
|
if self.remaining_amount != expected_remaining:
|
|
raise ValidationError({'remaining_amount': 'Remaining amount must match the remaining whole pieces and inner packs.'})
|
|
if self.inner_packs_per_package > 1 and not self.inner_pack_label:
|
|
raise ValidationError({'inner_pack_label': 'Name the inner package unit (for example, packet).'})
|
|
if not self.piece_label:
|
|
raise ValidationError({'piece_label': 'Name the individual item (for example, biscuit).'})
|
|
elif self.inner_pack_amount is not None or self.inner_pack_label or self.piece_label:
|
|
raise ValidationError({'inner_packs_per_package': 'Enter nested package counts before adding inner-pack details.'})
|
|
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'
|
|
|
|
@property
|
|
def remaining_full_inner_packs(self):
|
|
if not self.pieces_per_inner_pack or self.remaining_pieces is None:
|
|
return 0
|
|
return self.remaining_pieces // self.pieces_per_inner_pack
|
|
|
|
@property
|
|
def opened_inner_pack_pieces(self):
|
|
if not self.pieces_per_inner_pack or self.remaining_pieces is None:
|
|
return 0
|
|
return self.remaining_pieces % self.pieces_per_inner_pack
|
|
|
|
@property
|
|
def remaining_inner_pack_balance(self):
|
|
if not self.inner_packs_per_package:
|
|
return ''
|
|
parts = []
|
|
if self.remaining_full_inner_packs:
|
|
parts.append(f'{self.remaining_full_inner_packs} unopened {self.inner_pack_label or "inner pack"}{"s" if self.remaining_full_inner_packs != 1 else ""}')
|
|
if self.opened_inner_pack_pieces:
|
|
parts.append(f'1 opened {self.inner_pack_label or "inner pack"} with {self.opened_inner_pack_pieces} {self.piece_label or "piece"}{"s" if self.opened_inner_pack_pieces != 1 else ""} left')
|
|
return ' + '.join(parts) if parts else 'no inner packs remaining'
|
|
|
|
|
|
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=16)
|
|
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)
|
|
before_pieces = models.PositiveIntegerField(null=True, blank=True)
|
|
after_pieces = models.PositiveIntegerField(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')]
|
|
|
|
|
|
class InventoryScanRun(models.Model):
|
|
"""A resumable scan-in session, including batches submitted while scanning continues."""
|
|
class Status(models.TextChoices):
|
|
ACTIVE = 'active', 'Active'
|
|
PROCESSING = 'processing', 'Processing'
|
|
COMPLETE = 'complete', 'Complete'
|
|
COMPLETE_WITH_REVIEW = 'complete_with_review', 'Complete with review'
|
|
CANCELLED = 'cancelled', 'Cancelled'
|
|
|
|
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='inventory_scan_runs')
|
|
status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE, db_index=True)
|
|
selected_location = models.ForeignKey(InventoryLocation, on_delete=models.SET_NULL, null=True, blank=True,
|
|
related_name='active_scan_runs')
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
submitted_at = models.DateTimeField(null=True, blank=True)
|
|
completed_at = models.DateTimeField(null=True, blank=True)
|
|
notification_attempted_at = models.DateTimeField(null=True, blank=True)
|
|
notification_sent_at = models.DateTimeField(null=True, blank=True)
|
|
notification_error = models.CharField(max_length=255, blank=True)
|
|
|
|
class Meta:
|
|
indexes = [models.Index(fields=('user', 'status', '-created_at'), name='food_scan_run_user_status')]
|
|
constraints = [models.UniqueConstraint(fields=('user',), condition=Q(status='active'),
|
|
name='food_one_active_scan_run')]
|
|
|
|
|
|
class InventoryScanBatch(models.Model):
|
|
"""A location-specific portion of a run. Save & next closes one and opens another."""
|
|
class Status(models.TextChoices):
|
|
DRAFT = 'draft', 'Draft'
|
|
QUEUED = 'queued', 'Queued'
|
|
COMPLETE = 'complete', 'Complete'
|
|
|
|
run = models.ForeignKey(InventoryScanRun, on_delete=models.CASCADE, related_name='batches')
|
|
location = models.ForeignKey(InventoryLocation, on_delete=models.PROTECT, related_name='scan_batches')
|
|
sequence = models.PositiveIntegerField()
|
|
status = models.CharField(max_length=12, choices=Status.choices, default=Status.DRAFT, db_index=True)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
submitted_at = models.DateTimeField(null=True, blank=True)
|
|
completed_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
class Meta:
|
|
ordering = ('sequence',)
|
|
constraints = [
|
|
models.UniqueConstraint(fields=('run', 'sequence'), name='food_unique_scan_batch_sequence'),
|
|
models.UniqueConstraint(fields=('run',), condition=Q(status='draft'), name='food_one_draft_scan_batch'),
|
|
]
|
|
|
|
|
|
class InventoryScanItem(models.Model):
|
|
"""A persisted scan entry that becomes its own retryable enrichment job on submit."""
|
|
class Status(models.TextChoices):
|
|
ACTIVE = 'active', 'Active scan'
|
|
CONFIRMED = 'confirmed', 'Confirmed'
|
|
QUEUED = 'queued', 'Queued'
|
|
PROCESSING = 'processing', 'Processing'
|
|
NEEDS_REVIEW = 'needs_review', 'Needs review'
|
|
COMPLETE = 'complete', 'Complete'
|
|
DEFERRED = 'deferred', 'Deferred'
|
|
FAILED = 'failed', 'Failed'
|
|
|
|
batch = models.ForeignKey(InventoryScanBatch, on_delete=models.CASCADE, related_name='items')
|
|
location = models.ForeignKey(InventoryLocation, on_delete=models.PROTECT, related_name='scan_items')
|
|
barcode = models.CharField(max_length=64, db_index=True)
|
|
status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE, db_index=True)
|
|
package_count = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
|
|
package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
|
package_unit = models.CharField(max_length=8, blank=True)
|
|
pieces_per_package = models.PositiveIntegerField(null=True, blank=True)
|
|
piece_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
|
inner_packs_per_package = models.PositiveIntegerField(null=True, blank=True)
|
|
pieces_per_inner_pack = models.PositiveIntegerField(null=True, blank=True)
|
|
inner_pack_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
|
inner_pack_label = models.CharField(max_length=40, blank=True)
|
|
piece_label = models.CharField(max_length=40, blank=True)
|
|
product_name = models.CharField(max_length=255, blank=True)
|
|
brand = models.CharField(max_length=255, blank=True)
|
|
category_name = models.CharField(max_length=100, blank=True)
|
|
notes = models.TextField(blank=True)
|
|
best_before = models.DateField(null=True, blank=True)
|
|
opened = models.BooleanField(default=False)
|
|
source_data = models.JSONField(default=dict, blank=True)
|
|
user_data = models.JSONField(default=dict, blank=True)
|
|
product = models.ForeignKey(FoodProduct, on_delete=models.SET_NULL, null=True, blank=True,
|
|
related_name='scan_items')
|
|
inventory_item = models.ForeignKey(KitchenInventoryItem, on_delete=models.SET_NULL, null=True, blank=True,
|
|
related_name='scan_items')
|
|
attempts = models.PositiveSmallIntegerField(default=0)
|
|
next_attempt_at = models.DateTimeField(null=True, blank=True, db_index=True)
|
|
lease_until = models.DateTimeField(null=True, blank=True, db_index=True)
|
|
last_error = models.CharField(max_length=255, blank=True)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
confirmed_at = models.DateTimeField(null=True, blank=True)
|
|
completed_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
class Meta:
|
|
ordering = ('created_at', 'pk')
|
|
indexes = [models.Index(fields=('status', 'next_attempt_at'), name='food_scan_item_due')]
|
|
|
|
|
|
class OpenFoodFactsRequest(models.Model):
|
|
"""A durable timestamp for each actual OFF HTTP request; shared by web and worker processes."""
|
|
requested_at = models.DateTimeField(db_index=True)
|
|
endpoint = models.CharField(max_length=24, blank=True)
|
|
|
|
|
|
class OpenFoodFactsRateLimit(models.Model):
|
|
"""A single database lock row coordinates request reservations across processes."""
|
|
id = models.PositiveSmallIntegerField(primary_key=True, default=1, editable=False)
|
|
updated_at = models.DateTimeField(auto_now=True)
|
|
|
|
|
|
class InventoryReviewPreference(models.Model):
|
|
class Mode(models.TextChoices):
|
|
INDIVIDUAL = 'individual', 'Individual'
|
|
BULK = 'bulk', 'Bulk'
|
|
|
|
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
|
related_name='inventory_review_preference')
|
|
mode = models.CharField(max_length=12, choices=Mode.choices, default=Mode.INDIVIDUAL)
|
|
updated_at = models.DateTimeField(auto_now=True)
|