Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change method destroy, fix status for incomes #246

Merged
merged 1 commit into from
Nov 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions backend/api/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,13 @@ class StatusProjectFilter(django_filters.FilterSet):
# moderation = django_filters.CharFilter(method='filter_moderation')
# is_favorited = django_filters.CharFilter(method='filter_is_favorited')

# draft = django_filters.BooleanFilter(method='filter_draft')
# active = django_filters.BooleanFilter(method='filter_active')
# completed = django_filters.BooleanFilter(method='filter_completed')
# archive = django_filters.BooleanFilter(method='filter_archive')
# moderation = django_filters.BooleanFilter(method='filter_moderation')
# is_favorited = django_filters.BooleanFilter(method='filter_is_favorited')

def filter_draft(self, queryset):
"""
Фильтр для таба "Черновик".
Expand All @@ -137,6 +144,20 @@ def filter_draft(self, queryset):
Q(status_approve__in=[Project.EDITING, Project.REJECTED,]),
organization__contact_person=self.request.user
)
# вариант если чтобы фильтровался на 'true'
# def filter_draft(self, queryset, name, value):
# """
# Фильтр для таба "Черновик".
# """
# if value == 'true':
# return queryset.filter(
# Q(status_approve__in=[Project.EDITING, Project.REJECTED,]),
# organization__contact_person=self.request.user
# )
# else:
# return HttpResponseBadRequest('Неверно указан фильтр')
# # queryset = None
# # return queryset

def filter_active(self, queryset):
"""
Expand Down Expand Up @@ -266,6 +287,7 @@ def filter_queryset(self, queryset):

if status_filter:
queryset = status_filter(queryset).distinct()
# queryset = status_filter(queryset, name, value).distinct()

return queryset

Expand Down
74 changes: 45 additions & 29 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,11 +684,22 @@ def create(self, validated_data):
"""
Создает заявку волонтера.
"""
project = validated_data['project']

project = validated_data.get('project')
# project = validated_data['project']
volunteer = self.context['request'].user.volunteers
status_incomes = validated_data.get(
'status_incomes', ProjectIncomes.APPLICATION_SUBMITTED
)
if not (
project.status_approve == Project.APPROVED and
(project.start_date_application < timezone.now()
< project.end_date_application)
):
raise serializers.ValidationError(
'Нельзя подать заявку на проект, '
'к которому не открыта подача заявок.'
)
if (
project.project_incomes.filter(volunteer=volunteer)
.exclude(status_incomes=ProjectIncomes.REJECTED).exists()
Expand All @@ -715,16 +726,16 @@ def create(self, validated_data):
)
return project_income

def delete(self, instance):
"""
Удаляет заявку волонтера только если статус APPLICATION_SUBMITTED.
"""
if instance.status_incomes == ProjectIncomes.APPLICATION_SUBMITTED:
instance.delete()
return 'Заявка волонтера удалена.'
raise serializers.ValidationError(
'Невозможно удалить заявку, если статус не "Заявка подана".'
)
# def delete(self, instance):
# """
# Удаляет заявку волонтера только если статус APPLICATION_SUBMITTED.
# """
# if instance.status_incomes == ProjectIncomes.APPLICATION_SUBMITTED:
# instance.delete()
# return 'Заявка волонтера удалена.'
# raise serializers.ValidationError(
# 'Невозможно удалить заявку, если статус не "Заявка подана".'
# )

def validate_status_incomes(self, value):
return validate_status_incomes(value)
Expand Down Expand Up @@ -754,29 +765,34 @@ def reject_incomes(self, instance):
"""
Отклоняет заявку волонтера.
"""
if instance.status_incomes == ProjectIncomes.REJECTED:
raise serializers.ValidationError('Вы уже отклоняли данную заявку')
instance.status_incomes = ProjectIncomes.REJECTED
instance.save()
return {'message': 'Заявка волонтера отклонена.'}

def to_representation(self, instance):
request = self.context.get('request')
user = request.user
if (
user.role == User.VOLUNTEER
and hasattr(user, 'volunteer')
and instance.volunteer != user.volunteer
):
return {}
if (
user.role == User.ORGANIZER
and instance.project.organizer != user.organizer
):
return {}
if user.role == User.ORGANIZER:
return super().to_representation(instance)
data = super().to_representation(instance)
# data['volunteer'] = {'id': instance.volunteer.id}
return data
return ProjectIncomesGetSerializer(instance).data

# def to_representation(self, instance):
# request = self.context.get('request')
# user = request.user
# if (
# user.role == User.VOLUNTEER
# and hasattr(user, 'volunteer')
# and instance.volunteer != user.volunteer
# ):
# return {}
# if (
# user.role == User.ORGANIZER
# and instance.project.organizer != user.organizer
# ):
# return {}
# if user.role == User.ORGANIZER:
# return super().to_representation(instance)
# data = super().to_representation(instance)
# # data['volunteer'] = {'id': instance.volunteer.id}
# return data


class OrganizationGetSerializer(serializers.ModelSerializer):
Expand Down
57 changes: 36 additions & 21 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ class ProjectIncomesViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
):
"""
Представление для заявок волонтеров в рамках проектов.
Expand All @@ -495,6 +496,8 @@ def get_queryset(self):
return ProjectIncomes.objects.filter(
project__organization__contact_person=user
)
if user.is_authenticated and user.is_volunteer:
return user.volunteers.project_incomes.all()

def get_serializer_class(self):
if self.request.method in SAFE_METHODS:
Expand All @@ -507,38 +510,50 @@ def get_permissions(self):
Метод для установки разрешений в зависимости от действия.
"""
permission_classes_by_action = {
'list': [IsOrganizerOfProject],
'list': [IsOrganizerOfProject | IsVolunteerOfIncomes],
'create': [IsVolunteer],
'accept_incomes': [IsOrganizerOfProject],
'reject_incomes': [IsOrganizerOfProject],
'delete_incomes': [IsVolunteerOfIncomes],
# 'delete_incomes': [IsVolunteerOfIncomes],
'destroy': [IsVolunteerOfIncomes],
'retrieve': [IsOrganizerOfProject | IsVolunteerOfIncomes],
}
permission_classes = permission_classes_by_action.get(
self.action, [IsOrganizerOfProject]
)
return [permission() for permission in permission_classes]
# добавлено попытка создать пользователя
# def perform_create(self, serializer):
# serializer.save(volunteer=self.request.user.volunteers)

@action(
detail=True,
methods=['delete'],
permission_classes=[IsVolunteerOfIncomes],
)
def delete_incomes(self, request, pk):
"""
Удаляет заявку волонтера на участие в проекте.

Parameters: pk (int): Идентификатор заявки волонтера.
Возвращает успешный ответ с сообщением о том, что заявка удалена.
Если удалить не получилось, возвращает исключение.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
response_data = serializer.delete(instance)
return Response(response_data, status=status.HTTP_200_OK)
if instance.status_incomes == ProjectIncomes.APPLICATION_SUBMITTED:
instance.delete()
return Response(
{'message': 'Заявка волонтера удалена.'},
status=status.HTTP_204_NO_CONTENT
)
return Response(
{'error': (
'Нельзя удалить заявку, если статус не "Заявка подана".'
)},
status=status.HTTP_400_BAD_REQUEST
)
# @action(
# detail=True,
# methods=['delete'],
# permission_classes=[IsVolunteerOfIncomes],
# )
# def delete_incomes(self, request, pk):
# """
# Удаляет заявку волонтера на участие в проекте.

# Parameters: pk (int): Идентификатор заявки волонтера.
# Возвращает успешный ответ с сообщением о том, что заявка удалена.
# Если удалить не получилось, возвращает исключение.
# """
# instance = self.get_object()
# serializer = self.get_serializer(instance)
# response_data = serializer.delete(instance)
# return Response(response_data, status=status.HTTP_200_OK)

@action(
detail=True,
Expand Down