recopytex/backend/service/services.py

106 lines
2.6 KiB
Python
Raw Normal View History

2022-12-30 07:15:37 +00:00
from backend.model.student import Student
2022-12-30 06:19:48 +00:00
from backend.model.tribe import Tribe
from backend.repository.abstract_repository import AbstractRepository
2022-12-30 07:15:37 +00:00
from backend.repository.student_sqlite_repository import StudentRepositoryError
2022-12-30 06:19:48 +00:00
from backend.repository.tribe_sqlite_repository import TribeRepositoryError
class TribeExists(Exception):
pass
2022-12-30 07:15:37 +00:00
class TribeDoesNotExist(Exception):
pass
class StudentExists(Exception):
pass
class StudentDoesExist(Exception):
2022-12-30 06:35:05 +00:00
pass
def add_tribe(name: str, level: str, tribe_repo: AbstractRepository, conn) -> Tribe:
tribe = Tribe(name=name, level=level)
2022-12-30 06:19:48 +00:00
try:
tribe_repo.add(tribe)
except TribeRepositoryError:
raise TribeExists(f"The tribe {tribe.name} already exists")
conn.commit()
return tribe
2022-12-30 06:35:05 +00:00
def update_tribe(name: str, level: str, tribe_repo: AbstractRepository, conn) -> Tribe:
2022-12-30 06:35:05 +00:00
tribe = Tribe(name=name, level=level)
try:
tribe_repo.update(name=name, tribe=tribe)
except TribeRepositoryError:
2022-12-30 07:15:37 +00:00
raise TribeDoesNotExist(f"The tribe {name} does not exists you can't update it")
2022-12-30 06:35:05 +00:00
conn.commit()
return tribe
def delete_tribe(name: str, tribe_repo: AbstractRepository, conn) -> None:
try:
tribe_repo.delete(name=name)
except TribeRepositoryError:
2022-12-30 07:15:37 +00:00
raise TribeDoesNotExist(f"The tribe {name} does not exists you can't delete it")
conn.commit()
def add_student(
name: str,
tribe: str,
student_repo: AbstractRepository,
tribe_repo: AbstractRepository,
conn,
) -> Student:
try:
_tribe = tribe_repo.get(tribe)
except TribeRepositoryError:
raise TribeDoesNotExist(
f"The tribe {tribe} does not exists. Can't add a student in it"
)
student = Student(name=name, tribe=_tribe)
try:
student_repo.add(student)
except StudentRepositoryError:
raise StudentExists(f"The student {student.name} already exists. Can't add it.")
conn.commit()
2022-12-30 07:15:37 +00:00
return student
2022-12-30 09:34:20 +00:00
def update_student(
id: str,
name: str,
tribe: str,
student_repo: AbstractRepository,
tribe_repo: AbstractRepository,
conn,
) -> Student:
try:
_tribe = tribe_repo.get(tribe)
except TribeRepositoryError:
raise TribeDoesNotExist(
f"The tribe {tribe} does not exists. Can't update a student with it"
)
student = Student(id=id, name=name, tribe=_tribe)
try:
student_repo.update(student)
except StudentRepositoryError:
raise StudentDoesExist(
f"The student {student.name} ({student.id=}) does not exists. Can't update it."
)
conn.commit()
return student