Coverage for invoices/signals.py: 39%
31 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-05-22 11:14 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-05-22 11:14 -0600
1from django.core.files.base import ContentFile
2from django.dispatch import receiver
3from django.db.models import signals
4from .models import (
5 MembershipInvoiceConfiguration,
6 InvoiceConfiguration,
7 InvoiceProductConfiguration,
8 Invoice,
9 InvoiceExport,
10)
11from .resources import InvoiceResource
12from .utils import remove_social_regime_from_business_name
15@receiver(signals.post_save, sender=MembershipInvoiceConfiguration)
16def toggle_default(sender, instance, created, *args, **kwargs):
17 if instance.default:
18 sender.objects.exclude(random_slug=instance.random_slug).update(default=False)
21@receiver(signals.post_save, sender=InvoiceConfiguration)
22def set_legal_name(sender, instance, created, *args, **kwargs):
23 if created:
24 instance.legal_name = remove_social_regime_from_business_name(instance.legal_name)
25 instance.save()
28@receiver(signals.post_save, sender=InvoiceProductConfiguration)
29def update_product_charge_on_invoice_proudct_configuration(sender, instance, created, *args, **kwargs):
30 if created:
31 instance.product_charge.save()
34@receiver(signals.post_save, sender=Invoice)
35def update_product_charge_on_invoice(sender, instance, *args, **kwargs):
36 for product_charge in instance.product_charges.all():
37 product_charge.save()
40@receiver(signals.post_save, sender=InvoiceExport)
41def save_invoice_export_file(sender, instance, created, *args, **kwargs):
42 if created:
43 dataset = InvoiceResource().export(
44 queryset=Invoice.objects.filter(
45 organization=instance.organization,
46 created_at__date__gte=instance.from_date,
47 created_at__date__lte=instance.to_date,
48 status=instance.status,
49 )
50 )
52 from_date_str = instance.from_date.strftime("%Y-%m-%d")
53 to_date_str = instance.to_date.strftime("%Y-%m-%d")
55 csv_file = ContentFile(dataset.export("csv"))
57 instance.export_file.save(f"Invoice_{from_date_str}_{to_date_str}.csv", csv_file)