Problem
Saleor standard allows either unlimited usages of a Voucher per email address or only once. Saleor isn´t able to limit voucher usages per email to e.g. 3x.
Solution
- Add new filed on the Voucher Model
- Create and run migration
- Add new error code for Checkout
- Add a function to allow adding voucher usage only if within the limit
- Verify user is within limits on using the voucher code
Add new filed on the Voucher Model
In the Voucher Model ( class Voucher(models.Model)) in file saleor/discount/models.py
Add this Line (rename the field if you need)
limit_per_unique_email = models.IntegerField(default=0)
That allows the admin to set the number of usages per email address.
| # class Meta: | |||
| unique_together = ((“voucher”, “customer_email”),) | # unique_together = ((“voucher”, “customer_email”),) |
comment out to reuse voucher usage table from saleor standard
Create and run migration
Create migration
When your stack is running execute this command to create the migration required:
python3 manage.py makemigrations
Assuming that you models and migrations are in sync and you worked cleanly with migrations you should now have one new migration file. You need to run it to apply the changes to your database.
Run migration
To run your migration execute:
python3 manage.py migrate
Depending on your setup this might run quickly or you can get yourself a cup of coffee.
Add new error code for Checkout
PROMOCODE_USAGE_LIMIT_REACHED = "promocode_usage_limit_reached"
file saleor/checkout/error_codes.py
part class CheckoutErrorCode(Enum)
Add a function to allow adding voucher usage only if within the limit
saleor/discount/utils.py
Verify user is within limits on using the voucher code
saleor/graphql/checkout/mutations.py
Let me know when it helped you.
Best,
Frank
Sources: