65 lines
2.5 KiB
Python
65 lines
2.5 KiB
Python
from rest_framework.decorators import api_view, permission_classes
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
from .models import GymProgram
|
|
from server.appointment.models import Appointment
|
|
from .serializers import GymProgramSerializer
|
|
from server.appointment.serializers import AppointmentSerializer
|
|
from server.user.models import User
|
|
|
|
|
|
@api_view(['GET', 'POST'])
|
|
def gym_program_list(request):
|
|
if request.method == 'GET':
|
|
gym_programs = GymProgram.objects.all()
|
|
serializer = GymProgramSerializer(gym_programs, many=True)
|
|
return Response(serializer.data)
|
|
|
|
elif request.method == 'POST':
|
|
serializer = GymProgramSerializer(data=request.data)
|
|
if serializer.is_valid():
|
|
serializer.save()
|
|
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
@api_view(['GET', 'PUT', 'DELETE'])
|
|
def gym_program_detail(request, pk):
|
|
gym_program = get_object_or_404(GymProgram, pk=pk)
|
|
|
|
if request.method == 'GET':
|
|
serializer = GymProgramSerializer(gym_program)
|
|
return Response(serializer.data)
|
|
|
|
elif request.method == 'PUT':
|
|
serializer = GymProgramSerializer(gym_program, data=request.data)
|
|
if serializer.is_valid():
|
|
serializer.save()
|
|
return Response(serializer.data)
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
elif request.method == 'DELETE':
|
|
gym_program.delete()
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
|
@api_view(['POST', 'DELETE'])
|
|
def manage_user_program(request, gym_program_pk, user_pk):
|
|
gym_program = get_object_or_404(GymProgram, pk=gym_program_pk)
|
|
user = get_object_or_404(User, pk=user_pk)
|
|
|
|
if request.method == 'POST':
|
|
if Appointment.objects.filter(user=user, gym_program=gym_program).exists():
|
|
return Response({"detail": "User is already part of the program."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
appointment = Appointment.objects.create(user=user, gym_program=gym_program)
|
|
serializer = AppointmentSerializer(appointment)
|
|
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
|
|
|
elif request.method == 'DELETE':
|
|
appointment = get_object_or_404(Appointment, gym_program=gym_program, user=user)
|
|
appointment.delete()
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|