You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abstract_models.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. from decimal import Decimal
  2. import datetime
  3. from django.core import exceptions
  4. from django.db import models
  5. from django.utils.translation import ugettext as _
  6. class AbstractVoucher(models.Model):
  7. """
  8. A voucher. This is simply a link to a collection of offers.
  9. Note that there are three possible "usage" models:
  10. (a) Single use
  11. (b) Multi-use
  12. (c) Once per customer
  13. """
  14. name = models.CharField(_("Name"), max_length=128,
  15. help_text=_("This will be shown in the checkout and basket "
  16. "once the voucher is entered"))
  17. code = models.CharField(_("Code"), max_length=128,
  18. db_index=True, unique=True,
  19. help_text=_("""Case insensitive / No spaces allowed"""))
  20. offers = models.ManyToManyField(
  21. 'offer.ConditionalOffer', related_name='vouchers',
  22. verbose_name=_("Offers"), limit_choices_to={'offer_type': "Voucher"})
  23. SINGLE_USE, MULTI_USE, ONCE_PER_CUSTOMER = (
  24. 'Single use', 'Multi-use', 'Once per customer')
  25. USAGE_CHOICES = (
  26. (SINGLE_USE, _("Can be used once by one customer")),
  27. (MULTI_USE, _("Can be used multiple times by multiple customers")),
  28. (ONCE_PER_CUSTOMER, _("Can only be used once per customer")),
  29. )
  30. usage = models.CharField(_("Usage"), max_length=128,
  31. choices=USAGE_CHOICES, default=MULTI_USE)
  32. start_date = models.DateField(_('Start Date'))
  33. end_date = models.DateField(_('End Date'))
  34. # Audit information
  35. num_basket_additions = models.PositiveIntegerField(
  36. _("Times added to basket"), default=0)
  37. num_orders = models.PositiveIntegerField(_("Times on orders"), default=0)
  38. total_discount = models.DecimalField(
  39. _("Total discount"), decimal_places=2, max_digits=12,
  40. default=Decimal('0.00'))
  41. date_created = models.DateField(auto_now_add=True)
  42. class Meta:
  43. get_latest_by = 'date_created'
  44. abstract = True
  45. verbose_name = _("Voucher")
  46. verbose_name_plural = _("Vouchers")
  47. def __unicode__(self):
  48. return self.name
  49. def clean(self):
  50. if (self.start_date and self.end_date and
  51. self.start_date > self.end_date):
  52. raise exceptions.ValidationError(
  53. _('End date should be later than start date'))
  54. def save(self, *args, **kwargs):
  55. self.code = self.code.upper()
  56. super(AbstractVoucher, self).save(*args, **kwargs)
  57. def is_active(self, test_date=None):
  58. """
  59. Test whether this voucher is currently active.
  60. """
  61. if not test_date:
  62. test_date = datetime.date.today()
  63. return self.start_date <= test_date and test_date < self.end_date
  64. def is_available_to_user(self, user=None):
  65. """
  66. Test whether this voucher is available to the passed user.
  67. Returns a tuple of a boolean for whether it is successulf, and a
  68. message
  69. """
  70. is_available, message = False, ''
  71. if self.usage == self.SINGLE_USE:
  72. is_available = self.applications.count() == 0
  73. if not is_available:
  74. message = _("This voucher has already been used")
  75. elif self.usage == self.MULTI_USE:
  76. is_available = True
  77. elif self.usage == self.ONCE_PER_CUSTOMER:
  78. if not user.is_authenticated():
  79. is_available = False
  80. message = _(
  81. "This voucher is only available to signed in users")
  82. else:
  83. is_available = self.applications.filter(
  84. voucher=self, user=user).count() == 0
  85. if not is_available:
  86. message = _("You have already used this voucher in "
  87. "a previous order")
  88. return is_available, message
  89. def record_usage(self, order, user):
  90. """
  91. Records a usage of this voucher in an order.
  92. """
  93. if user.is_authenticated():
  94. self.applications.create(voucher=self, order=order, user=user)
  95. else:
  96. self.applications.create(voucher=self, order=order)
  97. self.num_orders += 1
  98. self.save()
  99. def record_discount(self, discount):
  100. """
  101. Record a discount that this offer has given
  102. """
  103. self.total_discount += discount
  104. self.save()
  105. @property
  106. def benefit(self):
  107. return self.offers.all()[0].benefit
  108. class AbstractVoucherApplication(models.Model):
  109. """
  110. For tracking how often a voucher has been used
  111. """
  112. voucher = models.ForeignKey(
  113. 'voucher.Voucher', related_name="applications",
  114. verbose_name=_("Voucher"))
  115. # It is possible for an anonymous user to apply a voucher so we need to
  116. # allow the user to be nullable
  117. user = models.ForeignKey('auth.User', blank=True, null=True,
  118. verbose_name=_("User"))
  119. order = models.ForeignKey('order.Order', verbose_name=_("Order"))
  120. date_created = models.DateField(_("Date Creted"), auto_now_add=True)
  121. class Meta:
  122. abstract = True
  123. verbose_name = _("Voucher Application")
  124. verbose_name_plural = _("Voucher Applications")
  125. def __unicode__(self):
  126. return _("'%(voucher)s' used by '%(user)s'") % {
  127. 'voucher': self.voucher,
  128. 'user': self.user}