|
| 1 | +""" |
| 2 | +User plan management and Dodo Payments integration. |
| 3 | +
|
| 4 | +This module provides functionality to determine user subscription plans |
| 5 | +by integrating with the Dodo Payments API. |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +from datetime import datetime |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +import httpx |
| 13 | +from dotenv import load_dotenv |
| 14 | + |
| 15 | +from mxtoai._logging import get_logger |
| 16 | +from mxtoai.schemas import UserPlan |
| 17 | + |
| 18 | +# Load environment variables |
| 19 | +load_dotenv() |
| 20 | + |
| 21 | +# Configure logging |
| 22 | +logger = get_logger(__name__) |
| 23 | + |
| 24 | +# Dodo Payments API configuration |
| 25 | +DODO_API_KEY = os.getenv("DODO_API_KEY") |
| 26 | +PRO_PLAN_PRODUCT_ID = os.getenv("PRO_PLAN_PRODUCT_ID") |
| 27 | +DODO_API_BASE_URL = "https://live.dodopayments.com" |
| 28 | + |
| 29 | +# HTTP client timeout configuration |
| 30 | +REQUEST_TIMEOUT = 30.0 |
| 31 | + |
| 32 | +# HTTP status codes |
| 33 | +HTTP_OK = 200 |
| 34 | + |
| 35 | + |
| 36 | +async def get_user_plan(email: str) -> UserPlan: |
| 37 | + """ |
| 38 | + Determine user plan based on Dodo Payments subscription status. |
| 39 | +
|
| 40 | + Args: |
| 41 | + email: User's email address |
| 42 | +
|
| 43 | + Returns: |
| 44 | + UserPlan: The user's subscription plan (PRO or BETA) |
| 45 | +
|
| 46 | + Note: |
| 47 | + Falls back to UserPlan.BETA on any errors or missing configuration. |
| 48 | +
|
| 49 | + """ |
| 50 | + # Check if Dodo API key is configured |
| 51 | + if not DODO_API_KEY: |
| 52 | + logger.warning("DODO_API_KEY not configured, falling back to BETA plan for all users") |
| 53 | + return UserPlan.BETA |
| 54 | + |
| 55 | + try: |
| 56 | + # Step 1: Look up customer by email |
| 57 | + customer_id = await _get_customer_id_by_email(email) |
| 58 | + if not customer_id: |
| 59 | + logger.info(f"No customer found for email {email}, returning BETA plan") |
| 60 | + return UserPlan.BETA |
| 61 | + |
| 62 | + # Step 2: Get active subscriptions for the customer |
| 63 | + latest_subscription = await _get_latest_active_subscription(customer_id) |
| 64 | + if not latest_subscription: |
| 65 | + logger.info(f"No active subscriptions found for customer {customer_id}, returning BETA plan") |
| 66 | + return UserPlan.BETA |
| 67 | + |
| 68 | + # Step 3: Check if subscription matches PRO plan product ID |
| 69 | + product_id = latest_subscription.get("product_id") |
| 70 | + if PRO_PLAN_PRODUCT_ID and product_id == PRO_PLAN_PRODUCT_ID: |
| 71 | + logger.info(f"User {email} has PRO plan subscription (product_id: {product_id})") |
| 72 | + return UserPlan.PRO |
| 73 | + logger.info( |
| 74 | + f"User {email} subscription does not match PRO plan (product_id: {product_id}), returning BETA plan" |
| 75 | + ) |
| 76 | + |
| 77 | + except Exception as e: |
| 78 | + logger.error(f"Error determining user plan for {email}: {e}") |
| 79 | + logger.warning(f"Falling back to BETA plan for user {email} due to error") |
| 80 | + |
| 81 | + return UserPlan.BETA |
| 82 | + |
| 83 | + |
| 84 | +async def _get_customer_id_by_email(email: str) -> str | None: |
| 85 | + """ |
| 86 | + Look up customer ID by email address using Dodo Payments API. |
| 87 | +
|
| 88 | + Args: |
| 89 | + email: Customer's email address |
| 90 | +
|
| 91 | + Returns: |
| 92 | + str | None: Customer ID if found, None otherwise |
| 93 | +
|
| 94 | + """ |
| 95 | + try: |
| 96 | + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: |
| 97 | + response = await client.get( |
| 98 | + f"{DODO_API_BASE_URL}/customers", |
| 99 | + headers={"Authorization": f"Bearer {DODO_API_KEY}", "Content-Type": "application/json"}, |
| 100 | + params={"email": email}, |
| 101 | + ) |
| 102 | + |
| 103 | + if response.status_code == HTTP_OK: |
| 104 | + data = response.json() |
| 105 | + customers = data.get("items", []) |
| 106 | + |
| 107 | + if customers: |
| 108 | + customer = customers[0] # Take the first matching customer |
| 109 | + customer_id = customer.get("customer_id") |
| 110 | + logger.debug(f"Found customer {customer_id} for email {email}") |
| 111 | + return customer_id |
| 112 | + logger.debug(f"No customers found for email {email}") |
| 113 | + return None |
| 114 | + logger.error(f"Dodo Payments API error for customer lookup: {response.status_code} - {response.text}") |
| 115 | + return None |
| 116 | + |
| 117 | + except httpx.TimeoutException: |
| 118 | + logger.error(f"Timeout while looking up customer for email {email}") |
| 119 | + return None |
| 120 | + except Exception as e: |
| 121 | + logger.error(f"Error looking up customer for email {email}: {e}") |
| 122 | + return None |
| 123 | + |
| 124 | + |
| 125 | +async def _get_latest_active_subscription(customer_id: str) -> dict[str, Any] | None: |
| 126 | + """ |
| 127 | + Get the latest active subscription for a customer. |
| 128 | +
|
| 129 | + Args: |
| 130 | + customer_id: Customer's ID from Dodo Payments |
| 131 | +
|
| 132 | + Returns: |
| 133 | + dict | None: Latest active subscription data if found, None otherwise |
| 134 | +
|
| 135 | + """ |
| 136 | + try: |
| 137 | + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: |
| 138 | + response = await client.get( |
| 139 | + f"{DODO_API_BASE_URL}/subscriptions", |
| 140 | + headers={"Authorization": f"Bearer {DODO_API_KEY}", "Content-Type": "application/json"}, |
| 141 | + params={"customer_id": customer_id, "status": "active"}, |
| 142 | + ) |
| 143 | + |
| 144 | + if response.status_code == HTTP_OK: |
| 145 | + data = response.json() |
| 146 | + subscriptions = data.get("items", []) |
| 147 | + |
| 148 | + if subscriptions: |
| 149 | + # Sort by created_at to get the latest subscription |
| 150 | + sorted_subscriptions = sorted( |
| 151 | + subscriptions, |
| 152 | + key=lambda x: datetime.fromisoformat(x.get("created_at", "1970-01-01T00:00:00Z")), |
| 153 | + reverse=True, |
| 154 | + ) |
| 155 | + latest_subscription = sorted_subscriptions[0] |
| 156 | + logger.debug( |
| 157 | + f"Found {len(subscriptions)} active subscriptions for customer {customer_id}, using latest: {latest_subscription.get('subscription_id')}" |
| 158 | + ) |
| 159 | + return latest_subscription |
| 160 | + logger.debug(f"No active subscriptions found for customer {customer_id}") |
| 161 | + return None |
| 162 | + logger.error(f"Dodo Payments API error for subscription lookup: {response.status_code} - {response.text}") |
| 163 | + return None |
| 164 | + |
| 165 | + except httpx.TimeoutException: |
| 166 | + logger.error(f"Timeout while looking up subscriptions for customer {customer_id}") |
| 167 | + return None |
| 168 | + except Exception as e: |
| 169 | + logger.error(f"Error looking up subscriptions for customer {customer_id}: {e}") |
| 170 | + return None |
0 commit comments