tasks.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 (
  11. Organization.objects.with_event_counts()
  12. .filter(
  13. Q(djstripe_customers__isnull=True)
  14. | Q(
  15. djstripe_customers__subscriptions__plan__amount=0,
  16. djstripe_customers__subscriptions__status="active",
  17. )
  18. | Q(
  19. djstripe_customers__subscriptions__status="canceled",
  20. )
  21. )
  22. .exclude(
  23. djstripe_customers__subscriptions__plan__amount__gt=0,
  24. djstripe_customers__subscriptions__status="active",
  25. )
  26. )
  27. @shared_task
  28. def set_organization_throttle():
  29. """Determine if organization should be throttled"""
  30. # Currently throttling only happens if billing is enabled and user has free plan.
  31. if settings.BILLING_ENABLED:
  32. events_max = settings.BILLING_FREE_TIER_EVENTS
  33. free_tier_organizations = get_free_tier_organizations_with_event_count()
  34. # Throttle when over event limit or has no plan/canceled plan
  35. orgs_over_quota = (
  36. free_tier_organizations.filter(
  37. is_accepting_events=True,
  38. )
  39. .filter(
  40. Q(total_event_count__gt=events_max)
  41. | Q(djstripe_customers__isnull=True)
  42. | Q(djstripe_customers__subscriptions__status="canceled")
  43. )
  44. .select_related("owner__organization_user")
  45. )
  46. for org in orgs_over_quota:
  47. send_email_met_quota.delay(org.pk)
  48. orgs_over_quota.update(is_accepting_events=False)
  49. # To unthrottled, must have active subscription and less events than max
  50. free_tier_organizations.exclude(djstripe_customers__isnull=True).filter(
  51. djstripe_customers__subscriptions__status="active",
  52. is_accepting_events=False,
  53. total_event_count__lte=events_max,
  54. ).update(is_accepting_events=True)
  55. # paid accounts should always be active at this time
  56. Organization.objects.filter(
  57. is_accepting_events=False,
  58. djstripe_customers__subscriptions__plan__amount__gt=0,
  59. djstripe_customers__subscriptions__status="active",
  60. ).update(is_accepting_events=True)
  61. @shared_task
  62. def send_email_met_quota(organization_id: int):
  63. MetQuotaEmail(pk=organization_id).send_email()
  64. @shared_task
  65. def send_email_invite(org_user_id: int, token: str):
  66. InvitationEmail(pk=org_user_id, token=token).send_email()