From d3297d5b1fa2c366bb5490ca550d268facbfb492 Mon Sep 17 00:00:00 2001 From: Adibov Date: Tue, 5 Dec 2023 00:45:05 +0330 Subject: [PATCH] fix(backend): check user duplicate discount usage for approved payments --- backend/backend_api/admin.py | 2 +- backend/backend_api/models.py | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/backend/backend_api/admin.py b/backend/backend_api/admin.py index 9189618..f3919bf 100644 --- a/backend/backend_api/admin.py +++ b/backend/backend_api/admin.py @@ -103,7 +103,7 @@ def execute_mailer(self, request, obj): class DiscountAdmin(admin.ModelAdmin): - list_display = ('__str__', 'is_active', 'discount_percent', 'capacity', 'expiration_date') + list_display = ('__str__', 'is_active', 'discount_percent', 'capacity', 'remaining_capacity', 'expiration_date') readonly_fields = ('participants',) class Meta: diff --git a/backend/backend_api/models.py b/backend/backend_api/models.py index 47f033b..726e7f1 100644 --- a/backend/backend_api/models.py +++ b/backend/backend_api/models.py @@ -362,20 +362,21 @@ def participants(self): users.append(payment.user) return users - def _remaining_capacity(self) -> int: + @property + def remaining_capacity(self) -> int: return self.capacity - self.payment_set.filter(status=Payment.PaymentStatus.PAYMENT_CONFIRMED).count() def is_usable(self, user: User) -> bool: if not self.is_active: raise ValidationError(new_detailed_response(status.HTTP_400_BAD_REQUEST, "Discount is not active")) - if self._remaining_capacity() <= 0: + if self.remaining_capacity <= 0: raise ValidationError(new_detailed_response(status.HTTP_400_BAD_REQUEST, "Discount capacity is full")) if self.expiration_date < timezone.now(): raise ValidationError(new_detailed_response(status.HTTP_400_BAD_REQUEST, "Discount has expired")) - if self.payment_set.filter(user=user).exists(): + if self.payment_set.filter(user=user, status=Payment.PaymentStatus.PAYMENT_CONFIRMED).exists(): raise ValidationError(new_detailed_response(status.HTTP_400_BAD_REQUEST, "Discount has already been used by this user")) return True