Spaces:
Running on T4
Running on T4
File size: 1,660 Bytes
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 | """Drill logs (E1, E2). drill_id must be in the AI coach drill library."""
from datetime import date
from functools import cache
from ai_coach.knowledge import all_drills
from sqlalchemy.ext.asyncio import AsyncSession
from app.common.schemas import Items
from app.core.errors import NotFound, ValidationFailed
from app.modules.accounts.models import Account
from app.modules.drills.repository import DrillLogRepository
from app.modules.drills.schemas import DrillLogIn, DrillLogOut
MAX_RANGE_DAYS = 90
@cache
def drill_ids() -> frozenset[str]:
return frozenset(d["id"] for d in all_drills())
class DrillLogService:
def __init__(self, db: AsyncSession):
self.logs = DrillLogRepository(db)
async def create(self, account: Account, body: DrillLogIn) -> DrillLogOut:
if body.drill_id not in drill_ids():
raise ValidationFailed(fields={"drill_id": "Unknown drill."})
if body.session_id and not await self.logs.owns_session(account.id, body.session_id):
raise NotFound()
log = await self.logs.create(owner_id=account.id, **body.model_dump())
return DrillLogOut.model_validate(log)
async def list(self, account: Account, start: date, end: date) -> Items[DrillLogOut]:
if end < start:
raise ValidationFailed(fields={"to": "Must be on or after from."})
if (end - start).days > MAX_RANGE_DAYS:
raise ValidationFailed(fields={"to": f"The range can be at most {MAX_RANGE_DAYS} days."})
logs = await self.logs.in_range(account.id, start, end)
return Items[DrillLogOut](items=[DrillLogOut.model_validate(log) for log in logs])
|