Update snapshots with sum db columns

This commit is contained in:
Edgar P. Burkhart 2022-12-29 21:58:26 +01:00
parent 02eb781492
commit c083fff07e
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
4 changed files with 87 additions and 30 deletions

View file

@ -4,7 +4,7 @@ import uuid
from django.conf import settings
from django.core.validators import FileExtensionValidator
from django.db import models
from django.db import models, transaction
from django.forms import ModelForm
from django.urls import reverse
from django.utils.translation import gettext as _
@ -64,9 +64,7 @@ class Account(CustomModel):
class AccountModel(CustomModel):
account = models.ForeignKey(
Account,
on_delete=models.SET_NULL,
blank=True,
null=True,
on_delete=models.CASCADE,
verbose_name=_("Account"),
)
@ -117,6 +115,20 @@ class Snapshot(AccountModel):
start_value = models.DecimalField(
max_digits=12, decimal_places=2, default=0, verbose_name=_("Start value")
)
diff = models.DecimalField(
max_digits=12,
decimal_places=2,
default=0,
verbose_name=_("Difference"),
editable=False,
)
sum = models.DecimalField(
max_digits=12,
decimal_places=2,
default=0,
verbose_name=_("Transaction difference"),
editable=False,
)
file = models.FileField(
upload_to=snapshot_path,
validators=[FileExtensionValidator(["pdf"])],
@ -135,8 +147,18 @@ class Snapshot(AccountModel):
if _prever.file and _prever.file != self.file:
pathlib.Path(_prever.file.path).unlink(missing_ok=True)
with transaction.atomic():
for trans in self.transaction_set.all():
trans.save()
self.diff = self.value - self.start_value
self.sum = self.transaction_set.aggregate(sum=models.Sum("value")).get("sum", 0)
super().save(*args, **kwargs)
def update_sum(self):
self.sum = self.transaction_set.aggregate(sum=models.Sum("value")).get("sum", 0)
super().save()
def delete(self, *args, only_super=False, **kwargs):
if self.file:
self.file.delete()
@ -147,24 +169,6 @@ class Snapshot(AccountModel):
def get_delete_url(self):
return reverse("del_snapshot", kwargs={"pk": self.pk})
@property
def pos(self):
return (
self.transactions.filter(value__gt=0).aggregate(sum=models.Sum("value"))[
"sum"
]
or 0
)
@property
def neg(self):
return (
self.transactions.filter(value__lt=0).aggregate(sum=models.Sum("value"))[
"sum"
]
or 0
)
class Meta:
ordering = ["-date"]
verbose_name = _("Statement")
@ -209,6 +213,7 @@ class Transaction(CustomModel):
def save(self, *args, **kwargs):
self.account = self.snapshot.account
self.snapshot.update_sum()
super().save(*args, **kwargs)
def __str__(self):