diff --git a/apps/tag/signals/tag_distribution_signals.py b/apps/tag/signals/tag_distribution_signals.py index 6e8fe8e..48e7737 100644 --- a/apps/tag/signals/tag_distribution_signals.py +++ b/apps/tag/signals/tag_distribution_signals.py @@ -1,26 +1,60 @@ -from django.db import transaction from django.db.models import Count from django.db.models.signals import m2m_changed from django.db.models.signals import post_save from django.dispatch import receiver -from apps.tag.models import TagDistribution, TagDistributionBatch, Tag +from apps.tag.models import TagDistribution, TagDistributionBatch -@receiver(post_save, sender=TagDistribution) -def calculate_tag_batch_details(sender, instance: TagDistribution, **kwargs): - """ - calculate distribution & remaining tag count from batch - """ - distributions = TagDistribution.objects.filter(batch=instance.batch) +# @receiver(post_save, sender=TagDistribution) +# def calculate_tag_batch_details(sender, instance: TagDistribution, **kwargs): +# """ +# calculate distribution & remaining tag count from batch +# """ +# distributions = TagDistribution.objects.filter(batch=instance.batch) +# +# distributed_tags = distributions.aggregate(count=Count('tag'))['count'] +# +# instance.batch.total_distributed_tags = distributed_tags \ +# if not instance.batch.total_distributed_tags != 0 \ +# else instance.total_tag_count +# instance.batch.total_remaining_tags = int(instance.batch.request_number) - distributed_tags +# instance.batch.save(update_fields=['total_distributed_tags', 'total_remaining_tags']) - distributed_tags = distributions.aggregate(count=Count('tag'))['count'] +@receiver(m2m_changed, sender=TagDistribution.tag.through) +def update_batch_on_distribution_change( + sender, instance: TagDistribution, action, **kwargs +): + if action not in ['post_add', 'post_remove', 'post_clear']: + return - instance.batch.total_distributed_tags = distributed_tags \ - if not instance.batch.total_distributed_tags != 0 \ - else instance.total_tag_count - instance.batch.total_remaining_tags = int(instance.batch.request_number) - distributed_tags - instance.batch.save(update_fields=['total_distributed_tags', 'total_remaining_tags']) + if not instance.batch: + return + + batch = instance.batch + + distributions = TagDistribution.objects.filter(batch=batch) + + distributed_tags = distributions.aggregate( + total=Count('tag') + )['total'] or 0 + + batch.total_distributed_tags = distributed_tags + batch.total_remaining_tags = ( + int(batch.request_number) - distributed_tags + ) + + batch.status = ( + 'distributed' + if batch.total_remaining_tags == 0 + else 'created' + ) + + batch.save(update_fields=[ + 'total_distributed_tags', + 'total_remaining_tags', + 'status' + ]) @receiver(post_save, sender=TagDistributionBatch)