Spaces:
Running on T4
Running on T4
File size: 2,478 Bytes
2756f0f 6437539 2756f0f be69d1e 2756f0f 6437539 2756f0f | 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 | """Plan and weekly usage. Shared by GET /me, GET /me/entitlement, POST /sessions and the swing report.
The plan is derived (pro while an active subscription has not expired), never stored on the account.
Usage counts analysed sessions in a rolling window, including deleted ones, so deleting a rep does not refund it.
"""
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from uuid import UUID
from sqlalchemy import exists, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.common.schemas import ResponseModel
from app.core.config import get_settings
from app.core.errors import PlanLimitReached
from app.modules.billing.models import Subscription
from app.modules.sessions.models import SwingSession
# Analyses a free account gets per window. Fixed in code on purpose: no environment variable can change it.
# The 402 message in app.core.errors.PlanLimitReached states the same number.
FREE_WEEKLY_LIMIT = 20
class Entitlement(ResponseModel):
plan: str
weekly_limit: int | None
used_this_week: int
left: int | None
window_days: int
@dataclass
class EntitlementService:
db: AsyncSession
async def get(self, account_id: UUID) -> Entitlement:
settings = get_settings()
now = datetime.now(UTC)
# One statement for both facts: each extra statement is a network round trip.
used, pro = (await self.db.execute(select(
select(func.count()).where(
SwingSession.owner_id == account_id,
SwingSession.analyzed_at >= now - timedelta(days=settings.entitlement_window_days)).scalar_subquery(),
exists().where(
Subscription.account_id == account_id,
Subscription.status.in_(("active", "grace")),
Subscription.expires_at > now),
))).one()
if pro:
return Entitlement(plan="pro", weekly_limit=None, used_this_week=used, left=None,
window_days=settings.entitlement_window_days)
limit = FREE_WEEKLY_LIMIT
return Entitlement(plan="free", weekly_limit=limit, used_this_week=used, left=max(0, limit - used),
window_days=settings.entitlement_window_days)
async def ensure_can_analyze(self, account_id: UUID) -> None:
entitlement = await self.get(account_id)
if entitlement.left is not None and entitlement.left <= 0:
raise PlanLimitReached()
|