views.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from rest_framework import exceptions, viewsets
  2. from rest_framework.decorators import action
  3. from rest_framework.response import Response
  4. from apps.projects.models import UserProjectAlert
  5. from .models import User
  6. from .serializers import (
  7. CurrentUserSerializer,
  8. UserSerializer,
  9. )
  10. class UserViewSet(viewsets.ReadOnlyModelViewSet):
  11. queryset = User.objects.all()
  12. serializer_class = UserSerializer
  13. def get_queryset(self):
  14. queryset = super().get_queryset()
  15. organization_slug = self.kwargs.get("organization_slug")
  16. if organization_slug:
  17. queryset = queryset.filter(
  18. organizations_ext_organization__slug=organization_slug,
  19. organizations_ext_organization__users=self.request.user,
  20. )
  21. else:
  22. queryset = queryset.filter(id=self.request.user.id)
  23. return queryset
  24. def get_object(self):
  25. if self.kwargs.get("pk") == "me":
  26. return self.request.user
  27. return super().get_object()
  28. def get_serializer_class(self):
  29. if self.kwargs.get("pk") == "me":
  30. return CurrentUserSerializer
  31. return super().get_serializer_class()
  32. @action(
  33. detail=True, methods=["get", "post", "put"], url_path="notifications/alerts"
  34. )
  35. def alerts(self, request, pk=None):
  36. """
  37. Returns dictionary of project_id: status. Now project_id status means it's "default"
  38. To update, submit `{project_id: status}` where status is -1 (default), 0, or 1
  39. """
  40. user = self.get_object()
  41. alerts = user.userprojectalert_set.all()
  42. if request.method == "GET":
  43. data = {}
  44. for alert in alerts:
  45. data[alert.project_id] = alert.status
  46. return Response(data)
  47. data = request.data
  48. try:
  49. items = [x for x in data.items()]
  50. except AttributeError as err:
  51. raise exceptions.ValidationError(
  52. "Invalid alert format, expected dictionary"
  53. ) from err
  54. if len(data) != 1:
  55. raise exceptions.ValidationError("Invalid alert format, expected one value")
  56. project_id, alert_status = items[0]
  57. if alert_status not in [1, 0, -1]:
  58. raise exceptions.ValidationError("Invalid status, must be -1, 0, or 1")
  59. alert = alerts.filter(project_id=project_id).first()
  60. if alert and alert_status == -1:
  61. alert.delete()
  62. else:
  63. UserProjectAlert.objects.update_or_create(
  64. user=user, project_id=project_id, defaults={"status": alert_status}
  65. )
  66. return Response(status=204)