from django.db import models from django.db.models import Sum from django.utils import timezone from users.models import User TYPES = ( ('minus', 'Снятие'), ('plus', 'Приход'), ) class Wallet(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) balance = models.DecimalField(max_digits=10, decimal_places=0, default=0) def __str__(self): return str(self.balance) class InvoiceHistory(models.Model): comment = models.TextField(blank=True) created = models.DateTimeField(default=timezone.now) sum = models.DecimalField(max_digits=10, decimal_places=0, default=0, null=True, blank=True) balance = models.DecimalField(max_digits=10, decimal_places=0, default=0) type = models.CharField(max_length=20, blank=True, null=True) user = models.ForeignKey(User, related_name='invoice_history') def __str__(self): return self.comment def save(self, *args, **kwargs): if self.pk is None: current_sum_info = InvoiceHistory.objects.filter(user=self.user).aggregate(Sum('sum')) current_sum = current_sum_info['sum__sum'] or 0 self.balance = current_sum + self.sum super().save(*args, **kwargs) class Meta: verbose_name = 'Счет(История)' verbose_name_plural = 'Счет(История)' ordering = ('-created',) class WithDraw(models.Model): sum = models.DecimalField(max_digits=10, decimal_places=0) created = models.DateTimeField(default=timezone.now) yandex_card = models.CharField(max_length=30) user = models.ForeignKey(User, related_name='with_draw') def __str__(self): return self.yandex_card class Meta: verbose_name = 'Заявка на вывод средств' verbose_name_plural = 'Заявки на вывод средств' ordering = ('-created',) class Transaction(models.Model): TYPES = ( ('add', 'Пополнение'), ('reservation', 'Резервирование'), ) complete = models.BooleanField(default=False, editable=False) # Not editable in admin created_at = models.DateTimeField(default=timezone.now, editable=False) customer = models.ForeignKey(User, related_name='customer_transactions') voids_at = models.DateTimeField() sum = models.DecimalField(max_digits=20, decimal_places=0, default=0) type = models.CharField(max_length=20, choices=TYPES, default='add') def save(self, *args, **kwargs): if not self.pk and self.created_at: self.voids_at = self.created_at + timezone.timedelta(minutes=9000) super().save(*args, **kwargs) def is_void(self): return timezone.now() > self.voids_at def __str__(self): return str(self.pk)