Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Handle routine and nutritional plans edit operations

Roland Geider26a5dedb8911
diff --git a/wger/core/api/views.py b/wger/core/api/views.py
index 6bef31119..329372870 100644
--- a/wger/core/api/views.py
+++ b/wger/core/api/views.py
@@ -59,6 +59,7 @@ from rest_framework.response import Response
# wger
import wger.manager.powersync as ps_manager
import wger.measurements.powersync as ps_measurements
+import wger.nutrition.powersync as ps_nutrition
import wger.weight.powersync as ps_weight
from wger.core.api import powersync
from wger.core.api.serializers import (
@@ -560,6 +561,31 @@ def upload_powersync_data(request):
elif http_verb == 'DELETE':
result = ps_manager.handle_delete_session(payload=payload, user_id=user_id)
+ case 'manager_routine':
+ # Creation still goes through REST; only edit and delete reach us via PowerSync
+ if http_verb == 'PATCH':
+ result = ps_manager.handle_update_routine(payload=payload, user_id=user_id)
+ elif http_verb == 'DELETE':
+ result = ps_manager.handle_delete_routine(payload=payload, user_id=user_id)
+ elif http_verb == 'PUT':
+ result = {
+ 'error': 'Method not allowed',
+ 'details': 'Routine creation must go through the REST API',
+ }
+
+ # Nutrition
+ case 'nutrition_nutritionplan':
+ # Creation still goes through REST; only edit and delete reach us via PowerSync
+ if 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 _:
logger.warning(f'Received unknown PowerSync table: {table}')
return JsonResponse({'error': f'Unknown table: {table}'}, status=200)
diff --git a/wger/manager/powersync.py b/wger/manager/powersync.py
index fee19ab5f..8bda972cf 100644
--- a/wger/manager/powersync.py
+++ b/wger/manager/powersync.py
@@ -19,6 +19,7 @@ from typing import Any
# wger
from wger.manager.api.serializers import (
+ RoutineSerializer,
WorkoutLogSerializer,
WorkoutSessionSerializer,
)
@@ -27,6 +28,7 @@ from wger.manager.api.views import (
WorkoutSessionViewSet,
)
from wger.manager.models import (
+ Routine,
WorkoutLog,
WorkoutSession,
)
@@ -146,3 +148,52 @@ def handle_delete_session(payload: dict[str, Any], user_id: int) -> dict | None:
}
entry.delete()
return None
+
+
+def handle_update_routine(payload: dict[str, Any], user_id: int) -> dict | None:
+ """Handle a PowerSync PATCH event for a routine.
+
+ Creation still goes through REST (the backend assigns the integer PK and
+ `created` timestamp), so there is no `handle_create_routine` here — only
+ edit and delete are part of the PowerSync upload pipeline.
+ """
+ logger.debug(f'Received PowerSync payload for routine update: {payload}')
+ try:
+ entry = Routine.objects.get(pk=payload['id'], user_id=user_id)
+ except Routine.DoesNotExist:
+ logger.warning(
+ f'Routine with id {payload["id"]} and user {user_id} not found for update.'
+ )
+ return {
+ 'error': 'Not found',
+ 'details': f'Routine with id {payload["id"]} not found',
+ }
+
+ serializer = RoutineSerializer(entry, data=payload, partial=True)
+ if serializer.is_valid():
+ serializer.save()
+ logger.info(f'Updated Routine {entry.pk} for user {user_id}')
+ return None
+ logger.warning(f'PowerSync routine update validation failed: {serializer.errors}')
+ return {'error': 'Validation failed', 'details': serializer.errors}
+
+
+def handle_delete_routine(payload: dict[str, Any], user_id: int) -> dict | None:
+ """
+ Handle a PowerSync DELETE event for a routine.
+
+ Django's FK CASCADE removes all dependent days, slots, set configs,
+ sessions and logs in the same transaction.
+ """
+ logger.debug(f'Received PowerSync payload for routine delete: {payload}')
+ try:
+ entry = Routine.objects.get(pk=payload['id'], user_id=user_id)
+ except Routine.DoesNotExist:
+ logger.warning(f'Routine with id {payload["id"]} not found for delete.')
+ return {
+ 'error': 'Not found',
+ 'details': f'Routine with id {payload["id"]} not found',
+ }
+ entry.delete()
+ logger.info(f'Deleted Routine {payload["id"]} for user {user_id}')
+ return None
diff --git a/wger/nutrition/powersync.py b/wger/nutrition/powersync.py
new file mode 100644
index 000000000..c694c55c8
--- /dev/null
+++ b/wger/nutrition/powersync.py
@@ -0,0 +1,73 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+from typing import Any
+
+# wger
+from wger.nutrition.api.serializers import NutritionPlanSerializer
+from wger.nutrition.models import NutritionPlan
+
+
+logger = 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.
+
+ 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.
+ """
+ logger.debug(f'Received PowerSync payload for nutritional plan update: {payload}')
+ try:
+ entry = NutritionPlan.objects.get(pk=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.'
+ )
+ return {
+ 'error': 'Not found',
+ 'details': f'NutritionPlan with id {payload["id"]} not found',
+ }
+
+ serializer = NutritionPlanSerializer(entry, data=payload, partial=True)
+ if serializer.is_valid():
+ serializer.save()
+ logger.info(f'Updated NutritionPlan {entry.pk} for user {user_id}')
+ return None
+ logger.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.
+
+ Django's FK CASCADE removes all dependent meals, meal items and diary
+ log 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)
+ except NutritionPlan.DoesNotExist:
+ logger.warning(f'NutritionPlan with id {payload["id"]} not found for delete.')
+ return {
+ 'error': 'Not found',
+ 'details': f'NutritionPlan with id {payload["id"]} not found',
+ }
+ entry.delete()
+ logger.info(f'Deleted NutritionPlan {payload["id"]} for user {user_id}')
+ return None