|
8 | 8 | import stripe |
9 | 9 | from celery import shared_task |
10 | 10 | from django.conf import settings |
| 11 | +from django.utils import timezone |
11 | 12 |
|
12 | 13 | from enterprise_access.apps.api_client.braze_client import BrazeApiClient |
13 | 14 | from enterprise_access.apps.api_client.lms_client import LmsApiClient |
14 | 15 | from enterprise_access.apps.customer_billing.api import create_stripe_billing_portal_session |
15 | | -from enterprise_access.apps.customer_billing.models import CheckoutIntent |
| 16 | +from enterprise_access.apps.customer_billing.models import CheckoutIntent, StripeEventSummary |
| 17 | +from enterprise_access.apps.customer_billing.stripe_api import get_stripe_trialing_subscription |
16 | 18 | from enterprise_access.apps.provisioning.utils import validate_trial_subscription |
17 | 19 | from enterprise_access.tasks import LoggedTaskWithRetry |
18 | | -from enterprise_access.utils import cents_to_dollars |
| 20 | +from enterprise_access.utils import cents_to_dollars, format_cents_for_user_display |
19 | 21 |
|
20 | 22 | logger = logging.getLogger(__name__) |
21 | 23 |
|
@@ -288,3 +290,195 @@ def send_trial_cancellation_email_task( |
288 | 290 | str(exc), |
289 | 291 | ) |
290 | 292 | raise |
| 293 | + |
| 294 | + |
| 295 | +@shared_task(base=LoggedTaskWithRetry) |
| 296 | +def send_trial_ending_reminder_email_task(checkout_intent_id): |
| 297 | + """ |
| 298 | + Send Braze email notification 72 hours before trial subscription ends. |
| 299 | +
|
| 300 | + This task handles sending a reminder email to enterprise admins when their |
| 301 | + trial subscription is about to end. The email includes subscription details, |
| 302 | + renewal information, and a link to manage their subscription. |
| 303 | +
|
| 304 | + Args: |
| 305 | + checkout_intent_id (int): ID of the CheckoutIntent record |
| 306 | +
|
| 307 | + Raises: |
| 308 | + BrazeClientError: If there's an error communicating with Braze |
| 309 | + Exception: For any other unexpected errors during email sending |
| 310 | + """ |
| 311 | + try: |
| 312 | + checkout_intent = CheckoutIntent.objects.get(id=checkout_intent_id) |
| 313 | + except CheckoutIntent.DoesNotExist: |
| 314 | + logger.error( |
| 315 | + "Email not sent: CheckoutIntent %s not found for trial ending reminder email", |
| 316 | + checkout_intent_id, |
| 317 | + ) |
| 318 | + return |
| 319 | + |
| 320 | + enterprise_slug = checkout_intent.enterprise_slug |
| 321 | + logger.info( |
| 322 | + "Sending trial ending reminder email for CheckoutIntent %s (enterprise slug: %s)", |
| 323 | + checkout_intent_id, |
| 324 | + enterprise_slug, |
| 325 | + ) |
| 326 | + |
| 327 | + braze_client = BrazeApiClient() |
| 328 | + lms_client = LmsApiClient() |
| 329 | + |
| 330 | + # Fetch enterprise customer data to get admin users |
| 331 | + try: |
| 332 | + enterprise_data = lms_client.get_enterprise_customer_data( |
| 333 | + enterprise_customer_slug=enterprise_slug |
| 334 | + ) |
| 335 | + except Exception as exc: # pylint: disable=broad-exception-caught |
| 336 | + logger.error( |
| 337 | + "Failed to fetch enterprise data for slug %s: %s. Cannot send trial ending reminder email.", |
| 338 | + enterprise_slug, |
| 339 | + str(exc), |
| 340 | + ) |
| 341 | + return |
| 342 | + |
| 343 | + admin_users = enterprise_data.get("admin_users", []) |
| 344 | + |
| 345 | + if not admin_users: |
| 346 | + logger.error( |
| 347 | + "Trial ending reminder email not sent: No admin users found for enterprise slug %s. " |
| 348 | + "Verify admin setup in LMS.", |
| 349 | + enterprise_slug, |
| 350 | + ) |
| 351 | + return |
| 352 | + |
| 353 | + # Retrieve subscription details from Stripe |
| 354 | + try: |
| 355 | + if not checkout_intent.stripe_customer_id: |
| 356 | + logger.error( |
| 357 | + "Trial ending reminder email not sent: No Stripe customer ID for CheckoutIntent %s", |
| 358 | + checkout_intent_id, |
| 359 | + ) |
| 360 | + return |
| 361 | + |
| 362 | + # Get the trialing subscription using the existing utility method |
| 363 | + subscription = get_stripe_trialing_subscription( |
| 364 | + checkout_intent.stripe_customer_id |
| 365 | + ) |
| 366 | + |
| 367 | + if not subscription: |
| 368 | + logger.error( |
| 369 | + "Trial ending reminder email not sent: No active trial subscription found for customer %s", |
| 370 | + checkout_intent.stripe_customer_id, |
| 371 | + ) |
| 372 | + return |
| 373 | + |
| 374 | + if not subscription["items"].data: |
| 375 | + logger.error( |
| 376 | + "Trial ending reminder email not sent: Subscription %s has no items", |
| 377 | + subscription.id, |
| 378 | + ) |
| 379 | + return |
| 380 | + |
| 381 | + first_item = subscription["items"].data[0] |
| 382 | + renewal_date = timezone.make_aware( |
| 383 | + datetime.fromtimestamp(first_item.current_period_end) |
| 384 | + ).strftime("%B %d, %Y") |
| 385 | + license_count = first_item.quantity |
| 386 | + |
| 387 | + # Get payment method details with card brand |
| 388 | + payment_method_info = "" |
| 389 | + if subscription.default_payment_method: |
| 390 | + payment_method = stripe.PaymentMethod.retrieve( |
| 391 | + subscription.default_payment_method |
| 392 | + ) |
| 393 | + if payment_method.type == "card": |
| 394 | + brand = ( |
| 395 | + payment_method.card.brand.capitalize() |
| 396 | + ) # e.g., "Visa", "Mastercard" |
| 397 | + last4 = payment_method.card.last4 |
| 398 | + payment_method_info = f"{brand} ending in {last4}" |
| 399 | + |
| 400 | + total_paid_amount = "$0.00 USD" |
| 401 | + if subscription.latest_invoice: |
| 402 | + invoice_summary = StripeEventSummary.get_latest_invoice_paid( |
| 403 | + subscription.latest_invoice |
| 404 | + ) |
| 405 | + |
| 406 | + if invoice_summary and invoice_summary.invoice_amount_paid is not None: |
| 407 | + total_paid_amount = format_cents_for_user_display( |
| 408 | + invoice_summary.invoice_amount_paid |
| 409 | + ) |
| 410 | + else: |
| 411 | + logger.warning( |
| 412 | + "No invoice summary found for invoice %s, falling back to $0.00 USD", |
| 413 | + subscription.latest_invoice, |
| 414 | + ) |
| 415 | + |
| 416 | + except stripe.StripeError as exc: |
| 417 | + logger.error( |
| 418 | + "Stripe API error while fetching subscription details for CheckoutIntent %s: %s", |
| 419 | + checkout_intent_id, |
| 420 | + str(exc), |
| 421 | + ) |
| 422 | + return |
| 423 | + except Exception as exc: # pylint: disable=broad-exception-caught |
| 424 | + logger.error( |
| 425 | + "Error retrieving subscription details for CheckoutIntent %s: %s", |
| 426 | + checkout_intent_id, |
| 427 | + str(exc), |
| 428 | + ) |
| 429 | + return |
| 430 | + |
| 431 | + subscription_management_url = _get_billing_portal_url(checkout_intent) |
| 432 | + |
| 433 | + braze_trigger_properties = { |
| 434 | + "renewal_date": renewal_date, |
| 435 | + "subscription_management_url": subscription_management_url, |
| 436 | + "license_count": license_count, |
| 437 | + "payment_method": payment_method_info, |
| 438 | + "total_paid_amount": total_paid_amount, |
| 439 | + } |
| 440 | + |
| 441 | + # Create Braze recipients for all admin users |
| 442 | + recipients = [] |
| 443 | + for admin in admin_users: |
| 444 | + try: |
| 445 | + admin_email = admin["email"] |
| 446 | + recipient = braze_client.create_braze_recipient( |
| 447 | + user_email=admin_email, |
| 448 | + lms_user_id=admin.get("lms_user_id"), |
| 449 | + ) |
| 450 | + recipients.append(recipient) |
| 451 | + except Exception as exc: # pylint: disable=broad-exception-caught |
| 452 | + logger.warning( |
| 453 | + "Failed to create Braze recipient for admin email %s: %s", |
| 454 | + admin_email, |
| 455 | + str(exc), |
| 456 | + ) |
| 457 | + |
| 458 | + if not recipients: |
| 459 | + logger.error( |
| 460 | + "Trial ending reminder email not sent: No valid Braze recipients created for enterprise slug %s. " |
| 461 | + "Check admin email errors above.", |
| 462 | + enterprise_slug, |
| 463 | + ) |
| 464 | + return |
| 465 | + |
| 466 | + try: |
| 467 | + braze_client.send_campaign_message( |
| 468 | + settings.BRAZE_ENTERPRISE_PROVISION_TRIAL_ENDING_SOON_CAMPAIGN, |
| 469 | + recipients=recipients, |
| 470 | + trigger_properties=braze_trigger_properties, |
| 471 | + ) |
| 472 | + logger.info( |
| 473 | + "Successfully sent trial ending reminder emails for CheckoutIntent %s to %d recipients", |
| 474 | + checkout_intent_id, |
| 475 | + len(recipients), |
| 476 | + ) |
| 477 | + |
| 478 | + except Exception as exc: |
| 479 | + logger.exception( |
| 480 | + "Braze API error: Failed to send trial ending reminder email for CheckoutIntent %s. Error: %s", |
| 481 | + checkout_intent_id, |
| 482 | + str(exc), |
| 483 | + ) |
| 484 | + raise |
0 commit comments