tasks.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from celery import shared_task
  2. from django.conf import settings
  3. from django.db.models import Q
  4. from .email import InvitationEmail, MetQuotaEmail
  5. from .models import Organization
  6. def get_free_tier_organizations_with_event_count():
  7. """
  8. Free tier means either no plan selected or only inactive plan
  9. """
  10. return Organization.objects.with_event_counts().filter(
  11. Q(djstripe_customers__isnull=True)
  12. | Q(
  13. djstripe_customers__subscriptions__plan__amount=0,
  14. djstripe_customers__subscriptions__status="active",
  15. )
  16. | Q(
  17. djstripe_customers__subscriptions__status="canceled",
  18. )
  19. & ~Q( # Avoid exclude, it doesn't filter relations the same way
  20. djstripe_customers__subscriptions__plan__amount__gt=0,
  21. djstripe_customers__subscriptions__status="active",
  22. )
  23. )
  24. @shared_task
  25. def set_organization_throttle():
  26. """Determine if organization should be throttled"""
  27. # Currently throttling only happens if billing is enabled and user has free plan.
  28. if settings.BILLING_ENABLED:
  29. events_max = settings.BILLING_FREE_TIER_EVENTS
  30. free_tier_organizations = get_free_tier_organizations_with_event_count()
  31. # Throttle when over event limit or has no plan/canceled plan
  32. orgs_over_quota = (
  33. free_tier_organizations.filter(
  34. is_accepting_events=True,
  35. )
  36. .filter(
  37. Q(total_event_count__gt=events_max)
  38. | Q(djstripe_customers__isnull=True)
  39. | Q(djstripe_customers__subscriptions__status="canceled")
  40. )
  41. .select_related("owner__organization_user")
  42. )
  43. for org in orgs_over_quota:
  44. send_email_met_quota.delay(org.pk)
  45. orgs_over_quota.update(is_accepting_events=False)
  46. # To unthrottled, must have active subscription and less events than max
  47. free_tier_organizations.exclude(djstripe_customers__isnull=True).filter(
  48. djstripe_customers__subscriptions__status="active",
  49. is_accepting_events=False,
  50. total_event_count__lte=events_max,
  51. ).update(is_accepting_events=True)
  52. # paid accounts should always be active at this time
  53. Organization.objects.filter(
  54. is_accepting_events=False,
  55. djstripe_customers__subscriptions__plan__amount__gt=0,
  56. djstripe_customers__subscriptions__status="active",
  57. ).update(is_accepting_events=True)
  58. @shared_task
  59. def send_email_met_quota(organization_id: int):
  60. MetQuotaEmail(pk=organization_id).send_email()
  61. @shared_task
  62. def send_email_invite(org_user_id: int, token: str):
  63. InvitationEmail(pk=org_user_id, token=token).send_email()