Self hosted FLOSS fitness/workout, nutrition and weight tracker
Sync the rest of the nutrition tables to powersync
Roland Geider8e32f65924b5
diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 6010f2536..8c446f123 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -576,16 +576,34 @@ def upload_powersync_data(request):# Nutritioncase 'nutrition_nutritionplan':- # Creation still goes through REST; only edit and delete reach us via PowerSync- if http_verb == 'PATCH':+ if http_verb == 'PUT':+ result = ps_nutrition.handle_create_plan(payload=payload, user_id=user_id)+ elif http_verb == 'PATCH':result = ps_nutrition.handle_update_plan(payload=payload, user_id=user_id)elif http_verb == 'DELETE':result = ps_nutrition.handle_delete_plan(payload=payload, user_id=user_id)- elif http_verb == 'PUT':- result = {- 'error': 'Method not allowed',- 'details': 'NutritionPlan creation must go through the REST API',- }++ case 'nutrition_meal':+ if http_verb == 'PUT':+ result = ps_nutrition.handle_create_meal(payload=payload, user_id=user_id)+ elif http_verb == 'PATCH':+ result = ps_nutrition.handle_update_meal(payload=payload, user_id=user_id)+ elif http_verb == 'DELETE':+ result = ps_nutrition.handle_delete_meal(payload=payload, user_id=user_id)++ case 'nutrition_mealitem':+ if http_verb == 'PUT':+ result = ps_nutrition.handle_create_mealitem(+ payload=payload, user_id=user_id+ )+ elif http_verb == 'PATCH':+ result = ps_nutrition.handle_update_mealitem(+ payload=payload, user_id=user_id+ )+ elif http_verb == 'DELETE':+ result = ps_nutrition.handle_delete_mealitem(+ payload=payload, user_id=user_id+ )case 'nutrition_logitem':if http_verb == 'PUT':diff --git a/wger/nutrition/fixtures/test-nutrition-data.json b/wger/nutrition/fixtures/test-nutrition-data.jsonindex 546f4736b..0339abff4 100644--- a/wger/nutrition/fixtures/test-nutrition-data.json+++ b/wger/nutrition/fixtures/test-nutrition-data.json@@ -1,366 +1,372 @@[- {- "pk": 1,- "model": "nutrition.nutritionplan",- "fields": {- "description": "",- "user": 2,- "creation_date": "2012-09-22",- "start": "2012-09-22",- "end": null- }- },- {- "pk": 2,- "model": "nutrition.nutritionplan",- "fields": {- "description": "",- "user": 1,- "creation_date": "2012-10-29",- "start": "2012-11-01",- "end": "2012-11-30"- }- },- {- "pk": 3,- "model": "nutrition.nutritionplan",- "fields": {- "description": "",- "user": 1,- "creation_date": "2012-11-09",- "start": "2012-11-09",- "end": null- }- },- {- "pk": 4,- "model": "nutrition.nutritionplan",- "fields": {- "description": "My plan to do xyz",- "user": 2,- "creation_date": "2012-11-12",- "start": "2012-11-12",- "end": null- }- },- {- "pk": 5,- "model": "nutrition.nutritionplan",- "fields": {- "description": "Description 1",- "user": 1,- "creation_date": "2012-11-19",- "start": "2012-12-01",- "end": "2012-12-31"- }- },- {- "pk": 1,- "model": "nutrition.meal",- "fields": {- "time": null,- "plan": 1,- "order": 1- }- },- {- "pk": 2,- "model": "nutrition.meal",- "fields": {- "time": "07:00:00",- "plan": 4,- "order": 1- }- },- {- "pk": 3,- "model": "nutrition.meal",- "fields": {- "time": "08:00:00",- "plan": 2,- "order": 1- }- },- {- "pk": 4,- "model": "nutrition.meal",- "fields": {- "time": "08:00:00",- "plan": 3,- "order": 1- }- },- {- "pk": 5,- "model": "nutrition.meal",- "fields": {- "time": "08:00:00",- "plan": 2,- "order": 1- }- },- {- "pk": 6,- "model": "nutrition.meal",- "fields": {- "time": "08:00:00",- "plan": 5,- "order": 1- }- },- {- "pk": 7,- "model": "nutrition.meal",- "fields": {- "time": "08:02:00",- "plan": 4,- "order": 1- }- },- {- "pk": 8,- "model": "nutrition.meal",- "fields": {- "time": "10:00:00",- "plan": 2,- "order": 1- }- },- {- "pk": 9,- "model": "nutrition.meal",- "fields": {- "time": "10:00:00",- "plan": 4,- "order": 1- }- },- {- "pk": 10,- "model": "nutrition.meal",- "fields": {- "time": "19:02:00",- "plan": 4,- "order": 1- }- },- {- "pk": 11,- "model": "nutrition.meal",- "fields": {- "time": "22:00:00",- "plan": 4,- "order": 1- }- },- {- "pk": 1,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 200,- "meal": 1,- "order": 1- }- },- {- "pk": 2,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 200,- "meal": 1,- "order": 1- }- },- {- "pk": 3,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 200,- "meal": 1,- "order": 1- }- },- {- "pk": 4,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 4,- "amount": 300,- "meal": 3,- "order": 1- }- },- {- "pk": 5,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 2,- "amount": 100,- "meal": 8,- "order": 1- }- },- {- "pk": 6,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 5,- "amount": 100,- "meal": 8,- "order": 1- }- },- {- "pk": 7,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 3,- "amount": 300,- "meal": 7,- "order": 1- }- },- {- "pk": 8,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 101,- "meal": 9,- "order": 1- }- },- {- "pk": 9,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 2,- "amount": 100,- "meal": 9,- "order": 1- }- },- {- "pk": 10,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 3,- "amount": 100,- "meal": 2,- "order": 1- }- },- {- "pk": 11,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 4,- "amount": 200,- "meal": 10,- "order": 1- }- },- {- "pk": 12,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 4,- "amount": 200,- "meal": 10,- "order": 1- }- },- {- "pk": 13,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 3,- "amount": 100,- "meal": 7,- "order": 1- }- },- {- "pk": 14,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 6,- "amount": 30,- "meal": 7,- "order": 1- }- },- {- "pk": 15,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 3,- "amount": 150,- "meal": 10,- "order": 1- }- },- {- "pk": 16,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 500,- "meal": 11,- "order": 1- }- },- {- "pk": 17,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 6,- "amount": 100,- "meal": 6,- "order": 1- }- },- {- "pk": 18,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 4,- "amount": 100,- "meal": 6,- "order": 1- }- },- {- "pk": 19,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 3,- "amount": 100,- "meal": 6,- "order": 1- }- },- {- "pk": 20,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 2,- "amount": 100,- "meal": 6,- "order": 1- }- },- {- "pk": 21,- "model": "nutrition.mealitem",- "fields": {- "ingredient": 1,- "amount": 100,- "meal": 6,- "order": 1- }- }-]+ {+ "pk": 1,+ "model": "nutrition.nutritionplan",+ "fields": {+ "description": "",+ "user": 2,+ "creation_date": "2012-09-22",+ "start": "2012-09-22",+ "end": null,+ "uuid": "cc000000-0000-0000-0000-000000000001"+ }+ },+ {+ "pk": 2,+ "model": "nutrition.nutritionplan",+ "fields": {+ "description": "",+ "user": 1,+ "creation_date": "2012-10-29",+ "start": "2012-11-01",+ "end": "2012-11-30",+ "uuid": "cc000000-0000-0000-0000-000000000002"+ }+ },+ {+ "pk": 3,+ "model": "nutrition.nutritionplan",+ "fields": {+ "description": "",+ "user": 1,+ "creation_date": "2012-11-09",+ "start": "2012-11-09",+ "end": null+ }+ },+ {+ "pk": 4,+ "model": "nutrition.nutritionplan",+ "fields": {+ "description": "My plan to do xyz",+ "user": 2,+ "creation_date": "2012-11-12",+ "start": "2012-11-12",+ "end": null+ }+ },+ {+ "pk": 5,+ "model": "nutrition.nutritionplan",+ "fields": {+ "description": "Description 1",+ "user": 1,+ "creation_date": "2012-11-19",+ "start": "2012-12-01",+ "end": "2012-12-31"+ }+ },+ {+ "pk": 1,+ "model": "nutrition.meal",+ "fields": {+ "time": null,+ "plan": 1,+ "order": 1,+ "uuid": "aa000000-0000-0000-0000-000000000001"+ }+ },+ {+ "pk": 2,+ "model": "nutrition.meal",+ "fields": {+ "time": "07:00:00",+ "plan": 4,+ "order": 1+ }+ },+ {+ "pk": 3,+ "model": "nutrition.meal",+ "fields": {+ "time": "08:00:00",+ "plan": 2,+ "order": 1,+ "uuid": "aa000000-0000-0000-0000-000000000003"+ }+ },+ {+ "pk": 4,+ "model": "nutrition.meal",+ "fields": {+ "time": "08:00:00",+ "plan": 3,+ "order": 1+ }+ },+ {+ "pk": 5,+ "model": "nutrition.meal",+ "fields": {+ "time": "08:00:00",+ "plan": 2,+ "order": 1+ }+ },+ {+ "pk": 6,+ "model": "nutrition.meal",+ "fields": {+ "time": "08:00:00",+ "plan": 5,+ "order": 1+ }+ },+ {+ "pk": 7,+ "model": "nutrition.meal",+ "fields": {+ "time": "08:02:00",+ "plan": 4,+ "order": 1+ }+ },+ {+ "pk": 8,+ "model": "nutrition.meal",+ "fields": {+ "time": "10:00:00",+ "plan": 2,+ "order": 1+ }+ },+ {+ "pk": 9,+ "model": "nutrition.meal",+ "fields": {+ "time": "10:00:00",+ "plan": 4,+ "order": 1+ }+ },+ {+ "pk": 10,+ "model": "nutrition.meal",+ "fields": {+ "time": "19:02:00",+ "plan": 4,+ "order": 1+ }+ },+ {+ "pk": 11,+ "model": "nutrition.meal",+ "fields": {+ "time": "22:00:00",+ "plan": 4,+ "order": 1+ }+ },+ {+ "pk": 1,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 200,+ "meal": 1,+ "order": 1,+ "uuid": "bb000000-0000-0000-0000-000000000001"+ }+ },+ {+ "pk": 2,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 200,+ "meal": 1,+ "order": 1+ }+ },+ {+ "pk": 3,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 200,+ "meal": 1,+ "order": 1+ }+ },+ {+ "pk": 4,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 4,+ "amount": 300,+ "meal": 3,+ "order": 1,+ "uuid": "bb000000-0000-0000-0000-000000000004"+ }+ },+ {+ "pk": 5,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 2,+ "amount": 100,+ "meal": 8,+ "order": 1+ }+ },+ {+ "pk": 6,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 5,+ "amount": 100,+ "meal": 8,+ "order": 1+ }+ },+ {+ "pk": 7,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 3,+ "amount": 300,+ "meal": 7,+ "order": 1+ }+ },+ {+ "pk": 8,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 101,+ "meal": 9,+ "order": 1+ }+ },+ {+ "pk": 9,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 2,+ "amount": 100,+ "meal": 9,+ "order": 1+ }+ },+ {+ "pk": 10,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 3,+ "amount": 100,+ "meal": 2,+ "order": 1+ }+ },+ {+ "pk": 11,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 4,+ "amount": 200,+ "meal": 10,+ "order": 1+ }+ },+ {+ "pk": 12,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 4,+ "amount": 200,+ "meal": 10,+ "order": 1+ }+ },+ {+ "pk": 13,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 3,+ "amount": 100,+ "meal": 7,+ "order": 1+ }+ },+ {+ "pk": 14,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 6,+ "amount": 30,+ "meal": 7,+ "order": 1+ }+ },+ {+ "pk": 15,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 3,+ "amount": 150,+ "meal": 10,+ "order": 1+ }+ },+ {+ "pk": 16,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 500,+ "meal": 11,+ "order": 1+ }+ },+ {+ "pk": 17,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 6,+ "amount": 100,+ "meal": 6,+ "order": 1+ }+ },+ {+ "pk": 18,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 4,+ "amount": 100,+ "meal": 6,+ "order": 1+ }+ },+ {+ "pk": 19,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 3,+ "amount": 100,+ "meal": 6,+ "order": 1+ }+ },+ {+ "pk": 20,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 2,+ "amount": 100,+ "meal": 6,+ "order": 1+ }+ },+ {+ "pk": 21,+ "model": "nutrition.mealitem",+ "fields": {+ "ingredient": 1,+ "amount": 100,+ "meal": 6,+ "order": 1+ }+ }+]\ No newline at end of filediff --git a/wger/nutrition/migrations/0035_add_uuids.py b/wger/nutrition/migrations/0035_add_uuids.pyindex d97d8f77f..aed5a8e82 100644--- a/wger/nutrition/migrations/0035_add_uuids.py+++ b/wger/nutrition/migrations/0035_add_uuids.py@@ -86,7 +86,7 @@ class Migration(migrations.Migration):name='uuid',field=models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,),@@ -96,7 +96,7 @@ class Migration(migrations.Migration):name='uuid',field=models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,),@@ -106,7 +106,7 @@ class Migration(migrations.Migration):name='uuid',field=models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,),diff --git a/wger/nutrition/models/meal.py b/wger/nutrition/models/meal.pyindex ae5b05a1d..31080a03b 100644--- a/wger/nutrition/models/meal.py+++ b/wger/nutrition/models/meal.py@@ -45,7 +45,7 @@ class Meal(models.Model):uuid = models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,)diff --git a/wger/nutrition/models/meal_item.py b/wger/nutrition/models/meal_item.pyindex 4bff7f0cc..7477ff123 100644--- a/wger/nutrition/models/meal_item.py+++ b/wger/nutrition/models/meal_item.py@@ -45,7 +45,7 @@ class MealItem(BaseMealItem, models.Model):uuid = models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,)diff --git a/wger/nutrition/models/plan.py b/wger/nutrition/models/plan.pyindex 50d3b42ab..bda97eb14 100644--- a/wger/nutrition/models/plan.py+++ b/wger/nutrition/models/plan.py@@ -49,7 +49,7 @@ class NutritionPlan(models.Model):uuid = models.UUIDField(default=uuid.uuid4,- editable=False,+ editable=True,null=False,unique=True,)diff --git a/wger/nutrition/powersync.py b/wger/nutrition/powersync.pyindex d81f05b93..fe13d6047 100644--- a/wger/nutrition/powersync.py+++ b/wger/nutrition/powersync.py@@ -20,81 +20,263 @@ from typing import Any# wgerfrom wger.nutrition.api.serializers import (LogItemSerializer,+ MealItemSerializer,+ MealSerializer,NutritionPlanSerializer,)from wger.nutrition.api.views import (LogItemViewSet,+ MealItemViewSet,+ MealViewSet,NutritionPlanViewSet,)from wger.nutrition.models import (LogItem,+ Meal,+ MealItem,NutritionPlan,)+from wger.utils.powersync import resolve_uuid_fkfrom wger.utils.viewsets import check_fk_ownershiplogger = logging.getLogger(__name__)-def handle_update_plan(payload: dict[str, Any], user_id: int) -> dict | None:- """Handle a PowerSync PATCH event for a nutritional plan.+#+# Nutritional plans+#- Creation still goes through REST (the backend assigns the integer PK and- `creation_date`), so there is no `handle_create_plan` here — only edit- and delete are part of the PowerSync upload pipeline.++def handle_create_plan(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PUT event for a nutritional plan.++ The client generates the row's UUID; the backend honours it via+ `serializer.save(uuid=...)`. The owning user is forced to the+ authenticated one regardless of payload contents."""+ logger.debug(f'Received PowerSync payload for nutritional plan create: {payload}')++ serializer = NutritionPlanSerializer(data=payload)+ if serializer.is_valid():+ serializer.save(user_id=user_id, uuid=payload['id'])+ logger.info(f'Created NutritionPlan (uuid={payload["id"]}) for user {user_id}')+ return None+ logger.warning(f'PowerSync nutritional plan create validation failed: {serializer.errors}')+ return {'error': 'Validation failed', 'details': serializer.errors}+++def handle_update_plan(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PATCH event for a nutritional plan."""logger.debug(f'Received PowerSync payload for nutritional plan update: {payload}')try:- entry = NutritionPlan.objects.get(pk=payload['id'], user_id=user_id)+ entry = NutritionPlan.objects.get(uuid=payload['id'], user_id=user_id)except NutritionPlan.DoesNotExist:logger.warning(- f'NutritionPlan with id {payload["id"]} and user {user_id} not found for update.'+ f'NutritionPlan with uuid {payload["id"]} and user {user_id} not found for update.')return {'error': 'Not found',- 'details': f'NutritionPlan with id {payload["id"]} not found',+ 'details': f'NutritionPlan with uuid {payload["id"]} not found',}if not check_fk_ownership(payload, NutritionPlanViewSet.get_owner_objects(), user_id):return {'error': 'Forbidden', 'details': 'NutritionPlan references an object you do not own'}+ payload.pop('id', None)serializer = NutritionPlanSerializer(entry, data=payload, partial=True)if serializer.is_valid():serializer.save()- logger.info(f'Updated NutritionPlan {entry.pk} for user {user_id}')+ logger.info(f'Updated NutritionPlan {entry.pk} (uuid={entry.uuid}) for user {user_id}')return Nonelogger.warning(f'PowerSync nutritional plan update validation failed: {serializer.errors}')return {'error': 'Validation failed', 'details': serializer.errors}def handle_delete_plan(payload: dict[str, Any], user_id: int) -> dict | None:- """- Handle a PowerSync DELETE event for a nutritional plan.+ """Handle a PowerSync DELETE event for a nutritional plan.Django's FK CASCADE removes all dependent meals, meal items and diarylog entries in the same transaction."""logger.debug(f'Received PowerSync payload for nutritional plan delete: {payload}')try:- entry = NutritionPlan.objects.get(pk=payload['id'], user_id=user_id)+ entry = NutritionPlan.objects.get(uuid=payload['id'], user_id=user_id)except NutritionPlan.DoesNotExist:- logger.warning(f'NutritionPlan with id {payload["id"]} not found for delete.')+ logger.warning(f'NutritionPlan with uuid {payload["id"]} not found for delete.')return {'error': 'Not found',- 'details': f'NutritionPlan with id {payload["id"]} not found',+ 'details': f'NutritionPlan with uuid {payload["id"]} not found',}entry.delete()- logger.info(f'Deleted NutritionPlan {payload["id"]} for user {user_id}')+ logger.info(f'Deleted NutritionPlan (uuid={payload["id"]}) for user {user_id}')+ return None+++#+# Meals+#+++def handle_create_meal(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PUT event for a meal.++ The client generates the row's UUID; the parent plan is referenced by UUID+ too and resolved here. The `order` field is set to whatever the client+ computed (or 1 by default, matching the existing REST `perform_create`).+ """+ logger.debug(f'Received PowerSync payload for meal create: {payload}')++ error = resolve_uuid_fk(payload, 'plan', NutritionPlan)+ if error:+ return error++ if not check_fk_ownership(payload, MealViewSet.get_owner_objects(), user_id):+ return {'error': 'Forbidden', 'details': 'Meal references an object you do not own'}++ serializer = MealSerializer(data=payload)+ if serializer.is_valid():+ serializer.save(uuid=payload['id'], order=payload.get('order', 1))+ logger.info(f'Created Meal (uuid={payload["id"]}) for user {user_id}')+ return None+ logger.warning(f'PowerSync meal create validation failed: {serializer.errors}')+ return {'error': 'Validation failed', 'details': serializer.errors}+++def handle_update_meal(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PATCH event for a meal."""+ logger.debug(f'Received PowerSync payload for meal update: {payload}')+ try:+ entry = Meal.objects.get(uuid=payload['id'], plan__user_id=user_id)+ except Meal.DoesNotExist:+ logger.warning(+ f'Meal with uuid {payload["id"]} and user {user_id} not found for update.'+ )+ return {'error': 'Not found', 'details': f'Meal with uuid {payload["id"]} not found'}++ error = resolve_uuid_fk(payload, 'plan', NutritionPlan)+ if error:+ return error++ if not check_fk_ownership(payload, MealViewSet.get_owner_objects(), user_id):+ return {'error': 'Forbidden', 'details': 'Meal references an object you do not own'}++ payload.pop('id', None)+ serializer = MealSerializer(entry, data=payload, partial=True)+ if serializer.is_valid():+ serializer.save()+ logger.info(f'Updated Meal {entry.pk} (uuid={entry.uuid}) for user {user_id}')+ return None+ logger.warning(f'PowerSync meal update validation failed: {serializer.errors}')+ return {'error': 'Validation failed', 'details': serializer.errors}+++def handle_delete_meal(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync DELETE event for a meal.++ Django's FK CASCADE removes all dependent meal items in the same transaction.+ """+ logger.debug(f'Received PowerSync payload for meal delete: {payload}')+ try:+ entry = Meal.objects.get(uuid=payload['id'], plan__user_id=user_id)+ except Meal.DoesNotExist:+ logger.warning(f'Meal with uuid {payload["id"]} not found for delete.')+ return {'error': 'Not found', 'details': f'Meal with uuid {payload["id"]} not found'}+ entry.delete()+ logger.info(f'Deleted Meal (uuid={payload["id"]}) for user {user_id}')return None++#+# Meal items+#+++def handle_create_mealitem(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PUT event for a meal item.++ The client generates the UUID and references its parent meal by UUID; the+ helper resolves that UUID to the integer FK before the serializer runs.+ """+ logger.debug(f'Received PowerSync payload for meal item create: {payload}')++ error = resolve_uuid_fk(payload, 'meal', Meal)+ if error:+ return error++ if not check_fk_ownership(payload, MealItemViewSet.get_owner_objects(), user_id):+ return {'error': 'Forbidden', 'details': 'MealItem references an object you do not own'}++ serializer = MealItemSerializer(data=payload)+ if serializer.is_valid():+ serializer.save(uuid=payload['id'], order=payload.get('order', 1))+ logger.info(f'Created MealItem (uuid={payload["id"]}) for user {user_id}')+ return None+ logger.warning(f'PowerSync meal item create validation failed: {serializer.errors}')+ return {'error': 'Validation failed', 'details': serializer.errors}+++def handle_update_mealitem(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync PATCH event for a meal item."""+ logger.debug(f'Received PowerSync payload for meal item update: {payload}')+ try:+ entry = MealItem.objects.get(uuid=payload['id'], meal__plan__user_id=user_id)+ except MealItem.DoesNotExist:+ logger.warning(+ f'MealItem with uuid {payload["id"]} and user {user_id} not found for update.'+ )+ return {'error': 'Not found', 'details': f'MealItem with uuid {payload["id"]} not found'}++ error = resolve_uuid_fk(payload, 'meal', Meal)+ if error:+ return error++ if not check_fk_ownership(payload, MealItemViewSet.get_owner_objects(), user_id):+ return {'error': 'Forbidden', 'details': 'MealItem references an object you do not own'}++ payload.pop('id', None)+ serializer = MealItemSerializer(entry, data=payload, partial=True)+ if serializer.is_valid():+ serializer.save()+ logger.info(f'Updated MealItem {entry.pk} (uuid={entry.uuid}) for user {user_id}')+ return None+ logger.warning(f'PowerSync meal item update validation failed: {serializer.errors}')+ return {'error': 'Validation failed', 'details': serializer.errors}+++def handle_delete_mealitem(payload: dict[str, Any], user_id: int) -> dict | None:+ """Handle a PowerSync DELETE event for a meal item."""+ logger.debug(f'Received PowerSync payload for meal item delete: {payload}')+ try:+ entry = MealItem.objects.get(uuid=payload['id'], meal__plan__user_id=user_id)+ except MealItem.DoesNotExist:+ logger.warning(f'MealItem with uuid {payload["id"]} not found for delete.')+ return {'error': 'Not found', 'details': f'MealItem with uuid {payload["id"]} not found'}+ entry.delete()+ logger.info(f'Deleted MealItem (uuid={payload["id"]}) for user {user_id}')+ return None++## Log items (nutrition diary)#+def handle_create_log(payload: dict[str, Any], user_id: int) -> dict | None:- """Handle a PowerSync PUT event for a diary log entry."""+ """Handle a PowerSync PUT event for a diary log entry.++ Plan and meal FKs both arrive as UUID strings and are resolved to integer+ PKs before validation.+ """logger.debug(f'Received PowerSync payload for log create: {payload}')+ error = resolve_uuid_fk(payload, 'plan', NutritionPlan)+ if error:+ return error+ error = resolve_uuid_fk(payload, 'meal', Meal)+ if error:+ return error+if not check_fk_ownership(payload, LogItemViewSet.get_owner_objects(), user_id):return {'error': 'Forbidden', 'details': 'LogItem references an object you do not own'}@@ -118,10 +300,16 @@ def handle_update_log(payload: dict[str, Any], user_id: int) -> dict | None:)return {'error': 'Not found', 'details': f'LogItem with uuid {payload["id"]} not found'}+ error = resolve_uuid_fk(payload, 'plan', NutritionPlan)+ if error:+ return error+ error = resolve_uuid_fk(payload, 'meal', Meal)+ if error:+ return error+if not check_fk_ownership(payload, LogItemViewSet.get_owner_objects(), user_id):return {'error': 'Forbidden', 'details': 'LogItem references an object you do not own'}- # Drop 'id' from the patch, the row is already resolved by uuid abovepayload.pop('id', None)serializer = LogItemSerializer(entry, data=payload, partial=True)if serializer.is_valid():diff --git a/wger/nutrition/tests/test_plan.py b/wger/nutrition/tests/test_plan.pyindex e10e321ce..88708ff5f 100644--- a/wger/nutrition/tests/test_plan.py+++ b/wger/nutrition/tests/test_plan.py@@ -53,23 +53,26 @@ class PlanCopyTestCase(WgerTestCase):copied_plan_pk = int(resolve(response.url).kwargs['id'])copied_plan = NutritionPlan.objects.get(pk=copied_plan_pk)- # Convert plans to dictionaries and compare- orig_plan_dict = model_to_dict(orig_plan, exclude=['id'])- copied_plan_dict = model_to_dict(copied_plan, exclude=['id'])+ # Convert plans to dictionaries and compare. The copy gets a fresh+ # uuid (PowerSync row identity), so we exclude it alongside the pk.+ orig_plan_dict = model_to_dict(orig_plan, exclude=['id', 'uuid'])+ copied_plan_dict = model_to_dict(copied_plan, exclude=['id', 'uuid'])self.assertEqual(orig_plan_dict, copied_plan_dict)orig_plan_meals = orig_plan.meal_set.all()copied_plan_meals = copied_plan.meal_set.all()for orig_meal, copied_meal in zip(orig_plan_meals, copied_plan_meals):- orig_meal_dict = model_to_dict(orig_meal, exclude=['id', 'plan'])- copied_meal_dict = model_to_dict(copied_meal, exclude=['id', 'plan'])+ orig_meal_dict = model_to_dict(orig_meal, exclude=['id', 'uuid', 'plan'])+ copied_meal_dict = model_to_dict(copied_meal, exclude=['id', 'uuid', 'plan'])self.assertEqual(orig_meal_dict, copied_meal_dict)+ self.assertNotEqual(orig_meal.uuid, copied_meal.uuid)orig_meal_items = orig_meal.mealitem_set.all()copied_meal_items = copied_meal.mealitem_set.all()for orig_meal_item, copied_meal_item in zip(orig_meal_items, copied_meal_items):- orig_meal_item_dict = model_to_dict(orig_meal_item, exclude=['id', 'meal'])- copied_meal_item_dict = model_to_dict(copied_meal_item, exclude=['id', 'meal'])- self.assertEqual(orig_meal_item_dict, copied_meal_item_dict)+ orig_dict = model_to_dict(orig_meal_item, exclude=['id', 'uuid', 'meal'])+ copied_dict = model_to_dict(copied_meal_item, exclude=['id', 'uuid', 'meal'])+ self.assertEqual(orig_dict, copied_dict)+ self.assertNotEqual(orig_meal_item.uuid, copied_meal_item.uuid)diff --git a/wger/nutrition/tests/test_powersync.py b/wger/nutrition/tests/test_powersync.pyindex b57a8e438..1e03b576b 100644--- a/wger/nutrition/tests/test_powersync.py+++ b/wger/nutrition/tests/test_powersync.py@@ -16,13 +16,19 @@from wger.core.tests import powersync_base_testfrom wger.nutrition.models import (LogItem,+ Meal,+ MealItem,NutritionPlan,)-# Pinned in test-nutrition-data.json-PLAN_OWNED = 1 # user 'test'-PLAN_OTHER = 2 # user 'admin'+# Pinned in test-nutrition-data.json (uuid field on the matching pk)+PLAN_OWNED_UUID = 'cc000000-0000-0000-0000-000000000001' # user 'test'+PLAN_OTHER_UUID = 'cc000000-0000-0000-0000-000000000002' # user 'admin'+MEAL_OWNED_UUID = 'aa000000-0000-0000-0000-000000000001'+MEAL_OTHER_UUID = 'aa000000-0000-0000-0000-000000000003'+MEAL_ITEM_OWNED_UUID = 'bb000000-0000-0000-0000-000000000001'+MEAL_ITEM_OTHER_UUID = 'bb000000-0000-0000-0000-000000000004'# Pinned in test-nutrition-diary.json (linked to PLAN_OWNED)LOG_OWNED_UUID = 'ee000000-0000-0000-0000-000000000001'@@ -30,35 +36,110 @@ LOG_OWNED_UUID = 'ee000000-0000-0000-0000-000000000001'INGREDIENT_PUBLIC = 1-class NutritionPlanPowerSyncTestCase(- powersync_base_test.PowerSyncBaseTestCase,- powersync_base_test.PowerSyncCreateNotAllowedTestCase,- powersync_base_test.PowerSyncUpdateTestCase,- powersync_base_test.PowerSyncDeleteTestCase,-):+class NutritionPlanPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):"""- PowerSync handlers for nutrition.NutritionPlan. Creation must go through- REST (the dispatcher rejects PUT), so only PATCH/DELETE are tested.+ PowerSync handlers for nutrition.NutritionPlan. Full CRUD via PowerSync —+ the handler keys rows by uuid (Pattern A)."""table = 'nutrition_nutritionplan'resource = NutritionPlan- pk_owned = PLAN_OWNED+ pk_owned = PLAN_OWNED_UUIDupdate_payload = {'id': pk_owned,'description': 'Renamed via PowerSync',}- create_payload = {'id': 9999, 'description': 'should not be created'}+ create_payload = {+ 'id': 'cc000000-0000-0000-0000-000000000099',+ 'description': 'created via PowerSync',+ 'creation_date': '2030-01-15',+ 'start': '2030-01-15',+ 'end': None,+ 'only_logging': False,+ 'has_goal_calories': False,+ 'goal_energy': None,+ 'goal_protein': None,+ 'goal_carbohydrates': None,+ 'goal_fat': None,+ 'goal_fiber': None,+ }++ def _get_entry_for_update(self):+ return NutritionPlan.objects.get(uuid=self.update_payload['id'])+++class MealPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):+ """+ PowerSync handlers for nutrition.Meal. Full CRUD via PowerSync — the+ handler keys rows by uuid; the `plan` FK in the payload is a uuid string+ that the handler resolves to the integer PK before saving.+ """++ table = 'nutrition_meal'+ resource = Meal++ pk_owned = MEAL_OWNED_UUID++ update_payload = {+ 'id': pk_owned,+ 'name': 'Renamed via PowerSync',+ }++ create_payload = {+ 'id': 'aa000000-0000-0000-0000-000000000099',+ 'plan': PLAN_OWNED_UUID,+ 'name': 'created via PowerSync',+ }++ fk_ownership = (+ ('plan', PLAN_OTHER_UUID),+ )++ def _get_entry_for_update(self):+ return Meal.objects.get(uuid=self.update_payload['id'])+++class MealItemPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):+ """+ PowerSync handlers for nutrition.MealItem. Full CRUD via PowerSync — the+ handler keys rows by uuid; the `meal` FK in the payload is a uuid string+ that the handler resolves to the integer PK before saving.+ """++ table = 'nutrition_mealitem'+ resource = MealItem++ pk_owned = MEAL_ITEM_OWNED_UUID++ update_payload = {+ 'id': pk_owned,+ 'amount': '99',+ }++ create_payload = {+ 'id': 'bb000000-0000-0000-0000-000000000099',+ 'meal': MEAL_OWNED_UUID,+ 'ingredient': INGREDIENT_PUBLIC,+ 'amount': '50',+ }++ fk_ownership = (+ ('meal', MEAL_OTHER_UUID),+ )++ def _get_entry_for_update(self):+ return MealItem.objects.get(uuid=self.update_payload['id'])class LogItemPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):"""PowerSync handlers for nutrition.LogItem. The handler runscheck_fk_ownership against (NutritionPlan, 'plan') and (Meal, 'meal').- Lookup uses the uuid field, not the integer pk.+ Lookup uses the uuid field; the `plan` and `meal` FKs in the payload are+ uuid strings that the handler resolves to the integer PKs before saving."""table = 'nutrition_logitem'@@ -68,7 +149,7 @@ class LogItemPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):create_payload = {'id': 'ee000000-0000-0000-0000-000000000099',- 'plan': PLAN_OWNED,+ 'plan': PLAN_OWNED_UUID,'datetime': '2030-01-15T10:00:00Z','ingredient': INGREDIENT_PUBLIC,'amount': '50',@@ -79,7 +160,7 @@ class LogItemPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):}fk_ownership = (- ('plan', PLAN_OTHER),+ ('plan', PLAN_OTHER_UUID),)def _get_entry_for_update(self):diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.pyindex cf0c3d108..755abaef6 100644--- a/wger/nutrition/views/plan.py+++ b/wger/nutrition/views/plan.py@@ -70,9 +70,12 @@ def copy(request, pk):"""orig_plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user)- # Convert the original plan to a dictionary and remove the primary key+ # Convert the original plan to a dictionary and remove the primary key.+ # uuid is editable so the copy gets a fresh one (otherwise we'd collide+ # with the original plan's uuid).plan_data = model_to_dict(orig_plan)plan_data.pop('id')+ plan_data.pop('uuid', None)plan_copy = NutritionPlan.objects.create(user=request.user, **plan_data)@@ -81,6 +84,9 @@ def copy(request, pk):for orig_meal in orig_meals:meal_data = model_to_dict(orig_meal)meal_data.pop('id')+ # uuid is editable so the copy gets a fresh one (otherwise we'd+ # collide with the original meal's uuid)+ meal_data.pop('uuid', None)meal_data['plan'] = plan_copy# setting manually due to "editable" Falsemeal_data['order'] = orig_meal.order@@ -91,6 +97,7 @@ def copy(request, pk):for orig_meal_item in orig_meal_items:meal_item_data = model_to_dict(orig_meal_item)meal_item_data.pop('id')+ meal_item_data.pop('uuid', None)meal_item_data.pop('ingredient')meal_item_data['meal'] = meal_copymeal_item_data['ingredient_id'] = orig_meal_item.ingredient_id