Skip to content

Commit

Permalink
fix(backend): check user duplicate discount usage for approved payments
Browse files Browse the repository at this point in the history
  • Loading branch information
Adibov committed Dec 4, 2023
1 parent d809933 commit d3297d5
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
2 changes: 1 addition & 1 deletion backend/backend_api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 4 additions & 3 deletions backend/backend_api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d3297d5

Please sign in to comment.