from django import forms from decimal import Decimal import uuid from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem class ManualFoodForm(forms.ModelForm): basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3, initial=100, required=False, label='Nutrition basis amount') class Meta: model = FoodProduct fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100') labels = { 'energy_kcal_100': 'Calories for base quantity', 'carbohydrates_100': 'Carbohydrates for base quantity', 'protein_100': 'Protein for base quantity', 'fat_100': 'Fat for base quantity', 'saturated_fat_100': 'Saturated fat for base quantity (optional)', 'fibre_100': 'Fibre for base quantity (optional)', 'sugars_100': 'Sugars for base quantity (optional)', 'salt_100': 'Salt for base quantity (optional)', } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.fields['barcode'].required = False self.fields['base_unit'].required = False if self.instance.pk: self.fields['base_unit'].disabled = True def clean_base_unit(self): return self.cleaned_data['base_unit'] or self.instance.base_unit or 'g' def clean_basis_amount(self): return self.cleaned_data['basis_amount'] or Decimal('100') def clean_barcode(self): barcode = self.cleaned_data['barcode'].strip() if barcode and (not barcode.isascii() or not barcode.isdigit()): raise forms.ValidationError('Enter a numeric barcode.') if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exclude(pk=self.instance.pk).exists(): raise forms.ValidationError('This barcode is already saved in your foods.') return barcode def clean(self): data = super().clean() basis = data.get('basis_amount') if basis: factor = Decimal('100') / basis for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'): value = data.get(name) if value is not None and value * factor > Decimal('9999999.999'): self.add_error(name, 'This amount is too large for the chosen base quantity.') return data def save(self, commit=True): product = super().save(commit=False) factor = Decimal('100') / self.cleaned_data['basis_amount'] for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'): value = self.cleaned_data[name] setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None) if commit: product.save() return product class FoodLogForm(forms.ModelForm): portion = forms.ChoiceField(label='Portion', required=False) portion_count = forms.IntegerField(label='How many portions', min_value=1, max_value=999, required=False, initial=1) inventory_package = forms.ChoiceField(label='Use inventory', required=False) save_portion = forms.BooleanField(required=False, label='Save custom amount as a portion') new_portion_label = forms.CharField(max_length=100, required=False, label='New portion label') make_default = forms.BooleanField(required=False, label='Use this portion by default') class Meta: model = FoodLogEntry fields = ('meal', 'amount', 'unit', 'portion_label_snapshot') labels = {'portion_label_snapshot': 'Portion label (optional)'} widgets = {'amount': forms.NumberInput(attrs={'min': '0.001', 'step': '0.001'})} def __init__(self, *args, product=None, inventory_options=None, **kwargs): super().__init__(*args, **kwargs) self.product = product or getattr(self.instance, 'product', None) self.fields['inventory_package'].choices = [('', 'Log without using inventory')] + (inventory_options or []) if self.instance.pk and self.instance.created_via == 'recipe': self.fields['unit'].choices = [('servings', 'servings')] if self.product and self.product.pk: self.fields['unit'].initial = self.product.base_unit unit = self.product.base_unit choices = [('custom', 'Custom amount'), ('base', f'100 {unit}')] if self.product.serving_amount and self.product.serving_unit == unit: choices.append(('serving', f'Serving — {self.product.serving_amount:g} {unit}')) portions = list(FoodPortion.objects.filter(product=self.product, user=self.product.owner).order_by('label')) choices.extend((f'portion:{item.pk}', f'{item.label} — {item.amount:g} {item.unit}') for item in portions) self.fields['portion'].choices = choices self.portions = {str(item.pk): item for item in portions} default = next((item for item in portions if item.is_default), None) if default is None: last = self.product.log_entries.filter(user=self.product.owner).order_by('-created_at').first() default = next((item for item in portions if last and item.label == last.portion_label_snapshot and item.amount == last.amount and item.unit == last.unit), None) if self.instance.pk: selected = next((item for item in portions if item.label == self.instance.portion_label_snapshot and item.amount == self.instance.amount and item.unit == self.instance.unit), None) self.fields['portion'].initial = f'portion:{selected.pk}' if selected else 'custom' elif default: self.fields['portion'].initial = f'portion:{default.pk}' self.fields['amount'].initial = default.amount elif self.product.serving_amount and self.product.serving_unit == unit: self.fields['portion'].initial = 'serving' self.fields['amount'].initial = self.product.serving_amount else: self.fields['portion'].initial = 'base' self.fields['amount'].initial = 100 self.fields['amount'].required = False def clean_unit(self): unit = self.cleaned_data['unit'] if self.instance.pk and self.instance.created_via == 'recipe' and unit != 'servings': raise forms.ValidationError('Recipe entries use servings.') if self.product and unit != self.product.base_unit: raise forms.ValidationError('Use the same unit as the product nutrition basis.') return unit def clean(self): data = super().clean() if self.instance.pk and self.instance.created_via == 'recipe': run = getattr(self.instance, 'recipe_cooking_run', None) if run and data.get('amount') is not None and data['amount'] > run.prepared_servings: self.add_error('amount', 'This portion exceeds the prepared servings.') selected = data.get('portion') or 'custom' count = data.get('portion_count') or 1 if not self.product or not selected: return data if selected == 'base': data['amount'], data['portion_label_snapshot'] = Decimal('100') * count, '' elif selected == 'serving': data['amount'], data['portion_label_snapshot'] = self.product.serving_amount * count, f'{count} × serving' if count > 1 else 'Serving' elif selected.startswith('portion:'): portion = self.portions.get(selected.partition(':')[2]) if not portion: self.add_error('portion', 'Choose a valid portion.') else: data['amount'], data['portion_label_snapshot'] = portion.amount * count, f'{count} × {portion.label}' if count > 1 else portion.label elif selected == 'custom': if data.get('amount') is None or data['amount'] <= 0: self.add_error('amount', 'Enter an amount greater than zero.') if data.get('save_portion'): label = (data.get('new_portion_label') or '').strip() if not label: self.add_error('new_portion_label', 'Enter a label for the saved portion.') elif FoodPortion.objects.filter(user=self.product.owner, product=self.product, label=label).exists(): try: submission_id = uuid.UUID(self.data.get('submission_id', '')) except (ValueError, TypeError, AttributeError): submission_id = None if not (submission_id and FoodLogEntry.objects.filter(user=self.product.owner, api_id=submission_id).exists()): self.add_error('new_portion_label', 'You already have a portion with this label.') else: data['portion_label_snapshot'] = label elif data.get('make_default'): self.add_error('make_default', 'Save the portion before making it the default.') return data class FoodLogEditForm(FoodLogForm): edit_nutrition = forms.BooleanField(required=False, label='Use these nutrition values for this entry') class Meta(FoodLogForm.Meta): fields = FoodLogForm.Meta.fields + ('quantity', 'calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)', 'calories_kcal': 'Calories (kcal)', 'carbohydrates_g': 'Carbohydrates (g)', 'protein_g': 'Protein (g)', 'fat_g': 'Fat (g)', 'fibre_g': 'Fibre (g)', 'sugars_g': 'Sugars (g)', 'salt_g': 'Salt (g)'} widgets = {**FoodLogForm.Meta.widgets, 'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Older clients may omit the new field; keep the saved quantity in that case. self.fields['quantity'].required = False def clean_quantity(self): return self.cleaned_data['quantity'] if self.cleaned_data['quantity'] is not None else self.instance.quantity class FoodProductHydrationForm(forms.ModelForm): class Meta: model = FoodProduct fields = ('is_beverage', 'hydration_enabled', 'hydration_factor') labels = {'is_beverage': 'Count as a beverage', 'hydration_enabled': 'Include in hydration totals', 'hydration_factor': 'Fluid counting factor (0 to 1)'} widgets = {'hydration_factor': forms.NumberInput(attrs={'min': 0, 'max': 1, 'step': '.001'})} class InventoryItemForm(forms.ModelForm): location_name = forms.CharField(max_length=100, label='Location', widget=forms.TextInput(attrs={'list': 'inventory-locations', 'autocomplete': 'off'})) category_name = forms.CharField(max_length=100, required=False, label='My category', widget=forms.TextInput(attrs={'list': 'inventory-categories', 'autocomplete': 'off'})) class Meta: model = KitchenInventoryItem fields = ('quantity', 'original_amount', 'inventory_unit', 'pieces_per_package', 'remaining_pieces', 'piece_amount', 'inner_packs_per_package', 'pieces_per_inner_pack', 'inner_pack_amount', 'inner_pack_label', 'piece_label', 'opened', 'best_before', 'notes') widgets = {'quantity': forms.NumberInput(attrs={'min': 1, 'step': 1}), 'original_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'pieces_per_package': forms.NumberInput(attrs={'min': 1, 'step': 1}), 'remaining_pieces': forms.NumberInput(attrs={'min': 0, 'step': 1}), 'piece_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'inner_packs_per_package': forms.NumberInput(attrs={'min': 1, 'step': 1}), 'pieces_per_inner_pack': forms.NumberInput(attrs={'min': 1, 'step': 1}), 'inner_pack_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'best_before': forms.DateInput(attrs={'type': 'date'}), 'notes': forms.Textarea(attrs={'rows': 2})} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['inventory_unit'] = forms.ChoiceField(required=False, label='Package unit', choices=[('', 'Count only (unknown size)')] + [(unit, unit) for unit in ('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions')]) self.fields['original_amount'].label = 'Amount in outer package' self.fields['quantity'].label = 'Number of packages' self.fields['pieces_per_package'].label = 'Total pieces per package (flat package)' self.fields['remaining_pieces'].label = 'Individual pieces remaining' self.fields['piece_amount'].label = 'Amount per piece in package unit (optional)' self.fields['inner_packs_per_package'].label = 'Inner packs per package (optional)' self.fields['pieces_per_inner_pack'].label = 'Pieces per inner pack' self.fields['inner_pack_amount'].label = 'Amount per inner pack' self.fields['inner_pack_label'].label = 'Inner pack name' self.fields['piece_label'].label = 'Individual item name' self.fields['quantity'].help_text = 'Count packages or cans here, not the pieces inside them.' self.fields['original_amount'].help_text = 'For nested packs, leave blank to calculate it from inner-pack amount × inner packs.' self.fields['pieces_per_package'].help_text = 'For flat packages, such as 12 rolls or 10 sausages. Leave blank when entering nested pack counts below.' self.fields['remaining_pieces'].help_text = 'Total individual pieces left across all inner packs. For a full package, leave blank.' self.fields['piece_amount'].help_text = 'Enter a measured amount per piece for g or ml conversion; never inferred from the pack label.' self.fields['inner_packs_per_package'].help_text = 'For a nested pack, such as 6 individually wrapped inner packs.' self.fields['pieces_per_inner_pack'].help_text = 'How many individual items are in each inner pack.' self.fields['inner_pack_amount'].help_text = 'Measured amount in one inner pack, for example 44 g. This derives the approximate amount per piece.' self.fields['inner_pack_label'].help_text = 'For example, packet or wrapper.' self.fields['piece_label'].help_text = 'For example, biscuit or cracker.' if self.instance.pk: self.fields['location_name'].initial = self.instance.location.name self.fields['category_name'].initial = self.instance.category.name if self.instance.category else '' self.fields['inventory_unit'].initial = self.instance.inventory_unit def clean(self): data = super().clean() pieces = data.get('pieces_per_package') remaining_pieces = data.get('remaining_pieces') piece_amount = data.get('piece_amount') original = data.get('original_amount') unit = data.get('inventory_unit') inner_packs = data.get('inner_packs_per_package') pieces_per_inner = data.get('pieces_per_inner_pack') inner_amount = data.get('inner_pack_amount') was_count_only = self.instance.pk and KitchenInventoryItem.objects.filter( pk=self.instance.pk, original_amount__isnull=True).exists() nested = inner_packs is not None or pieces_per_inner is not None if nested: if inner_packs is None or pieces_per_inner is None: raise forms.ValidationError('Enter both inner packs per package and pieces per inner pack.') if pieces is not None and pieces != inner_packs * pieces_per_inner: raise forms.ValidationError('Total pieces must equal inner packs times pieces per inner pack.') pieces = inner_packs * pieces_per_inner data['pieces_per_package'] = pieces self.instance.pieces_per_package = pieces if not data.get('piece_label'): raise forms.ValidationError('Name the individual item, for example biscuit.') if inner_packs > 1 and not data.get('inner_pack_label'): raise forms.ValidationError('Name the inner package, for example packet.') if not original and not unit: if inner_amount is not None: raise forms.ValidationError('Choose a package unit for the measured inner-pack amount.') original, unit = Decimal(pieces), 'pieces' data['original_amount'], data['inventory_unit'] = original, unit self.instance.original_amount, self.instance.inventory_unit = original, unit if unit == 'pieces': if inner_amount is not None: raise forms.ValidationError('Piece-only packages do not use a measured inner-pack amount.') original = Decimal(pieces) data['original_amount'] = original self.instance.original_amount = original elif unit in ('mg', 'g', 'kg', 'ml', 'L'): if inner_amount is None: raise forms.ValidationError('Enter the measured amount in one inner pack.') expected_original = inner_amount * inner_packs if original is not None and original != expected_original: raise forms.ValidationError('Outer package amount must equal inner-pack amount times inner packs.') original = expected_original data['original_amount'] = original self.instance.original_amount = original else: raise forms.ValidationError('Nested contents require a pieces, mass, or volume unit.') if piece_amount is not None: raise forms.ValidationError('Nested packages derive piece amounts from the inner-pack amount.') if pieces is not None: if remaining_pieces is None: remaining_pieces = pieces data['remaining_pieces'] = pieces self.instance.remaining_pieces = pieces if remaining_pieces > pieces: raise forms.ValidationError('Pieces remaining cannot exceed pieces per package.') if not original and not unit: original, unit = Decimal(pieces), 'pieces' data['original_amount'], data['inventory_unit'] = original, unit self.instance.original_amount, self.instance.inventory_unit = original, unit if unit == 'pieces': if original != Decimal(pieces) or piece_amount is not None: raise forms.ValidationError('For piece stock, package amount must equal pieces per package; leave amount per piece blank.') if not self.instance.pk or was_count_only: self.instance.remaining_amount = Decimal(remaining_pieces) elif unit in ('mg', 'g', 'kg', 'ml', 'L'): if remaining_pieces < pieces and (not self.instance.pk or was_count_only): if nested: full_packs, loose_pieces = divmod(remaining_pieces, pieces_per_inner) remaining_value = inner_amount * full_packs if loose_pieces: remaining_value += (inner_amount * loose_pieces / pieces_per_inner).quantize(Decimal('.001')) self.instance.remaining_amount = remaining_value elif piece_amount is None: raise forms.ValidationError('Enter an explicit amount per piece to record a partly used weighed package.') else: self.instance.remaining_amount = piece_amount * remaining_pieces if self.instance.remaining_amount > original: raise forms.ValidationError('Piece amounts exceed the package amount.') else: raise forms.ValidationError('Piece contents require a piece, mass, or volume package unit.') if remaining_pieces < pieces: self.instance.opened = True data['opened'] = True elif remaining_pieces is not None or piece_amount is not None: raise forms.ValidationError('Enter pieces per package first.') if bool(data.get('original_amount')) != bool(data.get('inventory_unit')): raise forms.ValidationError('Enter both package amount and unit, or leave both blank.') if data.get('original_amount') and self.instance.remaining_amount is None: self.instance.remaining_amount = data['original_amount'] if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount: raise forms.ValidationError('Existing package sizes cannot be changed after tracking starts.') if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit: raise forms.ValidationError('Existing package units cannot be changed after tracking starts.') if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('quantity') != 1: raise forms.ValidationError('A tracked package has a quantity of one.') if self.instance.pk and not was_count_only: old = KitchenInventoryItem.objects.get(pk=self.instance.pk) nested_state = (inner_packs, pieces_per_inner, inner_amount, data.get('inner_pack_label'), data.get('piece_label')) old_nested_state = (old.inner_packs_per_package, old.pieces_per_inner_pack, old.inner_pack_amount, old.inner_pack_label, old.piece_label) if old.pieces_per_package is not None and (pieces != old.pieces_per_package or piece_amount != old.piece_amount or remaining_pieces != old.remaining_pieces or nested_state != old_nested_state): raise forms.ValidationError('Use inventory consumption to change tracked pieces.') if old.pieces_per_package is None and pieces is not None and not nested and piece_amount is not None and old.remaining_amount != piece_amount * remaining_pieces: raise forms.ValidationError('Piece counts must match current measured stock; use inventory consumption for deductions.') return data def clean_location_name(self): value = ' '.join(self.cleaned_data['location_name'].split()) if not value: raise forms.ValidationError('Enter a location.') return value def clean_category_name(self): return ' '.join(self.cleaned_data['category_name'].split()) class InventoryManualProductForm(ManualFoodForm): class Meta(ManualFoodForm.Meta): fields = ('product_name', 'brand', 'barcode', 'package_quantity', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100')