tasks.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from django.conf import settings
  2. from celery import shared_task
  3. from .models import Organization
  4. from .email import MetQuotaEmail, InvitationEmail
  5. def get_free_tier_organizations_with_event_count():
  6. return Organization.objects.with_event_counts().filter(
  7. djstripe_customers__subscriptions__plan__amount=0,
  8. djstripe_customers__subscriptions__status="active",
  9. )
  10. @shared_task
  11. def set_organization_throttle():
  12. """Determine if organization should be throttled"""
  13. # Currently throttling only happens if billing is enabled and user has free plan.
  14. if settings.BILLING_ENABLED:
  15. events_max = settings.BILLING_FREE_TIER_EVENTS
  16. free_tier_organizations = get_free_tier_organizations_with_event_count()
  17. orgs_over_quota = free_tier_organizations.filter(
  18. is_accepting_events=True, total_event_count__gt=events_max
  19. ).select_related("owner__organization_user")
  20. for org in orgs_over_quota:
  21. send_email_met_quota.delay(org.pk)
  22. orgs_over_quota.update(is_accepting_events=False)
  23. free_tier_organizations.filter(
  24. is_accepting_events=False, total_event_count__lte=events_max
  25. ).update(is_accepting_events=True)
  26. # paid accounts should always be active at this time
  27. Organization.objects.filter(
  28. is_accepting_events=False,
  29. djstripe_customers__subscriptions__plan__amount__gt=0,
  30. djstripe_customers__subscriptions__status="active",
  31. ).update(is_accepting_events=True)
  32. @shared_task
  33. def send_email_met_quota(organization_id: int):
  34. MetQuotaEmail(pk=organization_id).send_email()
  35. @shared_task
  36. def send_email_invite(org_user_id: int, token: str):
  37. InvitationEmail(pk=org_user_id, token=token).send_email()