You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
2.0 KiB

  1. from django.db import IntegrityError
  2. from django_filters.rest_framework import DjangoFilterBackend
  3. from rest_framework import generics, status
  4. from rest_framework.permissions import IsAuthenticated
  5. from rest_framework.response import Response
  6. from .permissions import IsProjectAdmin
  7. from .serializers import MemberSerializer
  8. from .exceptions import RoleAlreadyAssignedException, RoleConstraintException
  9. from .models import Member
  10. class MemberList(generics.ListCreateAPIView):
  11. filter_backends = [DjangoFilterBackend]
  12. filterset_fields = ['user']
  13. queryset = Member.objects.all()
  14. serializer_class = MemberSerializer
  15. pagination_class = None
  16. permission_classes = [IsAuthenticated & IsProjectAdmin]
  17. def filter_queryset(self, queryset):
  18. queryset = queryset.filter(project=self.kwargs['project_id'])
  19. return super().filter_queryset(queryset)
  20. def perform_create(self, serializer):
  21. try:
  22. serializer.save(project_id=self.kwargs['project_id'])
  23. except IntegrityError:
  24. raise RoleAlreadyAssignedException
  25. def delete(self, request, *args, **kwargs):
  26. delete_ids = request.data['ids']
  27. project_id = self.kwargs['project_id']
  28. Member.objects.filter(project=project_id, pk__in=delete_ids)\
  29. .exclude(user=self.request.user)\
  30. .delete()
  31. return Response(status=status.HTTP_204_NO_CONTENT)
  32. class MemberDetail(generics.RetrieveUpdateAPIView):
  33. queryset = Member.objects.all()
  34. serializer_class = MemberSerializer
  35. lookup_url_kwarg = 'member_id'
  36. permission_classes = [IsAuthenticated & IsProjectAdmin]
  37. def perform_update(self, serializer):
  38. project_id = self.kwargs['project_id']
  39. member_id = self.kwargs['member_id']
  40. role = serializer.validated_data['role']
  41. if not Member.objects.can_update(project_id, member_id, role.name):
  42. raise RoleConstraintException
  43. try:
  44. super().perform_update(serializer)
  45. except IntegrityError:
  46. raise RoleAlreadyAssignedException