Add coupon redemption with one-per-user limit

Python · Django · advanced · modification

Coupon redemption: the user POSTs a coupon code, the handler checks they haven't already redeemed it, and records the redemption. Tested by redeeming a few codes sequentially — the duplicate check fires correctly and redemption counts add up.

The coupon endpoint is public to any authenticated user. During a flash sale thousands of users may attempt to redeem the same popular code within seconds. The application runs on PostgreSQL behind a WSGI server with multiple worker processes, so requests are truly concurrent.

Requirements

Files touched

--- coupons/models.py
+from django.conf import settings
+from django.db import models
+
+
+class Coupon(models.Model):
+    code = models.CharField(max_length=50, unique=True)
+    description = models.TextField(blank=True)
+    discount_percent = models.PositiveSmallIntegerField(default=10)
+    is_active = models.BooleanField(default=True)
+    created_at = models.DateTimeField(auto_now_add=True)
+
+    def __str__(self):
+        return self.code
+
+
+class Redemption(models.Model):
+    user = models.ForeignKey(
+        settings.AUTH_USER_MODEL,
+        on_delete=models.CASCADE,
+        related_name='redemptions',
+    )
+    coupon = models.ForeignKey(
+        Coupon,
+        on_delete=models.CASCADE,
+        related_name='redemptions',
+    )
+    redeemed_at = models.DateTimeField(auto_now_add=True)
+
+    class Meta:

Review this PR

Python practice