103 lines
2.8 KiB
Python
103 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from .domain import ActiveEntitlementRecord
|
|
from .repository import AccessRepository
|
|
from .schema import (
|
|
AccessMeResponse,
|
|
ActiveEntitlementResponse,
|
|
ActiveSubscriptionResponse,
|
|
)
|
|
|
|
|
|
LIFETIME_PLAN_CODES = frozenset({
|
|
"LIFETIME_ALL",
|
|
"LIFETIME_ALL_USD",
|
|
})
|
|
|
|
|
|
class AccessService:
|
|
"""Resolve effective module access for an authenticated user."""
|
|
|
|
def __init__(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
repository: AccessRepository,
|
|
) -> None:
|
|
self.session = session
|
|
self.repository = repository
|
|
|
|
async def get_access_me(
|
|
self,
|
|
*,
|
|
user_id: UUID,
|
|
) -> AccessMeResponse:
|
|
subscriptions = await self.repository.get_active_subscriptions(
|
|
user_id
|
|
)
|
|
entitlements = await self.repository.get_active_entitlements(
|
|
user_id
|
|
)
|
|
|
|
module_codes: set[str] = {
|
|
item.module_code
|
|
for item in entitlements
|
|
if item.module_code
|
|
}
|
|
module_slugs: set[str] = {
|
|
item.module_slug
|
|
for item in entitlements
|
|
}
|
|
|
|
has_lifetime_access = any(
|
|
subscription.plan_code in LIFETIME_PLAN_CODES
|
|
for subscription in subscriptions
|
|
)
|
|
|
|
if has_lifetime_access:
|
|
for code, slug in await self.repository.get_all_active_modules():
|
|
if code:
|
|
module_codes.add(code)
|
|
module_slugs.add(slug)
|
|
|
|
return AccessMeResponse(
|
|
user_id=user_id,
|
|
active_subscriptions=[
|
|
ActiveSubscriptionResponse(
|
|
id=item.id,
|
|
plan_code=item.plan_code,
|
|
status=item.status,
|
|
started_at=item.started_at,
|
|
expires_at=item.expires_at,
|
|
)
|
|
for item in subscriptions
|
|
],
|
|
active_entitlements=[
|
|
self._entitlement_response(item)
|
|
for item in entitlements
|
|
],
|
|
unlocked_module_codes=sorted(module_codes),
|
|
unlocked_module_slugs=sorted(module_slugs),
|
|
)
|
|
|
|
@staticmethod
|
|
def _entitlement_response(
|
|
item: ActiveEntitlementRecord,
|
|
) -> ActiveEntitlementResponse:
|
|
return ActiveEntitlementResponse(
|
|
id=item.id,
|
|
module_id=item.module_id,
|
|
module_code=item.module_code,
|
|
module_slug=item.module_slug,
|
|
module_name=item.module_name,
|
|
status=item.status,
|
|
granted_at=item.granted_at,
|
|
expires_at=item.expires_at,
|
|
source_subscription_id=item.source_subscription_id,
|
|
source_plan_id=item.source_plan_id,
|
|
)
|