Repository: aipotheosis-labs/aci
File: backend/aci/server/routes/billing.py (Python)

Code before:
    Handles the customer.subscription.deleted event.
    1. Find the existing subscription record by stripe_subscription_id
    2. Delete the subscription record
    """
    logger.info(
        f"Handling customer.subscription.deleted event, subscription_data={subscription_data}"
    )
    stripe_subscription_id = subscription_data.get("id")

    if not stripe_subscription_id:
        logger.error(f"Subscription deleted event missing ID, payload={subscription_data}")
        raise BillingError(
            "Subscription deleted event missing ID",
            error_code=status.HTTP_400_BAD_REQUEST,
        )

    # 1. Find the existing subscription record by stripe_subscription_id
    subscription = crud.subscriptions.get_subscription_by_stripe_id(
        db_session, stripe_subscription_id
    )

    if subscription:
        # 2. Update PropelAuth organization max_users to 1 (free plan limit)
        try:
            # TODO: Update when allowing multiple orgs
            auth.update_org_metadata(org_id=str(subscription.org_id), max_users=1)
            logger.info(
                f"Updated PropelAuth org max_users to 1 for deleted subscription, "
                f"org_id={subscription.org_id}"
            )
        except Exception as e:
            logger.error(
                f"Failed to update PropelAuth org max_users for deleted subscription, "
                f"org_id={subscription.org_id}, error={e}"
            )
            # Don't fail the webhook if PropelAuth update fails, just log the error

        # 3. Delete the subscription record
        logger.info(
            f"Deleting subscription record, stripe_subscription_id={stripe_subscription_id}, "
            f"org_id={subscription.org_id}, plan_id={subscription.plan_id}"
        )
        crud.subscriptions.delete_subscription_by_stripe_id(db_session, stripe_subscription_id)
        db_session.commit()
    else:
        logger.error(
            f"Subscription record not found, stripe_subscription_id={stripe_subscription_id}"
        )
        raise BillingError(
            "Subscription record not found",
            error_code=status.HTTP_404_NOT_FOUND,

Review comment (suggestion):
`max_users=1`: maybe a robust way is to get the free plan from the db and get the `developer_seats` value? (and update the log message as well)

Code after:
        )
        # Don't fail the webhook if PropelAuth update fails, just log the error
        # The subscription update in our DB is still valid

    db_session.commit()

    logger.info(
        f"Successfully updated subscription record, stripe_subscription_id={latest_subscription_details.stripe_subscription_id}"
    )


async def handle_customer_subscription_deleted(
    subscription_data: dict, db_session: Session
) -> None:
    """
    Handles the customer.subscription.deleted event.
    1. Find the existing subscription record by stripe_subscription_id
    2. Delete the subscription record
    """
    logger.info(
        f"Handling customer.subscription.deleted event, subscription_data={subscription_data}"
    )
    stripe_subscription_id = subscription_data.get("id")

    if not stripe_subscription_id:
        logger.error(f"Subscription deleted event missing ID, payload={subscription_data}")
        raise BillingError(
            "Subscription deleted event missing ID",
            error_code=status.HTTP_400_BAD_REQUEST,
        )

    # 1. Find the existing subscription record by stripe_subscription_id
    subscription = crud.subscriptions.get_subscription_by_stripe_id(
        db_session, stripe_subscription_id
    )

    if subscription:
        # 2. Update PropelAuth organization max_users to free plan limit
        try:
            # Get the free plan to determine the correct max_users value
            plan = crud.plans.get_by_name(db_session, "free")
            if not plan:
                logger.exception(f"Free plan not found, org_id={subscription.org_id}")
                raise BillingError(
                    "Free plan not found",
                    error_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )

            max_users = plan.features["developer_seats"]
            logger.info(
                f"Using developer_seats from free plan, plan={plan.name}, max_users={max_users}"