2022-11-12 16:18:07 +01:00
|
|
|
from flask import abort
|
|
|
|
from apiflask import APIBlueprint
|
|
|
|
|
|
|
|
from ...students.models import YearGroup
|
|
|
|
from ..schemas import YearGroupSchema, MessageSchema, YearGroupPaginationSchema, YearGroupQuerySchema
|
|
|
|
from ...dependencies import db
|
|
|
|
from ...base.utils import paginate_models
|
|
|
|
|
|
|
|
bp = APIBlueprint("year_group", __name__, url_prefix="/year-group")
|
|
|
|
|
|
|
|
|
|
|
|
@bp.post('/')
|
|
|
|
@bp.input(YearGroupSchema)
|
2023-01-06 22:35:47 +01:00
|
|
|
@bp.output(MessageSchema, status_code=201)
|
2022-11-12 16:18:07 +01:00
|
|
|
def create_year_group(data: dict) -> dict:
|
|
|
|
name = data['name']
|
2022-11-17 10:21:36 +01:00
|
|
|
mode = data['mode']
|
|
|
|
year_group = YearGroup.query.filter(YearGroup.name == name, YearGroup.mode == mode).first()
|
2022-11-12 16:18:07 +01:00
|
|
|
if year_group is not None:
|
|
|
|
abort(400, "Year group has already exists!")
|
|
|
|
|
|
|
|
yg = YearGroup(**data)
|
|
|
|
db.session.add(yg)
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
return {"message": "Year group was created!"}
|
|
|
|
|
|
|
|
|
|
|
|
@bp.get('/')
|
|
|
|
@bp.input(YearGroupQuerySchema, location='query')
|
|
|
|
@bp.output(YearGroupPaginationSchema)
|
|
|
|
def list_of_year_groups(query: dict) -> dict:
|
|
|
|
page = query.get('page')
|
|
|
|
per_page = query.get('per_page')
|
|
|
|
|
|
|
|
year_group_query = YearGroup.query.order_by(db.desc(YearGroup.created_at))
|
|
|
|
data = paginate_models(page, year_group_query, per_page)
|
|
|
|
|
|
|
|
return {
|
|
|
|
"year_groups": data['items'],
|
|
|
|
"max_pages": data['max_pages']
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@bp.put('/<int:id>/')
|
|
|
|
@bp.input(YearGroupSchema)
|
|
|
|
@bp.output(MessageSchema)
|
|
|
|
def update_year_of_group(id: int, data: dict) -> dict:
|
|
|
|
if not data:
|
|
|
|
abort(400, 'You have passed empty data!')
|
|
|
|
|
|
|
|
year_group_query = YearGroup.query.filter(YearGroup.id == id)
|
|
|
|
year_group = year_group_query.first()
|
|
|
|
|
|
|
|
if year_group is None:
|
|
|
|
abort(404, 'Not found year group!')
|
|
|
|
|
2022-11-17 10:21:36 +01:00
|
|
|
name = data['name']
|
|
|
|
mode = data['mode']
|
|
|
|
year_group = YearGroup.query.filter(YearGroup.name == name, YearGroup.mode == mode, YearGroup.id != id).first()
|
|
|
|
if year_group is not None:
|
|
|
|
abort(400, "Year group has already exists!")
|
|
|
|
|
2022-11-12 16:18:07 +01:00
|
|
|
year_group_query.update(data)
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
return {"message": "Year group was updated!"}
|
|
|
|
|
|
|
|
|
|
|
|
@bp.delete('/<int:id>/')
|
|
|
|
@bp.output(MessageSchema, status_code=202)
|
|
|
|
def delete_year_of_group(id: int) -> dict:
|
|
|
|
year_group = YearGroup.query.filter_by(id=id).first()
|
|
|
|
if year_group is None:
|
|
|
|
abort(404, f"Year group doesn't exist!")
|
|
|
|
db.session.delete(year_group)
|
|
|
|
db.session.commit()
|
|
|
|
return {"message": "Year group was deleted!"}
|