Skip to content

Commit

Permalink
refactor: Доделал отображение для владельца или для участника, для за…
Browse files Browse the repository at this point in the history
…явок
  • Loading branch information
Denis-Shtanskiy committed Nov 3, 2024
1 parent 2c67f78 commit 1518f39
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 22 deletions.
2 changes: 1 addition & 1 deletion src/backend/api/v1/general/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class CounterApiView(generics.RetrieveAPIView):
"""Представление счетчика проектов и пользователей."""

@method_decorator(cache_page(600))
def get(self, request):
def get(self, request) -> Response:
with connection.cursor() as cursor:
cursor.execute(
"""
Expand Down
2 changes: 1 addition & 1 deletion src/backend/api/v1/profile/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class Meta(BaseProfileSerializer.Meta):
)
read_only_fields = fields

def get_is_favorite(self, profile):
def get_is_favorite(self, profile) -> bool:
user = self.context["request"].user
return (
user.is_authenticated
Expand Down
6 changes: 3 additions & 3 deletions src/backend/api/v1/projects/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def get_is_favorite(self, project) -> bool:
return project.favorited_by.filter(id=user.id).exists()
return False

def get_owner(self, project):
def get_owner(self, project) -> dict[str, Any]:
"""Метод возвращает требуемые поля для владельца."""
owner = project.owner
return {
Expand All @@ -173,7 +173,7 @@ def get_owner(self, project):
"visible_status": owner.profile.visible_status,
}

def get_unique_project_participants_skills(self, obj):
def get_unique_project_participants_skills(self, obj) -> list[Any]:
all_skills = chain.from_iterable(
[
participant.skills.values_list("name", flat=True)
Expand Down Expand Up @@ -368,7 +368,7 @@ class Meta:
"project",
)

def get_position(self, obj):
def get_position(self, obj) -> str:
"""Метод получения specialization из ProfessionSerializer."""
return ProfessionSerializer(obj.position.profession).data[
"specialization"
Expand Down
50 changes: 33 additions & 17 deletions src/backend/api/v1/projects/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser
from django.db.models import Prefetch, Q, QuerySet
from django.db.models.manager import BaseManager
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view
from drf_spectacular.utils import (
OpenApiParameter,
extend_schema,
extend_schema_view,
)
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.permissions import SAFE_METHODS, AllowAny, IsAuthenticated
Expand Down Expand Up @@ -282,6 +288,20 @@ class ProjectSpecialistsViewSet(

@extend_schema_view(
retrieve=extend_schema(exclude=True),
list=extend_schema(
parameters=[
OpenApiParameter(
"role",
type=str,
description="Роль пользователя: owner или participant",
required=True,
enum=[
"owner",
"participant",
], # Ограничение на допустимые значения
)
]
),
)
class ProjectParticipationRequestsViewSet(ModelViewSet):
"""Представление для запросов на участие в проекте."""
Expand All @@ -297,6 +317,8 @@ class ProjectParticipationRequestsViewSet(ModelViewSet):
def get_queryset(self) -> QuerySet["ParticipationRequest"]:
"""Метод получения queryset-а для запросов на участие в проекте."""

user = self.request.user
role = self.request.query_params.get("role")
queryset = (
super()
.get_queryset()
Expand All @@ -312,20 +334,18 @@ def get_queryset(self) -> QuerySet["ParticipationRequest"]:
).prefetch_related(
"project__directions",
)
user = self.request.user
if (
queryset.filter(project__owner=user).exists()
or queryset.filter(project__creator=user).exists()
):
queryset = queryset.exclude(
if role == "owner":
queryset = queryset.filter(
Q(project__owner=user) | Q(project__creator=user)
).exclude(
request_status__in=[
RequestStatuses.ACCEPTED,
RequestStatuses.REJECTED,
]
)
queryset.filter(is_viewed=False).update(is_viewed=True)
return queryset
return queryset.filter(Q(user=self.request.user)).only(
return queryset.filter(Q(user=user)).only(
*PROJECT_PARTICIPATION_REQUEST_ONLY_FIELDS.get(self.action, ())
)

Expand All @@ -351,13 +371,9 @@ def get_queryset(self) -> QuerySet["ParticipationRequest"]:

def get_serializer_class(self) -> type[BaseSerializer]:
"""Метод получения сериализатора для запросов на участие в проекте."""

is_owner = any(
self.request.user in (pr.project.owner, pr.project.creator)
for pr in self.get_queryset()
)
role = self.request.query_params.get("role")
if self.request.method in SAFE_METHODS:
if is_owner:
if role == "owner":
return ReadListParticipationRequestSerializer
return MyRequestsSerializer
return WriteParticipationRequestSerializer
Expand All @@ -384,7 +400,7 @@ def answer(self, request, pk) -> Response:
"""Метод ответа на запрос на участие в проекте."""

participation_request = self.get_object()
serializer = self.serializer_class(
serializer = self.get_serializer(
instance=participation_request,
data=request.data,
context=self.get_serializer_context(),
Expand All @@ -401,8 +417,8 @@ class InvitationToProjectViewSet(ModelViewSet):
http_method_names = ("get", "post", "patch", "delete", "options")
permission_classes = (IsInvitationAuthorOrUser,)

def get_queryset(self):
user = self.request.user
def get_queryset(self) -> BaseManager[InvitationToProject]:
user: AbstractBaseUser | AnonymousUser = self.request.user
return (
InvitationToProject.objects.filter(Q(user=user) | Q(author=user))
.order_by("-created")
Expand Down

0 comments on commit 1518f39

Please sign in to comment.