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.

64 lines
2.4 KiB

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