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) @bp.output(MessageSchema, status_code=200) def create_year_group(data: dict) -> dict: name = data['name'] mode = data['mode'] year_group = YearGroup.query.filter(YearGroup.name == name, YearGroup.mode == mode).first() 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('//') @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!') 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!") year_group_query.update(data) db.session.commit() return {"message": "Year group was updated!"} @bp.delete('//') @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!"}