psb_hack/api/app/infrastructure/courses_service.py

78 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import List, Optional
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.application.courses_repository import CoursesRepository
from app.core.constants import UserRoles
from app.domain.entities.courses import CourseRead, CourseCreate, CourseCreated
from app.domain.models import Course, User
from app.settings import Settings
class CoursesService:
def __init__(self, db: AsyncSession):
self.courses_repository = CoursesRepository(db)
self.settings = Settings()
async def get_all(self) -> List[CourseRead]:
courses = await self.courses_repository.get_all()
response = []
for course in courses:
response.append(
CourseRead.model_validate(course)
)
return response
async def get_all_for_me(self, user: User) -> Optional[List[CourseRead]]:
if user.role.title == self.settings.root_role_name:
courses = await self.courses_repository.get_all()
elif user.role.title == UserRoles.TEACHER:
courses = await self.courses_repository.get_all_for_teacher(user.id)
elif user.role.title == UserRoles.STUDENT:
courses = await self.courses_repository.get_all_for_enrollment(user.id)
else:
courses = []
response = []
for course in courses:
response.append(
CourseRead.model_validate(course)
)
return response
async def get_by_id(self, course_id: int) -> Optional[CourseRead]:
course = await self.courses_repository.get_by_id(course_id)
if course is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Курс с таким Id не найден')
return CourseRead.model_validate(course)
async def create(self, course: CourseCreate) -> CourseCreated: # ← возвращаем CourseCreated
course_model = Course(
title=course.title,
description=course.description,
)
course_model = await self.courses_repository.create(course_model)
return CourseCreated.model_validate(course_model)
async def update(self, course_id: int, course: CourseCreate) -> Optional[CourseRead]:
course_model = await self.courses_repository.get_by_id(course_id)
if course_model is None:
raise HTTPException(status_code=404, detail='Курс с таким ID не найден')
course_model.title = course.title
course_model.description = course.description
course_model = await self.courses_repository.update(course_model)
return CourseRead.model_validate(course_model)