distributed & remaining weight of distribution by signal calculated
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
from django.db.models import Sum
|
||||
from django.db.models import Sum, Q
|
||||
from django.db.models.signals import post_save, post_delete
|
||||
from common.helpers import get_organization_by_user
|
||||
from django.dispatch import receiver
|
||||
@@ -18,6 +18,7 @@ from crum import get_current_user
|
||||
|
||||
|
||||
def recalculate_remaining_amount(quota):
|
||||
""" calculate remaining weight from distribution """
|
||||
total_distributed = quota.distributions_assigned.aggregate(
|
||||
total=Sum('weight')
|
||||
)['total'] or 0
|
||||
@@ -27,10 +28,39 @@ def recalculate_remaining_amount(quota):
|
||||
quota.save(update_fields=["remaining_weight", "quota_distributed"])
|
||||
|
||||
|
||||
def remaining_distribution_weight(instance: QuotaDistribution):
|
||||
""" calculate remaining & distributed weight from distribution """
|
||||
|
||||
organization = get_organization_by_user(get_current_user())
|
||||
|
||||
total_assigned_distribution = QuotaDistribution.objects.filter(
|
||||
Q(assigned_organization=organization)
|
||||
).aggregate(
|
||||
total=Sum('weight')
|
||||
)['total'] or 0
|
||||
|
||||
print(total_assigned_distribution)
|
||||
|
||||
total_assigner_distribution = QuotaDistribution.objects.filter(
|
||||
Q(assigner_organization=organization)
|
||||
).aggregate(
|
||||
total=Sum('weight')
|
||||
)['total'] or 0
|
||||
|
||||
instance.remaining_weight = total_assigned_distribution - total_assigner_distribution
|
||||
instance.distributed = total_assigner_distribution
|
||||
instance._from_signal = True
|
||||
instance.save(update_fields=['remaining_weight', 'distributed'])
|
||||
|
||||
|
||||
@receiver(post_save, sender=QuotaDistribution)
|
||||
@receiver(post_delete, sender=QuotaDistribution)
|
||||
def update_quota_remaining(sender, instance, **kwargs):
|
||||
|
||||
recalculate_remaining_amount(instance.quota)
|
||||
if getattr(instance, '_from_signal', False):
|
||||
return
|
||||
remaining_distribution_weight(instance)
|
||||
|
||||
|
||||
def update_product_stats(instance: Product):
|
||||
|
||||
Reference in New Issue
Block a user