Files
Django_TasksApp/main/food/services/hydration.py
T
2026-10-11 20:46:55 +02:00

98 lines
4.3 KiB
Python

"""Snapshot a food entry's eligible drink volume when it is saved."""
import re
from decimal import Decimal, InvalidOperation
from planner.models import UserSettings
ZERO = Decimal('0')
ONE = Decimal('1')
ML = Decimal('0.001')
DRINK_WORDS = {
'water': r'water|sparkling water|mineral water',
'juice': r'juice|sap|limonade|lemonade',
'milk': r'milk|melk|chocolademelk|chocolate milk',
'coffee': r'coffee|koffie|espresso|cappuccino|latte',
'tea': r'tea|thee',
'smoothie': r'smoothie|shake',
'soup': r'soup|soep|bouillon|broth',
'other_drink': r'soda|cola|drink|drank|bier|beer|wine|wijn',
}
def beverage_kind(name, categories=''):
text = f'{name} {categories}'.casefold()
for kind, words in DRINK_WORDS.items():
if re.search(rf'(?<!\w)(?:{words})(?!\w)', text):
return kind
if re.search(r'(?<!\w)(?:beverages|drinks|boissons|dranken)(?!\w)', categories.casefold()):
return 'other_drink'
return ''
def validate_rules(rules):
if not isinstance(rules, dict) or set(rules) - set(DRINK_WORDS):
raise ValueError('Rules must use supported beverage types.')
clean = {}
for kind, rule in rules.items():
if not isinstance(rule, dict) or set(rule) - {'enabled', 'factor'}:
raise ValueError('Each beverage rule needs enabled and/or factor.')
item = {}
if 'enabled' in rule:
if not isinstance(rule['enabled'], bool):
raise ValueError('Rule enabled must be true or false.')
item['enabled'] = rule['enabled']
if 'factor' in rule:
try:
factor = Decimal(str(rule['factor']))
except (InvalidOperation, TypeError):
raise ValueError('Invalid hydration factor.') from None
if not factor.is_finite() or factor < 0 or factor > 1 or factor != factor.quantize(ML):
raise ValueError('Hydration factor must be between 0 and 1 with at most three decimals.')
item['factor'] = str(factor)
clean[kind] = item
return clean
def sync_food_hydration(entry):
"""Use saved classification on edits, so later product edits do not rewrite history."""
previous = None
if entry.pk:
previous = type(entry).objects.filter(pk=entry.pk, user=entry.user).only(
'hydration_source', 'hydration_kind', 'hydration_factor_snapshot').first()
if previous and previous.hydration_source:
kind, source, factor = (previous.hydration_kind, previous.hydration_source,
previous.hydration_factor_snapshot)
else:
product = entry.product if entry.product_id else None
name = product.product_name if product else entry.product_name_snapshot
categories = (str(product.raw_data.get('categories', '')) if product and
isinstance(product.raw_data, dict) else '')
kind = beverage_kind(name, categories)
source = 'product_metadata' if product and categories and kind else 'inferred'
if product and product.hydration_source == 'manual':
source = 'manual'
kind = kind or 'other_drink'
enabled = product.is_beverage and product.hydration_enabled
else:
enabled = bool(kind) and (product.hydration_enabled if product else True)
settings = UserSettings.objects.get_or_create(user=entry.user)[0]
if kind == 'soup' and not settings.include_liquid_foods and source != 'manual':
enabled = False
rule = settings.hydration_beverage_rules.get(kind, {})
if rule.get('enabled') is False:
enabled = False
factor = ((product.hydration_factor if product else ONE) *
Decimal(str(rule.get('factor', '1')))) if enabled else ZERO
factor = factor.quantize(ML)
if not enabled:
kind = kind if kind == 'soup' else ''
entry.hydration_kind = kind
entry.hydration_source = source
entry.hydration_factor_snapshot = factor
# Food Diary nutrition units do not imply density. Only millilitres qualify.
entry.beverage_volume_ml = entry.amount if entry.unit == 'ml' and factor > 0 else None
entry.hydration_amount_ml = (entry.beverage_volume_ml * factor).quantize(ML) if entry.beverage_volume_ml else ZERO
return entry