adding food logging, phase 6
This commit is contained in:
@@ -7,6 +7,7 @@ from datetime import timedelta
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from django.conf import settings
|
||||
@@ -67,8 +68,16 @@ def map_product(data):
|
||||
match = re.search(r'(?i)(\d+(?:[.,]\d+)?)\s*(g|ml)\b', serving_text)
|
||||
serving_amount = _decimal(match.group(1).replace(',', '.')) if match else None
|
||||
serving_unit = match.group(2).lower() if match else ''
|
||||
image_url = str(data.get('image_front_small_url') or data.get('image_front_url') or '')
|
||||
try:
|
||||
parsed_image = urlparse(image_url)
|
||||
trusted_image = parsed_image.scheme == 'https' and parsed_image.hostname in {'images.openfoodfacts.org', 'static.openfoodfacts.org'}
|
||||
except ValueError:
|
||||
trusted_image = False
|
||||
if not trusted_image:
|
||||
image_url = ''
|
||||
return {'barcode': code[:64], 'product_name': name[:255], 'brand': str(data.get('brands') or '')[:255],
|
||||
'image_url': str(data.get('image_front_url') or data.get('image_front_small_url') or '')[:200],
|
||||
'image_url': image_url[:200],
|
||||
'package_quantity': str(data.get('quantity') or '')[:100], 'serving_size_text': serving_text,
|
||||
'serving_amount': serving_amount, 'serving_unit': serving_unit,
|
||||
'base_unit': Unit.MILLILITRE if serving_unit == 'ml' else Unit.GRAM, **values}
|
||||
|
||||
@@ -32,6 +32,8 @@ class OpenFoodFactsTests(TestCase):
|
||||
self.assertEqual(mapped['serving_amount'], Decimal('300.000'))
|
||||
self.assertEqual(mapped['energy_kcal_100'], Decimal('58.000'))
|
||||
self.assertIsNone(mapped['fat_100'])
|
||||
unsafe = dict(SAMPLE, image_front_url='https://example.com/track.png')
|
||||
self.assertEqual(map_product(unsafe)['image_url'], '')
|
||||
|
||||
@patch.object(OpenFoodFactsClient, 'get_product')
|
||||
def test_fresh_cached_barcode_avoids_http(self, get_product):
|
||||
|
||||
@@ -118,3 +118,12 @@ class RepeatLoggingTests(TestCase):
|
||||
self.assertContains(response, 'id="food-workspace"')
|
||||
self.assertNotContains(response, '<!doctype html>')
|
||||
self.assertNotIn('HX-Push-Url', response)
|
||||
|
||||
def test_add_and_edit_use_settings_switches(self):
|
||||
add = self.client.get(reverse('food:add'), {'product': self.product.pk})
|
||||
self.assertContains(add, 'settings-switch__track', count=2)
|
||||
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3),
|
||||
meal=MealType.BREAKFAST, product=self.product, product_name_snapshot='Greek yoghurt',
|
||||
amount=100, unit=Unit.GRAM)
|
||||
edit = self.client.get(reverse('food:edit', args=[entry.pk]))
|
||||
self.assertContains(edit, 'settings-switch__track', count=2)
|
||||
|
||||
Reference in New Issue
Block a user