from functools import partial from registrasion.models.commerce import Invoice, LineItem def generate_ticket(prefix, length, num): return "%d-%0*d" % (prefix, length, num) def create_ticket_numbers(item): quantity = item['quantity'] length = len(str(quantity)) ticket_func = partial(generate_ticket, item['id'], length) return map(ticket_func, range(1, quantity+1)) class RaffleMixin: @property def is_open(self): prizes = self.prizes.all() return len(prizes) and not all(p.locked for p in prizes) def draw(self, user): self.draws.create(drawn_by=user) def get_tickets(self, user=None): filters = { 'invoice__status': Invoice.STATUS_PAID, 'product__in': self.products.all() } if user is not None: filters['invoice__user'] = user for item in LineItem.objects.filter(**filters).values('id', 'quantity'): yield (item['id'], list(create_ticket_numbers(item))) class LockMixin(): @property def locked(self): return self._locked def unlock(self, user): self.audit_events.create(user=user, reason="Unlocked") self._locked = False class PrizeMixin: def remove_winner(self, user): reason = "Removed winning ticket: {}".format(self.winning_ticket.id) self.audit_events.create(user=user, reason=reason) self.winning_ticket = None self.save(update_fields=('winning_ticket',))