Exemplo n.º 1
0
 def get_all_attendances(self, page: int, grade: str, year: int, per_page: int = 20) -> (List, Any):
     """
     get all attendance
     :params page
     :params grade
     :params year
     :params per_page
     :return: attendance list of dict
     """
     try:
         if year and not grade:
             attendances = AttendanceModel.get_attendances_by_year(page, year, per_page)
         elif grade and not year:
             attendances = AttendanceModel.get_attendances_by_grade(page, grade, per_page)
         elif year and grade:
             attendances = AttendanceModel.get_attendances_by_grade_year(page, grade, year, per_page)
         else:
             attendances = AttendanceModel.get_all_attendances(page, per_page)
         return {
             "attendances": [attendance.attendance_dict(school, student) for attendance, school, student in
                             attendances.items],
             "total_count": attendances.total,
             "current_page": attendances.page,
             "next_page": attendances.next_num,
             "prev_page": attendances.prev_num,
             "pages": attendances.pages
         }
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="GET Attendance SQL ERROR")
Exemplo n.º 2
0
 def update_attendance_by_id(self, attendance_id: int, data: Dict) -> bool:
     """
     put attendance by id
     :param attendance_id:
     :param data:
     :return:
     """
     if not data:
         raise RequestDataEmpty("Attendance data is empty")
     if not self.input_validate.validate_json(data, attendance_schema):
         self.logger.error("All attendance field input must be required.")
         raise ValidateFail("Attendance update validation fail")
     try:
         self.logger.info("Update attendance info by attendance_id:{}".format(attendance_id))
         return AttendanceModel.update_attendance(attendance_id, AttendanceModel(
             student_id=data["student_id"],
             school_id=data["school_id"],
             grade=data["grade"],
             year=data["year"],
             enrolled_date=data["enrolled_date"]))
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="Update attendance by ID SQL ERROR")
     except SQLCustomError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="No record for requested attendance")
Exemplo n.º 3
0
    def post(self):
        parser.add_argument('present_student',
                            type=int,
                            action="append",
                            help='student field required',
                            required=True)
        parser.add_argument('absant_student',
                            type=int,
                            action="append",
                            help='student field required',
                            required=True)

        data = parser.parse_args()

        student_attendance = []
        y, m, d = data['date'].split('-')
        class_date = datetime.datetime(int(y), int(m), int(d))

        if AttendanceModel.find_by_date(data['class_id'],
                                        data['department_id'],
                                        data['subject_id'], class_date):
            return {
                'message':
                'This date {} data already exists '.format(data['date'])
            }

        present_data_add = [
            student_attendance.append({
                "date": class_date,
                "class_id": data['class_id'],
                "department_id": data['department_id'],
                "subject_id": data['subject_id'],
                "student_id": p_data,
                "status": "Present",
            }) for p_data in data['present_student']
        ]
        present_data_add = [
            student_attendance.append({
                "date": class_date,
                "class_id": data['class_id'],
                "department_id": data['department_id'],
                "subject_id": data['subject_id'],
                "student_id": p_data,
                "status": "Absent",
            }) for p_data in data['absant_student']
        ]

        try:
            for atten_data in student_attendance:
                add_attendance = AttendanceModel(
                    **atten_data)  #CREATE MODEL DATA FOR SAVE
                add_attendance.save_to_db(
                )  #CALL THIS FUNCTION FOR COMMIT DATA

            return {'message': 'Attendance data added successfully'}, 200

        except:
            return {'message': 'Something went wrong'}, 500
Exemplo n.º 4
0
    def get_all_attendances(self,
                            page: int,
                            grade: Optional[str],
                            year: Optional[int],
                            keyword: Optional[str],
                            per_page: int = 20) -> (List, Any):
        """
        get all attendance
        :params page
        :params grade
        :params year
        :params keyword
        :params per_page
        :return: attendance list of dict
        """
        try:
            if year or grade or keyword:
                self.logger.info(
                    f"Searching attendances: year: {year}, grade: {grade}, keyword: {keyword}"
                )
                attendances = AttendanceModel.search_attendances(
                    grade=grade,
                    year=year,
                    keyword=keyword,
                    page=page,
                    per_page=per_page)
            else:
                self.logger.info("Getting all attendances")
                attendances = AttendanceModel.get_all_attendances(
                    page=page, per_page=per_page)

            return {
                "attendances": [
                    attendance.attendance_dict(attendance.school,
                                               attendance.student)
                    for attendance in attendances.items
                ],
                "total_count":
                attendances.total,
                "current_page":
                attendances.page,
                "next_page":
                attendances.next_num,
                "prev_page":
                attendances.prev_num,
                "pages":
                attendances.pages
            }
        except SQLAlchemyError as error:
            self.logger.error("Error: {}".format(error))
            raise SQLCustomError(description="GET Attendance SQL ERROR")
Exemplo n.º 5
0
 def post(self):
     data = parser.parse_args()
     y, m, d = data['date'].split('-')
     class_date = datetime.datetime(int(y), int(m), int(d))
     return AttendanceModel.return_all(data['class_id'],
                                       data['department_id'],
                                       data['subject_id'], class_date)
Exemplo n.º 6
0
 def create_attendance(self, data: Dict) -> bool:
     """
     create attendance records
     :param data:
     :return:
     """
     if not data:
         raise RequestDataEmpty("Attendance data is empty")
     if not self.input_validate.validate_json(data, attendance_schema):
         self.logger.error("All attendance field input must be required.")
         raise ValidateFail("Attendance validation fail")
     try:
         return AttendanceModel.create_attendance(AttendanceModel(**data))
     except SQLAlchemyError as error:
         self.logger.error("Attendance create fail. error %s, format: %s ",
                           error, traceback.format_exc())
         raise SQLCustomError("Attendance create fail")
Exemplo n.º 7
0
 def get_all_attendance_years() -> List[int]:
     """
     get all attendance
     :params page
     :params grade
     :params year
     :params per_page
     :return: attendance list of dict
     """
     return AttendanceModel.get_all_attendance_years()
Exemplo n.º 8
0
    def get(self):
        attend = AttendanceModel.find_course_by_userid(get_jwt_identity())
        if attend:
            all_attend = [{
                'CourseName': user.course_name,
                'Percentage': user.percentage,
                'Ratio': user.ratio
            } for user in attend]
            return jsonify(all_attend)

        return {"message": "User data not found!"}, 404
Exemplo n.º 9
0
 def delete_attendance_by_id(self, attendance_id: int) -> bool:
     """
     delete attendance by id
     :param attendance_id:
     :return:
     """
     try:
         self.logger.info("Delete attendance info by attendance_id:{}".format(attendance_id))
         return AttendanceModel.delete_attendance_by_id(attendance_id)
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="Delete attendance by ID SQL ERROR")
Exemplo n.º 10
0
 def get_all_attendance_records(self) -> (List, Any):
     """
     get all attendance
     :return: attendance list of dict
     """
     try:
         self.logger.info("Get attendance list")
         return [attendance.attendance_dict(school, student) for attendance, school, student in
                 AttendanceModel.get_all_attendance()]
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="GET Attendance SQL ERROR")
Exemplo n.º 11
0
 def create_attendance(self, data: Dict) -> bool:
     """
     create attendance records
     :param data:
     :return:
     """
     if not data:
         raise RequestDataEmpty("attendance data is empty")
     if not self.input_validate.validate_json(data, attendance_schema):
         self.logger.error("All attendance field input must be required.")
         raise ValidateFail("Attendance validation fail")
     try:
         return AttendanceModel.create_attendance(AttendanceModel(
             student_id=data["student_id"],
             school_id=data["school_id"],
             grade=data["grade"],
             year=data["year"],
             enrolled_date=data["enrolled_date"]))
     except SQLAlchemyError as error:
         self.logger.error("Attendance create fail. error %s", error)
         raise SQLCustomError("Attendance create fail")
Exemplo n.º 12
0
 def get_attendance_by_id(self, attendance_id: int) -> Optional[List]:
     """
     get attendance info by id
     :param attendance_id:
     :return: attendance list of dict
     """
     try:
         self.logger.info("Get attendance info by attendance_id:{}".format(attendance_id))
         return [attendance.attendance_dict(school, student) for attendance, school, student in
                 AttendanceModel.get_attendance_by_id(attendance_id)]
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(traceback.format_exc()))
         raise SQLCustomError(description="GET Attendance by ID SQL ERROR")
Exemplo n.º 13
0
def attendance():
    with app.app_context():
        users = UserModel.query.all()
        AttendanceModel.query.delete()
        amizone = amizonebot()
        for user in users:
            amizone.login(user.username, user.password)
            attend = amizone.getAttendance()
            i = 1
            while i < len(attend):
                AttendanceModel(
                    user_id=user.id, course_name=attend[i-1], percentage=attend[i+1-1], ratio=attend[i+2-1]).save_to_db()
                i = i+3
Exemplo n.º 14
0
 def get_all_attendances(self, page) -> (List, Any):
     """
     get all attendance
     :params page
     :return: attendance list of dict
     """
     try:
         self.logger.info("Get attendance list")
         attendances = AttendanceModel.get_all_attendances(page)
         return [
             attendance.attendance_dict(school, student)
             for attendance, school, student in attendances.items
         ], attendances.total
     except SQLAlchemyError as error:
         self.logger.error("Error: {}".format(error))
         raise SQLCustomError(description="GET Attendance SQL ERROR")
Exemplo n.º 15
0
    def post(self):
        data = _user_parser.parse_args()

        user = UserModel.find_user_by_username(data["username"])
        expires = datetime.timedelta(days=30)
        if user and user.password == data["password"]:
            # Puts User ID as Identity in JWT
            access_token = create_access_token(identity=user.id,
                                               fresh=True,
                                               expires_delta=expires)
            refresh_token = create_refresh_token(
                identity=user.id)  # Puts User ID as Identity in JWT
            return {
                "access_token": access_token,
                "refresh_token": refresh_token
            }, 200

        amizone = amizonebot()
        scraperdata = amizone.login(usern=data["username"],
                                    passw=data["password"])

        user = UserModel(data["username"], data["password"],
                         scraperdata["fullname"], scraperdata["profilepic"])
        user.save_to_db()

        attend = amizone.getAttendance()
        schedule = amizone.getSchedule()
        i = 1
        while i < len(attend):
            AttendanceModel(user_id=user.id,
                            course_name=attend[i - 1],
                            percentage=attend[i + 1 - 1],
                            ratio=attend[i + 2 - 1]).save_to_db()
            i = i + 3

        i = 2
        while i < len(schedule):
            ScheduleModel(user_id=user.id,
                          course_details=schedule[i],
                          prof_name=schedule[i + 1]).save_to_db()
            i = i + 2

        # except:
        #     print(Exception.__name__)
        #     return {
        #         "message": "User not found!"
        #     }, 404
        # finally:
        #     return {
        #         "message": "User not found!"
        #     }, 404

        # Puts User ID as Identity in JWT
        access_token = create_access_token(identity=user.id,
                                           fresh=True,
                                           expires_delta=expires)
        refresh_token = create_refresh_token(identity=user.id)

        return {
            "message": "User {} created!".format(data["username"]),
            "access_token": access_token,
            "refresh_token": refresh_token
        }, 200