|
1 | 1 | """ |
2 | 2 | Utility functions for the Enterprise API. |
3 | 3 | """ |
| 4 | +import logging |
| 5 | +from typing import List, Set |
| 6 | + |
4 | 7 | from django.conf import settings |
5 | 8 | from django.contrib import auth |
| 9 | +from django.db import DatabaseError, transaction |
| 10 | +from django.db.models import F |
| 11 | +from django.db.models.functions import Lower |
6 | 12 | from django.utils.translation import gettext as _ |
7 | 13 |
|
8 | 14 | from enterprise.constants import ( |
9 | 15 | ENTERPRISE_CATALOG_ADMIN_ROLE, |
10 | 16 | ENTERPRISE_DASHBOARD_ADMIN_ROLE, |
11 | 17 | ENTERPRISE_REPORTING_CONFIG_ADMIN_ROLE, |
| 18 | + AdminInviteStatus, |
12 | 19 | ) |
13 | 20 | from enterprise.models import ( |
14 | 21 | EnterpriseCustomer, |
| 22 | + EnterpriseCustomerAdmin, |
15 | 23 | EnterpriseCustomerCatalog, |
16 | 24 | EnterpriseCustomerInviteKey, |
17 | 25 | EnterpriseCustomerReportingConfiguration, |
18 | 26 | EnterpriseCustomerUser, |
19 | 27 | EnterpriseFeatureRole, |
20 | 28 | EnterpriseFeatureUserRoleAssignment, |
21 | 29 | EnterpriseGroup, |
| 30 | + PendingEnterpriseCustomerAdminUser, |
22 | 31 | ) |
| 32 | +from enterprise.tasks import send_enterprise_admin_invite_email |
| 33 | + |
| 34 | +logger = logging.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +def get_existing_admin_emails(enterprise_customer: EnterpriseCustomer) -> Set[str]: |
| 38 | + """ |
| 39 | + Retrieve normalized email addresses of existing enterprise admins. |
| 40 | +
|
| 41 | + Args: |
| 42 | + enterprise_customer: The enterprise customer instance. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + Set of lowercased email addresses. |
| 46 | +
|
| 47 | + Raises: |
| 48 | + DatabaseError: If database query fails. |
| 49 | +
|
| 50 | + Example: |
| 51 | + >>> emails = get_existing_admin_emails(customer) |
| 52 | + >>> 'admin@example.com' in emails |
| 53 | + True |
| 54 | + """ |
| 55 | + try: |
| 56 | + return set( |
| 57 | + EnterpriseCustomerAdmin.objects.filter( |
| 58 | + enterprise_customer_user__enterprise_customer=enterprise_customer, |
| 59 | + enterprise_customer_user__active=True, |
| 60 | + enterprise_customer_user__user_fk__is_active=True, |
| 61 | + ) |
| 62 | + .annotate(email_l=Lower(F("enterprise_customer_user__user_fk__email"))) |
| 63 | + .values_list("email_l", flat=True) |
| 64 | + ) |
| 65 | + except DatabaseError: |
| 66 | + logger.exception( |
| 67 | + "Database error retrieving existing admin emails for enterprise customer: %s", |
| 68 | + enterprise_customer.uuid, |
| 69 | + ) |
| 70 | + raise |
| 71 | + |
| 72 | + |
| 73 | +def get_existing_pending_emails( |
| 74 | + enterprise_customer: EnterpriseCustomer, |
| 75 | + normalized_emails: List[str] |
| 76 | +) -> Set[str]: |
| 77 | + """ |
| 78 | + Retrieve normalized email addresses of pending admin invitations. |
| 79 | +
|
| 80 | + Args: |
| 81 | + enterprise_customer: The enterprise customer instance. |
| 82 | + normalized_emails: List of normalized email addresses to check. |
| 83 | +
|
| 84 | + Returns: |
| 85 | + Set of lowercased email addresses that have pending invitations. |
| 86 | +
|
| 87 | + Raises: |
| 88 | + DatabaseError: If database query fails. |
| 89 | +
|
| 90 | + Example: |
| 91 | + >>> pending = get_existing_pending_emails(customer, ['user@example.com']) |
| 92 | + >>> 'user@example.com' in pending |
| 93 | + True |
| 94 | + """ |
| 95 | + try: |
| 96 | + return set( |
| 97 | + PendingEnterpriseCustomerAdminUser.objects.filter( |
| 98 | + enterprise_customer=enterprise_customer, |
| 99 | + ) |
| 100 | + .annotate(email_l=Lower(F("user_email"))) |
| 101 | + .filter(email_l__in=normalized_emails) |
| 102 | + .values_list("email_l", flat=True) |
| 103 | + ) |
| 104 | + except DatabaseError: |
| 105 | + logger.exception( |
| 106 | + "Database error retrieving existing pending emails for enterprise customer: %s", |
| 107 | + enterprise_customer.uuid, |
| 108 | + ) |
| 109 | + raise |
| 110 | + |
| 111 | + |
| 112 | +def create_pending_invites( |
| 113 | + enterprise_customer: EnterpriseCustomer, |
| 114 | + emails_to_invite: List[str] |
| 115 | +) -> List[PendingEnterpriseCustomerAdminUser]: |
| 116 | + """ |
| 117 | + Create pending admin invitations and trigger email notifications. |
| 118 | +
|
| 119 | + Creates PendingEnterpriseCustomerAdminUser records for new admin invites |
| 120 | + and enqueues Braze email tasks to be sent after transaction commits. |
| 121 | +
|
| 122 | + Args: |
| 123 | + enterprise_customer: The enterprise customer instance. |
| 124 | + emails_to_invite: List of normalized email addresses to invite. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + List of created PendingEnterpriseCustomerAdminUser instances. |
| 128 | +
|
| 129 | + Raises: |
| 130 | + DatabaseError: If database operation fails. |
| 131 | + ValueError: If emails_to_invite is empty. |
| 132 | + RuntimeError: If called outside a transaction.atomic block. |
| 133 | +
|
| 134 | + Note: |
| 135 | + - Caller must wrap in transaction.atomic() to ensure atomicity |
| 136 | + - Uses get_or_create per email to avoid duplicate invite emails in race conditions |
| 137 | + - Emails are queued via transaction.on_commit() to send after transaction commits |
| 138 | + - This ensures emails only send if database changes succeed |
| 139 | +
|
| 140 | + Example: |
| 141 | + >>> with transaction.atomic(): |
| 142 | + ... invites = create_pending_invites(customer, ['new@example.com']) |
| 143 | + >>> len(invites) > 0 |
| 144 | + True |
| 145 | + """ |
| 146 | + if not emails_to_invite: |
| 147 | + raise ValueError("emails_to_invite cannot be empty") |
| 148 | + |
| 149 | + if not transaction.get_connection().in_atomic_block: |
| 150 | + raise RuntimeError("create_pending_invites must be called inside transaction.atomic().") |
| 151 | + |
| 152 | + try: |
| 153 | + created_invites = [] |
| 154 | + for email in emails_to_invite: |
| 155 | + pending_invite, created = PendingEnterpriseCustomerAdminUser.objects.get_or_create( |
| 156 | + enterprise_customer=enterprise_customer, |
| 157 | + user_email=email, |
| 158 | + ) |
| 159 | + if created: |
| 160 | + created_invites.append(pending_invite) |
| 161 | + |
| 162 | + def _enqueue_email_jobs(): |
| 163 | + # Send invite email only for newly created pending invites. |
| 164 | + if created_invites: |
| 165 | + send_enterprise_admin_invite_email.delay( |
| 166 | + str(enterprise_customer.uuid), |
| 167 | + [invite.user_email for invite in created_invites] |
| 168 | + ) |
| 169 | + |
| 170 | + transaction.on_commit(_enqueue_email_jobs) |
| 171 | + return created_invites |
| 172 | + except DatabaseError: |
| 173 | + logger.exception( |
| 174 | + "Database error creating pending invites for enterprise customer: %s", |
| 175 | + enterprise_customer.uuid, |
| 176 | + ) |
| 177 | + raise |
| 178 | + |
| 179 | + |
| 180 | +def get_invite_status( |
| 181 | + email: str, |
| 182 | + existing_admin_emails: Set[str], |
| 183 | + existing_pending_emails: Set[str] |
| 184 | +) -> str: |
| 185 | + """ |
| 186 | + Determine the invitation status for a given email address. |
| 187 | +
|
| 188 | + Args: |
| 189 | + email (str): The email address to check. |
| 190 | + existing_admin_emails (set): Set of existing admin email addresses. |
| 191 | + existing_pending_emails (set): Set of pending invitation email addresses. |
| 192 | +
|
| 193 | + Returns: |
| 194 | + str: Status constant indicating email state: |
| 195 | + - AdminInviteStatus.EXISTING_ADMIN if user is already an admin |
| 196 | + - AdminInviteStatus.PENDING_INVITE if invitation already sent |
| 197 | + - AdminInviteStatus.NEW_INVITE if this is a new invitation |
| 198 | +
|
| 199 | + Example: |
| 200 | + >>> status = get_invite_status('new@example.com', set(), set()) |
| 201 | + >>> status == 'invite sent' |
| 202 | + True |
| 203 | + """ |
| 204 | + if email in existing_admin_emails: |
| 205 | + return AdminInviteStatus.EXISTING_ADMIN |
| 206 | + if email in existing_pending_emails: |
| 207 | + return AdminInviteStatus.PENDING_INVITE |
| 208 | + return AdminInviteStatus.NEW_INVITE |
| 209 | + |
23 | 210 |
|
24 | 211 | User = auth.get_user_model() |
25 | 212 | SERVICE_USERNAMES = ( |
|
0 commit comments