Coverage for apps/practitioners/signals.py: 38%
44 statements
« prev ^ index » next coverage.py v6.4.4, created at 2024-05-09 16:59 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2024-05-09 16:59 -0600
1from django.conf import settings
2from django.db.models import signals
3from django.dispatch import receiver
4from djstripe import webhooks
5from djstripe.enums import SubscriptionStatus
6from djstripe.models import APIKey, Customer, Invoice, Subscription
7from djstripe.models.core import Event
9from app.facturapi import FacturapiOrganizationClient
10from app.stripe.actions import Stripe
12from .models import Practitioner, PractitionerGoogleCalendar
15@receiver(signals.pre_save, sender=Practitioner)
16def set_full_name(sender, instance: Practitioner, *args, **kwargs):
17 instance.full_name = " ".join(
18 filter(None, (instance.first_name, instance.middle_name, instance.father_last_name, instance.mother_last_name))
19 )
22@receiver(signals.pre_save, sender=PractitionerGoogleCalendar)
23def turn_off_other_calendars(sender, instance: PractitionerGoogleCalendar, *args, **kwargs):
24 others = instance.practitioner.calendars.filter(for_sync=True).exclude(random_slug=instance.random_slug)
25 others.update(
26 for_sync=False,
27 )
30@receiver(signals.post_save, sender=Practitioner)
31def create_practitioner_stripe_customer(sender, instance: Practitioner, created, *args, **kwargs):
32 if created:
33 if APIKey.objects.all().exists():
34 stripe = Stripe()
35 stripe_customer = stripe.create_practitioner_customer(instance)
36 customer = Customer.sync_from_stripe_data(stripe_customer)
37 customer.subscriber = instance
38 customer.save()
41@receiver(signals.post_save, sender=Subscription)
42def set_practitioner_is_paid(sender, instance: Subscription, created, *args, **kwargs):
43 if instance.status != SubscriptionStatus.active:
44 instance.customer.subscriber.is_paid = False
45 instance.customer.subscriber.save()
46 else:
47 instance.customer.subscriber.is_paid = True
48 instance.customer.subscriber.save()
51@webhooks.handler("invoice.paid")
52def invoice_paid(event: Event, **kwargs):
53 invoice_id = event.data.get("object").get("id")
54 try:
55 invoice = Invoice.objects.get(id=invoice_id)
56 subscription_items = invoice.subscription.items.all()
57 facturapi_client = FacturapiOrganizationClient(settings.FACTURAPI_TUAL_ORGANIZATION_KEY)
58 receipt_id = facturapi_client.Receipt.create(
59 payment_form="04",
60 items=[
61 {
62 "product": {
63 "description": subscription_item.plan.product.name,
64 "price": float(invoice.total),
65 "product_key": subscription_item.plan.product.metadata.get("sat_id", "60131325"),
66 }
67 }
68 for subscription_item in subscription_items
69 ],
70 )
71 facturapi_client.Receipt.send_email(receipt_id.get("id"), invoice.customer_email)
72 except Invoice.DoesNotExist:
73 pass