def create_code(self): discounts = Discount.objects.all() code = self._code_build() while len(discounts.filter(code=code)): #print "found matching code %s" % code code = self._code_build() d = Discount() d.site = Site.objects.all()[0] d.description = u"Discount for %s" % self.name d.code = code d.active = True d.percentage = 100 d.allowedUses = 1 d.allValid = False d.startDate = datetime.now() d.endDate = datetime.now() + timedelta(days=30) d.shipping = 'FREE' d.save() # All free products for p in ProductAttribute.objects.filter( option__name='Free', value="YES" ): d.valid_products.add( p.product ) d.save() self.discount_code = code return code
def _activate(self, user): today = datetime.utcnow().date() code = "%x%x%x%x%x" % uuid1().fields[0:5] discount = Discount( site=self.site, description=_(u"Invite discount " u"for %(last_name)s %(first_name)s") % { 'last_name': user.last_name, 'first_name': user.first_name }, code=code, active=True, amount=self.amount, percentage=self.percentage, automatic=False, allowedUses=1, minOrder=self.minOrder, startDate=today, endDate=today + timedelta(days=self.daysValid), shipping=self.shipping, allValid=self.allValid) discount.save() for product in self.valid_products.all(): discount.valid_products.add(product) for category in self.valid_categories.all(): discount.valid_categories.add(category) discount.save() discount_amount = None if self.amount is not None: discount_amount = moneyfmt(self.amount) else: discount_amount = "%s%%" % self.percentage send_store_mail(subject=_(u"A discount coupon for you"), context={ 'first_name': user.first_name, 'invites_number': self.invites_target, 'discount_amount': discount_amount, 'coupon_code': discount.code, 'end_date': discount.endDate }, template='invites/mail/discount.txt', recipients_list=[user.email], template_html='invites/mail/discount.html') # create new InviterDiscount inviter_discount = InviterDiscount(user=user, coupon=discount, template=self) inviter_discount.save() return True