tasks.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from celery import shared_task
  2. from django.core.cache import cache
  3. from .email import InvitationEmail, ThrottleNoticeEmail
  4. from .models import Organization
  5. @shared_task
  6. def check_organization_throttle(organization_id: int):
  7. if not cache.add(f"org-throttle-{organization_id}", True):
  8. return # Recent check already performed
  9. org = Organization.objects.with_event_counts().get(id=organization_id)
  10. _check_and_update_throttle(org)
  11. @shared_task
  12. def check_all_organizations_throttle():
  13. for org in Organization.objects.with_event_counts().iterator():
  14. _check_and_update_throttle(org)
  15. def _check_and_update_throttle(org: Organization):
  16. from djstripe.models import Product
  17. plan_events: int | None = (
  18. Product.objects.filter(
  19. plan__subscriptions__customer__subscriber=org,
  20. plan__subscriptions__status="active",
  21. )
  22. .values_list("metadata__events", flat=True)
  23. .first()
  24. )
  25. if plan_events:
  26. plan_events = int(plan_events)
  27. org_throttle = 0
  28. if plan_events is None or org.total_event_count > plan_events * 2:
  29. org_throttle = 100
  30. elif org.total_event_count > plan_events * 1.5:
  31. org_throttle = 50
  32. elif org.total_event_count > plan_events:
  33. org_throttle = 10
  34. if org.event_throttle_rate != org_throttle:
  35. old_throttle = org.event_throttle_rate
  36. org.event_throttle_rate = org_throttle
  37. org.save(update_fields=["event_throttle_rate"])
  38. if org_throttle > old_throttle:
  39. send_throttle_email.delay(org.id)
  40. @shared_task
  41. def send_throttle_email(organization_id: int):
  42. ThrottleNoticeEmail(pk=organization_id).send_email()
  43. @shared_task
  44. def send_email_invite(org_user_id: int, token: str):
  45. InvitationEmail(pk=org_user_id, token=token).send_email()