Spaces:
Runtime error
Runtime error
File size: 16,693 Bytes
17847d4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | """
Subscription service for managing user subscriptions and Stripe integration
"""
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from datetime import datetime
import logging
from ..models import User, Subscription, SubscriptionPlan
from .credit_service import credit_service
from .plan_service import plan_service
logger = logging.getLogger(__name__)
class SubscriptionService:
"""Service for managing user subscriptions"""
def get_user_subscription(self, db: Session, user_id: int) -> Optional[Subscription]:
"""
Get the active subscription for a user
Args:
db: Database session
user_id: User ID
Returns:
Subscription object or None if not found
"""
return (
db.query(Subscription)
.filter(Subscription.user_id == user_id)
.order_by(Subscription.created_at.desc())
.first()
)
def create_or_update_subscription(
self,
db: Session,
user: User,
plan_id: int,
stripe_subscription_data: Dict[str, Any]
) -> Subscription:
"""
Create or update a subscription from Stripe webhook data
Args:
db: Database session
user: User object
plan_id: SubscriptionPlan ID
stripe_subscription_data: Data from Stripe subscription object
Returns:
Created or updated Subscription object
"""
# Check if subscription exists
existing = self.get_user_subscription(db, user.id)
# Extract Stripe data
stripe_sub_id = stripe_subscription_data.get("id")
stripe_customer_id = stripe_subscription_data.get("customer")
status = stripe_subscription_data.get("status", "active")
current_period_start = stripe_subscription_data.get("current_period_start")
current_period_end = stripe_subscription_data.get("current_period_end")
cancel_at_period_end = stripe_subscription_data.get("cancel_at_period_end", False)
# Convert timestamps if they exist
period_start = None
period_end = None
if current_period_start:
period_start = datetime.fromtimestamp(current_period_start)
if current_period_end:
period_end = datetime.fromtimestamp(current_period_end)
if existing:
# Update existing subscription
existing.plan_id = plan_id
existing.status = status
existing.stripe_customer_id = stripe_customer_id
existing.stripe_subscription_id = stripe_sub_id
existing.current_period_start = period_start
existing.current_period_end = period_end
existing.cancel_at_period_end = cancel_at_period_end
existing.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing)
logger.info(f"Updated subscription for user {user.id} to plan {plan_id}")
return existing
else:
# Create new subscription
subscription = Subscription(
user_id=user.id,
plan_id=plan_id,
status=status,
stripe_customer_id=stripe_customer_id,
stripe_subscription_id=stripe_sub_id,
current_period_start=period_start,
current_period_end=period_end,
cancel_at_period_end=cancel_at_period_end
)
db.add(subscription)
db.commit()
db.refresh(subscription)
logger.info(f"Created subscription for user {user.id} with plan {plan_id}")
return subscription
def cancel_subscription(
self,
db: Session,
user_id: int,
immediate: bool = False
) -> Optional[Subscription]:
"""
Cancel a user's subscription
Args:
db: Database session
user_id: User ID
immediate: If True, cancel immediately; if False, cancel at period end
Returns:
Updated Subscription object or None if not found
"""
subscription = self.get_user_subscription(db, user_id)
if not subscription:
logger.warning(f"No subscription found for user {user_id}")
return None
if immediate:
subscription.status = "canceled"
subscription.cancel_at_period_end = False
else:
subscription.cancel_at_period_end = True
subscription.updated_at = datetime.utcnow()
db.commit()
db.refresh(subscription)
logger.info(f"Canceled subscription for user {user_id} (immediate={immediate})")
return subscription
def downgrade_to_free(self, db: Session, user_id: int) -> Subscription:
"""
Downgrade a user to the free tier
Args:
db: Database session
user_id: User ID
Returns:
Updated or created Subscription object
"""
# Get free plan
free_plan = plan_service.get_plan_by_name(db, "Free")
if not free_plan:
raise ValueError("Free plan not found in database")
# Get or create subscription
subscription = self.get_user_subscription(db, user_id)
if subscription:
subscription.plan_id = free_plan.id
subscription.status = "active"
subscription.stripe_subscription_id = None
subscription.cancel_at_period_end = False
subscription.updated_at = datetime.utcnow()
db.commit()
db.refresh(subscription)
else:
subscription = Subscription(
user_id=user_id,
plan_id=free_plan.id,
status="active"
)
db.add(subscription)
db.commit()
db.refresh(subscription)
# Reset credits to free tier
credit_service.reset_credits(
db,
user_id,
free_plan.id,
description="Downgraded to Free tier"
)
logger.info(f"Downgraded user {user_id} to Free tier")
return subscription
def assign_free_tier(self, db: Session, user: User) -> Subscription:
"""
Assign free tier to a new user
Args:
db: Database session
user: User object
Returns:
Created Subscription object
"""
# Get free plan
free_plan = plan_service.get_plan_by_name(db, "Free")
if not free_plan:
raise ValueError("Free plan not found in database")
# Create subscription
subscription = Subscription(
user_id=user.id,
plan_id=free_plan.id,
status="active"
)
db.add(subscription)
db.commit()
db.refresh(subscription)
# Initialize credits
credit_service.reset_credits(
db,
user.id,
free_plan.id,
description="New user - Free tier"
)
logger.info(f"Assigned Free tier to new user {user.id}")
return subscription
def handle_payment_succeeded(
self,
db: Session,
user_id: int,
stripe_invoice_data: Dict[str, Any]
) -> None:
"""
Handle successful payment (monthly renewal) - reset credits
Args:
db: Database session
user_id: User ID
stripe_invoice_data: Data from Stripe invoice object
"""
subscription = self.get_user_subscription(db, user_id)
if not subscription or not subscription.plan_id:
logger.warning(f"No subscription or plan found for user {user_id}")
return
# Reset credits to plan limit
credit_service.reset_credits(
db,
user_id,
subscription.plan_id,
description="Monthly subscription renewal"
)
logger.info(f"Reset credits for user {user_id} after successful payment")
def handle_payment_failed(
self,
db: Session,
user_id: int,
stripe_invoice_data: Dict[str, Any]
) -> None:
"""
Handle failed payment
Args:
db: Database session
user_id: User ID
stripe_invoice_data: Data from Stripe invoice object
"""
subscription = self.get_user_subscription(db, user_id)
if not subscription:
logger.warning(f"No subscription found for user {user_id}")
return
# Mark subscription as past_due
subscription.status = "past_due"
subscription.updated_at = datetime.utcnow()
db.commit()
logger.warning(f"Payment failed for user {user_id}, subscription marked as past_due")
def change_plan(
self,
db: Session,
user_id: int,
new_plan_id: int,
billing_period: str = "monthly"
) -> Subscription:
"""
Change user's subscription plan immediately with proration
Args:
db: Database session
user_id: User ID
new_plan_id: New plan ID to switch to
billing_period: "monthly" or "yearly"
Returns:
Updated Subscription object
"""
import stripe
subscription = self.get_user_subscription(db, user_id)
if not subscription or not subscription.stripe_subscription_id:
raise ValueError("No active Stripe subscription found")
# Get new plan
new_plan = plan_service.get_plan_by_id(db, new_plan_id)
if not new_plan:
raise ValueError(f"Plan {new_plan_id} not found")
# Get price ID based on billing period
if billing_period.lower() == "yearly":
new_price_id = new_plan.stripe_price_id_yearly
else:
new_price_id = new_plan.stripe_price_id_monthly or new_plan.stripe_price_id
if not new_price_id:
raise ValueError(f"Plan {new_plan.name} does not have a {billing_period} price ID")
# Get current Stripe subscription
stripe_sub = stripe.Subscription.retrieve(subscription.stripe_subscription_id)
# Get current subscription item ID
current_item_id = stripe_sub["items"]["data"][0]["id"]
# Modify subscription in Stripe with immediate proration
updated_sub = stripe.Subscription.modify(
subscription.stripe_subscription_id,
items=[{
"id": current_item_id,
"price": new_price_id,
}],
proration_behavior="always_invoice",
metadata={
"user_id": str(user_id),
"plan_id": str(new_plan_id),
"billing_period": billing_period
}
)
# Update database subscription
subscription.plan_id = new_plan_id
subscription.status = updated_sub["status"]
subscription.current_period_start = datetime.fromtimestamp(updated_sub["current_period_start"])
subscription.current_period_end = datetime.fromtimestamp(updated_sub["current_period_end"])
subscription.updated_at = datetime.utcnow()
db.commit()
db.refresh(subscription)
# Reset credits to new plan limit
credit_service.reset_credits(
db,
user_id,
new_plan_id,
description=f"Plan changed to {new_plan.name} ({billing_period})"
)
logger.info(f"Changed plan for user {user_id} to {new_plan.name} ({billing_period})")
return subscription
def reactivate_subscription(
self,
db: Session,
user_id: int
) -> Optional[Subscription]:
"""
Reactivate a canceled subscription
Args:
db: Database session
user_id: User ID
Returns:
Updated Subscription object or None if not found
"""
import stripe
subscription = self.get_user_subscription(db, user_id)
if not subscription or not subscription.stripe_subscription_id:
logger.warning(f"No subscription found for user {user_id}")
return None
# Reactivate in Stripe
stripe.Subscription.modify(
subscription.stripe_subscription_id,
cancel_at_period_end=False
)
# Update database
subscription.cancel_at_period_end = False
subscription.updated_at = datetime.utcnow()
db.commit()
db.refresh(subscription)
logger.info(f"Reactivated subscription for user {user_id}")
return subscription
def get_subscription_info(self, db: Session, user_id: int) -> Dict[str, Any]:
"""
Get comprehensive subscription information for a user
Args:
db: Database session
user_id: User ID
Returns:
Dictionary with subscription details
"""
subscription = self.get_user_subscription(db, user_id)
# Get all available plans
all_plans = plan_service.get_all_active_plans(db)
available_plans = [
plan_service.get_plan_info(db, plan.id)
for plan in all_plans
]
if not subscription:
return {
"has_subscription": False,
"status": None,
"plan": None,
"credits": None,
"available_plans": available_plans,
"current_period_start": None,
"current_period_end": None,
"next_billing_amount": None,
"billing_period": None,
"cancel_at_period_end": False
}
# Get plan info
plan_info = None
if subscription.plan_id:
plan_info = plan_service.get_plan_info(db, subscription.plan_id)
# Get credit info
credit_info = credit_service.get_balance_info(db, user_id)
# Add credits_per_month from plan if available
if plan_info and credit_info:
credit_info["credits_per_month"] = plan_info.get("credits_per_month", 0)
# Determine billing period from Stripe if available
billing_period = None
next_billing_amount = None
if subscription.stripe_subscription_id:
try:
import stripe
stripe_sub = stripe.Subscription.retrieve(subscription.stripe_subscription_id)
# Determine billing period from interval
if stripe_sub.get("items", {}).get("data", []):
interval = stripe_sub["items"]["data"][0]["price"].get("recurring", {}).get("interval")
billing_period = "yearly" if interval == "year" else "monthly"
# Get next billing amount
if stripe_sub.get("items", {}).get("data", []):
price = stripe_sub["items"]["data"][0]["price"]
next_billing_amount = price.get("unit_amount", 0) / 100 # Convert from cents
except Exception as e:
logger.warning(f"Could not fetch Stripe subscription details: {e}")
return {
"has_subscription": True,
"status": subscription.status,
"plan": plan_info,
"credits": credit_info,
"stripe_subscription_id": subscription.stripe_subscription_id,
"current_period_start": subscription.current_period_start.isoformat() if subscription.current_period_start else None,
"current_period_end": subscription.current_period_end.isoformat() if subscription.current_period_end else None,
"cancel_at_period_end": subscription.cancel_at_period_end,
"available_plans": available_plans,
"billing_period": billing_period,
"next_billing_amount": next_billing_amount
}
# Singleton instance
subscription_service = SubscriptionService()
|