75 lines
2.5 KiB
Python
75 lines
2.5 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from app.api.deps import get_training_repository, get_user_repository
|
|
from app.core.database.repository import TrainingRepository
|
|
from app.core.database.user_repository import UserRepository
|
|
from app.core.dto.training import TrainingDTO
|
|
from app.core.dto.user import UserRole
|
|
from app.schemas.trainings import TrainingUpdate
|
|
from app.core.parsers.obsidian import parse_training_data
|
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/obsidian/")
|
|
async def obsidian_trainings_list():
|
|
return {"data": parse_training_data()}
|
|
|
|
|
|
@router.get("/", response_model=List[TrainingDTO])
|
|
async def get_trainings_list(
|
|
repository: TrainingRepository = Depends(get_training_repository),
|
|
):
|
|
return await repository.list()
|
|
|
|
|
|
async def _check_participant(
|
|
repository: UserRepository, user_id: int, role: UserRole
|
|
) -> None:
|
|
user = await repository.get(user_id)
|
|
if user is None or user.role != role:
|
|
raise HTTPException(
|
|
status_code=422, detail=f"User {user_id} is not an existing {role.value}"
|
|
)
|
|
|
|
|
|
@router.get("/{training_id}/", response_model=TrainingDTO)
|
|
async def get_training(
|
|
training_id: int,
|
|
repository: TrainingRepository = Depends(get_training_repository),
|
|
):
|
|
training = await repository.get(training_id)
|
|
if training is None:
|
|
raise HTTPException(status_code=404, detail="Training not found")
|
|
return training
|
|
|
|
|
|
@router.put("/{training_id}/", response_model=TrainingDTO)
|
|
async def update_training(
|
|
training_id: int,
|
|
payload: TrainingUpdate,
|
|
repository: TrainingRepository = Depends(get_training_repository),
|
|
user_repository: UserRepository = Depends(get_user_repository),
|
|
):
|
|
"""Replace the training: its date, trainee, trainer, exercises and approaches."""
|
|
await _check_participant(user_repository, payload.trainee_id, UserRole.trainee)
|
|
if payload.trainer_id is not None:
|
|
await _check_participant(user_repository, payload.trainer_id, UserRole.trainer)
|
|
training = TrainingDTO.model_validate(payload.model_dump())
|
|
if not await repository.replace(training_id, training):
|
|
raise HTTPException(status_code=404, detail="Training not found")
|
|
return await repository.get(training_id)
|
|
|
|
|
|
@router.delete("/{training_id}/")
|
|
async def delete_training(
|
|
training_id: int,
|
|
repository: TrainingRepository = Depends(get_training_repository),
|
|
):
|
|
deleted = await repository.delete([training_id])
|
|
if not deleted:
|
|
raise HTTPException(status_code=404, detail="Training not found")
|
|
return {"status": "ok"}
|