Пример #1
0
    def decorated(*args, **kwargs):
        token = None

        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        if not token:
            return create_error_exception(message="Token is missing",
                                          response_code=401,
                                          value="Token is missing")

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'])
            db = DatabaseHelper()
            result = db.get_user(data['staff_id'])

            if not result['response']:
                return create_error_exception(message="User not found",
                                              response_code=401,
                                              value="User not found")

            current_user = result['value']

        except Exception as e:
            print("Error %d: %s" % (e.args[0], e.args[1]))
            return create_error_exception(message="Token is missing",
                                          response_code=401,
                                          value="Token is missing")

        return f(current_user, *args, **kwargs)
Пример #2
0
def get_activity_list(current_user):
    year = request.args.get('year')

    db = DatabaseHelper()
    result = db.get_activity_list(year)

    return api_helper.return_response(result)
Пример #3
0
def get_all_department_data(current_user):
    dept_id = request.args.get('dept_id')

    db = DatabaseHelper()
    result = db.get_department_detail(dept_id)

    return api_helper.return_response(result)
Пример #4
0
    def student_tracking(self, id_student):
        connect = DatabaseHelper()
        data = connect.get_student_tracking(id_student)
        value = {}
        if data['value']:
            df = pd.DataFrame(data['value'])
            if (not df.gpa.empty) & (not df.current_gpax.empty):
                df = df.sort_values(by=['education_year', 'semester'])
                df_drop_s = df[df['semester'] != 'S']
                df_drop_s.reset_index(inplace=True)

                df_tracking = df_drop_s.gpa
                value = {
                    'student_id': id_student,
                    'firstname': df_drop_s.loc[0, 'firstname'],
                    'lastname': df_drop_s.loc[0, 'lastname'],
                    'gpax': df_drop_s.current_gpax.loc[0],
                    'trackking': df_tracking.to_dict()
                }
                response = True
                message = "Analyze Subject Successfully"
            else:
                response = False
                message = "Don't have Data"

        else:
            response = False
            message = "Don't have Data"

        return inner_res_helper.make_inner_response(response, message, value)
Пример #5
0
def add_student_data(current_user):
    try:
        file = request.files['upload']
        if file and Constant.allowed_file(file.filename):
            destination = upload_helper.upload_file(
                store_folder=Constant.STUDENT_FOLDER, file=file)
        else:
            return api_helper.create_error_exception(
                "Type of file is not match", "file not match", 418)
    except Exception as e:
        print(e)
        return api_helper.create_error_exception(
            str(e), "Can not find a file with " + str(e.args[0]), 400)

    if destination['response']:
        data_helper = DataHelper()
        insert_value = data_helper.read_new_student_file(destination['value'])
        if insert_value['response']:
            db = DatabaseHelper()
            insert = db.insert_new_student_data(insert_value['value'])
        else:
            return api_helper.return_response(insert_value)
    else:
        return api_helper.return_response(destination)
    return api_helper.return_response(insert)
Пример #6
0
def get_project_list():
    project_type = request.args.get('project_type')

    db = DatabaseHelper()
    result = db.get_project_list(project_type)

    return api_helper.return_response(result)
Пример #7
0
def sign_in():
    auth_data = request.get_json()
    if not auth_data or not auth_data['username'] or not auth_data['password']:
        return api_helper.create_error_exception(message="Credentials data not found.", response_code=401,
                                                 value="Credentials data not found.")

    connect = DatabaseHelper()
    result = connect.get_user_for_auth(auth_data['username'])

    if not result['response']:
        return api_helper.create_error_exception(message="Cloud not verify.", response_code=401,
                                                 value="Cloud not verify.")

    user = result['value']
    user = list(user[0])
    user_type = "user" if user[1] == -1 else "admin"

    userData = {
        'name': user[2],
        'type': user_type
    }
    if check_password_hash(user[4], auth_data['password']):
        token = jwt.encode({'staff_id': user[0], 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60)},
                           app.config['SECRET_KEY'])
        return api_helper.create_response(message="Signin successful",
                                          data={'token': token.decode('UTF-8'), 'userData': userData},
                                          response_code=200, response=True)

    return api_helper.create_error_exception(message="Cloud not verify.", response_code=401, value="Cloud not verify.")
Пример #8
0
def get_branch_data():
    branch_id = request.args.get('branch_id')

    db = DatabaseHelper()
    data = db.get_branch(branch_id)

    return api_helper.return_response(data)
Пример #9
0
def get_department_data():
    dept_id = request.args.get('dept_id')

    db = DatabaseHelper()
    data = db.get_department(dept_id)

    return api_helper.return_response(data)
Пример #10
0
def get_probation_student(current_user):
    # this api need department id and status id
    department = request.args.get('dept_id')
    status = request.args.get('status_id')

    db = DatabaseHelper()
    data = db.get_student_status(department, status)

    return api_helper.return_response(data)
Пример #11
0
def delete_activity(current_user):
    act_id = request.args.get('act_id')
    project_type = request.args.get('project_type')

    if act_id is None or act_id == "null" or act_id == "undefined":
        return api_helper.create_error_exception(message="Can not get value.",
                                                 response_code=400,
                                                 value="Can not get value.")

    db = DatabaseHelper()
    result = db.delete_activity(act_id)

    return api_helper.return_response(result)
Пример #12
0
def get_student_list(current_user):
    year = request.args.get('year')

    if year == 'null' or year is None:
        return api_helper.create_response("Can not found input.", False,
                                          "Can not found input.", 400)

    year = year[2:]

    db = DatabaseHelper()
    result = db.get_student_by_year(year)

    return api_helper.return_response(result)
Пример #13
0
def create_staff():
    if request.method == 'POST':
        data = request.get_json()

        staff_id = data['staff_id']
        first_name = data['firstname']
        last_name = data['lastname']
        hashed_pass = generate_password_hash(data['password'], method='sha256')

        connect = DatabaseHelper()
        result = connect.create_user(staff_id, first_name, last_name, hashed_pass)

        return api_helper.return_response(result)
Пример #14
0
def insert_academic_record(current_user):
    # this api need education year (2561, 2562) and semester (1,2 or S)
    year = request.form.get('year')
    semester = request.form.get('semester')

    if year is None or semester is None:
        value = {'year': year, 'semester': semester}
        return api_helper.create_response(message="One of these is Null",
                                          response=False,
                                          data=[value],
                                          response_code=418)

    try:
        file = request.files['upload']
        if file and Constant.allowed_file(file.filename):
            destination = upload_helper.upload_file(
                store_folder=Constant.ACADEMIC_FOLDER, file=file, year=year)
        else:
            return api_helper.create_error_exception(
                "Type of file is not match", "file not match", 418)
    except Exception as e:
        print(e)
        return api_helper.create_error_exception(
            str(e), "Can not find a file with " + str(e.args[0]), 400)

    if destination['response']:
        data_helper = DataHelper()
        insert_value = data_helper.read_academic_file(destination['value'],
                                                      year, semester)
        if insert_value['response']:
            data = insert_value['value']
            db = DatabaseHelper()
            academic_record = db.insert_academic_record(
                data['academic_record'], data['gpa_record'],
                data['gpax_record'], data['status_record'])
            if not academic_record['response']:
                return api_helper.create_response(
                    message=academic_record['message'],
                    response=False,
                    response_code=500,
                    data=academic_record['value'])

    return api_helper.create_response(message="Developing",
                                      response=True,
                                      response_code=200,
                                      data="Developing")
Пример #15
0
def delete_admission_list():
    year = request.args.get('year')
    round_id = request.args.get('round_id')
    channel_id = request.args.get('channel_id')

    if year == 'null' or round_id == 'null' or channel_id == 'null':
        return api_helper.create_error_exception("Some data null",
                                                 "Some data null", 400)

    data = {
        'year': int(year),
        'round_id': int(round_id),
        'channel_id': int(channel_id)
    }

    db = DatabaseHelper()
    result = db.delete_admission_data(data)
    return api_helper.return_response(result)
Пример #16
0
def insert_activity_participant(current_user):
    form = request.form
    activity_id = form.get('activity_id')
    project_id = form.get('project_id')
    project_type = form.get('project_type')
    year = form.get('year')

    data = [activity_id, project_id, year, project_type]

    if None in data:
        return api_helper.create_error_exception(
            message="Can not found some value.",
            response_code=400,
            value="Can not found some value.")
    try:
        file = request.files['upload']
        if file and Constant.allowed_file(file.filename):
            destination = upload_helper.upload_file(
                Constant.ACTIVITY_FOLDER + "/{}".format(project_id), file,
                year)
        else:
            return api_helper.create_error_exception(
                "Type of file is not match", "file not match", 418)
    except Exception as e:
        print(e)
        return api_helper.create_error_exception(
            str(e), "Can not find a file with " + str(e.args[0]), 400)

    if destination['response']:
        data_helper = DataHelper()
        insert_value = data_helper.read_activity_participant(
            destination['value'], activity_id)
        if insert_value['response']:
            db = DatabaseHelper()
            result = db.insert_activity_participant(insert_value['value'],
                                                    project_type)
        else:
            return api_helper.return_response(insert_value)
    else:
        return api_helper.return_response(destination)

    return api_helper.return_response(result)
Пример #17
0
def add_new_activity(current_user):
    form = request.form
    activity_id = form.get('activity_id')
    project_id = form.get('project_id')
    activity_name = form.get('activity_name')
    activity_budget = form.get('budget')
    year = form.get('year')

    data = [activity_id, project_id, activity_name, activity_budget, year]

    if None in data:
        return api_helper.create_error_exception(
            message="Can not found some value.",
            response_code=400,
            value="Can not found some value.")

    db = DatabaseHelper()
    result = db.create_activity(data)

    return api_helper.return_response(result)
Пример #18
0
def insert_admission(current_user):
    # This api need "Year" as year , "Admission type" as admission_type
    # and "Admission channel" as channel to be a parameter

    year = request.form.get('year')
    channel = request.form.get('channel')

    if year is None or channel is None:
        value = {"year": year, "channel": channel}
        return api_helper.create_response(message="One of these is Null",
                                          response=False,
                                          data=[value],
                                          response_code=418)

    try:
        file = request.files['upload']
        if file and Constant.allowed_file(file.filename):
            destination = upload_helper.upload_file(Constant.ADMISSION_FOLDER,
                                                    file, year)
        else:
            return api_helper.create_error_exception(
                "Type of file is not match", "file not match", 418)
    except Exception as e:
        print(e)
        return api_helper.create_error_exception(
            str(e), "Can not find a file with " + str(e.args[0]), 400)

    if destination['response']:
        data_helper = DataHelper()
        insert_value = data_helper.read_admission(channel, year,
                                                  destination['value'])
        if insert_value['response']:
            db = DatabaseHelper()
            insert = db.insert_admission(insert_value['value'])
        else:
            return api_helper.return_response(insert_value)
    else:
        return api_helper.return_response(destination)
    return api_helper.return_response(insert)
Пример #19
0
    def subject_by_branch(self, branch_id, semester, education_year):
        connect = DatabaseHelper()
        data = connect.subject_by_branch(branch_id, semester, education_year)
        value = {}
        if data['value']:
            df = pd.DataFrame(data['value'])
            list_grade = {
                'A': 4,
                'B+': 3.5,
                'B': 3,
                'C+': 2.5,
                'C': 2,
                'D+': 1.5,
                'D': 1,
                'F': 0,
                'Fe': 0
            }
            df['grade'].replace(list_grade, inplace=True)
            df = df[df['grade'] != 'W']
            df['grade'] = df.grade.astype(int)
            grouped = df.groupby(
                ["subject_code", "subject_name_en",
                 "subject_weigth"])["grade"].agg(['size', 'mean', 'std'])
            grouped = grouped.reset_index(
                level=['subject_name_en', 'subject_weigth'])
            grouped = grouped.round(2)
            value = {
                'subject': grouped.to_dict('index'),
            }
            response = True
            message = "Analyze Subject Successfully"
        else:
            response = False
            message = "Don't have Data"

        return inner_res_helper.make_inner_response(response, message, value)
Пример #20
0
def add_activity_project(current_user):
    data = request.get_json()

    if data is None:
        return api_helper.create_error_exception(message="Can not get value.",
                                                 response_code=400,
                                                 value="Can not get value.")

    if len(data) != 3:
        return api_helper.create_error_exception(
            message="Can not found some value.",
            response_code=400,
            value="Can not found some value.")

    project_id = data['project_id']
    project_name = data['project_name']
    project_type = data['project_type']

    data = [project_id, project_type, project_name]

    db = DatabaseHelper()
    result = db.create_project(data)

    return api_helper.return_response(result)
Пример #21
0
def get_admission_year_list():
    db = DatabaseHelper()
    data = db.get_admission_year_list()

    return api_helper.return_response(data)
Пример #22
0
    def read_alumni_personal_data(self, data: pd.DataFrame, personal_header,
                                  graduated_year):

        try:
            data = data.loc[1:, :]
            data.drop_duplicates(subset=personal_header[0],
                                 keep=False,
                                 inplace=True)

            data.rename(columns={
                personal_header[0]: 'alumni_id',
                personal_header[1]: 'gpax',
                personal_header[2]: 'branch_name',
                personal_header[3]: 'company',
                personal_header[4]: 'status',
                personal_header[5]: 'job_description',
                personal_header[6]: 'salary',
                personal_header[7]: 'institution',
                personal_header[9]: 'branch',
                personal_header[10]: 'apprentice',
                personal_header[8]: 'faculty'
            },
                        inplace=True)

            data.astype({'alumni_id': str})

            # alumni table
            alumni = data.loc[:, ['alumni_id', 'gpax']]
            alumni['graduated_year'] = graduated_year
            alumni.loc[alumni['gpax'] == 'ไม่ระบุ', ['gpax']] = -1
            alumni.astype({'gpax': float})

            # alumni graduated table
            db = DatabaseHelper()
            branch = db.get_branch()
            branch = branch['value']
            alumni_graduated = data.loc[:, ['alumni_id', 'branch_name']]

            for i in branch:
                branch_name = i['branch_name']
                if \
                        alumni_graduated.loc[
                            alumni_graduated['branch_name'].str.contains(branch_name.split()[0]), [
                                'branch_name']].shape[
                            0] > 0:
                    alumni_graduated.loc[alumni_graduated['branch_name'].str.
                                         contains(branch_name.split()[0]),
                                         ['branch_name']] = str(i['branch_id'])

            alumni_graduated.rename(columns={'branch_name': 'branch_id'},
                                    inplace=True)

            # alumni apprentice table
            apprentice = db.get_apprentice_status_list()
            apprentice = apprentice['value']

            apprentice_table = data.loc[:, ['alumni_id', 'apprentice']]

            for i in apprentice:
                title = i['status_title']
                title_id = i['status_id']
                if apprentice_table.loc[
                        apprentice_table['apprentice'].str.contains(title),
                    ['apprentice']].shape[0] > 0:
                    apprentice_table.loc[
                        apprentice_table['apprentice'].str.contains(title),
                        ['apprentice']] = str(title_id)

            apprentice_table.rename(columns={'apprentice': 'apprentice_id'},
                                    inplace=True)

            # alumni working table
            working_status = db.get_working_status_list()
            working_status = working_status['value']

            working_table = data.loc[:, [
                'alumni_id', 'status', 'company', 'institution',
                'job_description', 'faculty', 'branch', 'salary'
            ]]

            for i in working_status:
                title = i['status_title']
                title_id = i['status_id']
                if working_table.loc[working_table['status'].str.
                                     contains(title), ['status']].shape[0] > 0:
                    working_table.loc[
                        working_table['status'].str.contains(title),
                        ['status']] = str(title_id)

            working_table.rename(columns={'status': 'status_id'}, inplace=True)

            working_table.loc[working_table['salary'].str.contains("ไม่ระบุ"),
                              ['salary']] = np.nan
            working_table.loc[working_table['salary'] == "",
                              ['salary']] = np.nan
            working_table['salary'] = working_table['salary'].astype(float)

            working_table.loc[working_table['company'] == "",
                              ['company']] = None
            working_table.loc[working_table['institution'] == "",
                              ['institution']] = None
            working_table.loc[working_table['job_description'] == "",
                              ['job_description']] = None
            working_table.loc[working_table['faculty'] == "",
                              ['faculty']] = None
            working_table.loc[working_table['branch'] == "", ['branch']] = None

            out_function_data = {
                'alumni': alumni.to_json(orient='index'),
                'alumni_graduated': alumni_graduated.to_json(orient='index'),
                'working_table': working_table.to_json(orient='index'),
                'apprentice_table': apprentice_table.to_json(orient='index')
            }
            return inner_res_helper.make_inner_response(
                True, "Data for insert to data base", out_function_data)
        except Exception as e:
            print(e)
            return inner_res_helper.make_inner_response(
                False, "Error", "Having problem when prepare data.")
Пример #23
0
def get_project_type(current_user):
    db = DatabaseHelper()
    result = db.get_project_type()

    return api_helper.return_response(result)
Пример #24
0
    def read_admission(self, channel, year, file_location):
        df = pd.read_excel(file_location,
                           converters={
                               'เลขที่ใบสมัคร': str,
                               'รหัสสถานศึกษา': str
                           })

        try:
            df = df.loc[1:, [
                'เลขที่ใบสมัคร', 'คำนำหน้านาม(ไทย)', 'ชื่อ(ไทย)',
                'นามสกุล(ไทย)', 'GPAX', 'รหัสสถานศึกษา', 'สาขาวิชาที่สมัคร',
                'ได้เข้าศึกษา'
            ]]
            df.rename(columns={
                'เลขที่ใบสมัคร': 'application_no',
                'คำนำหน้านาม(ไทย)': 'gender',
                'ชื่อ(ไทย)': 'firstname',
                'นามสกุล(ไทย)': 'lastname',
                'รหัสสถานศึกษา': 'school_id',
                'สาขาวิชาที่สมัคร': 'branch',
                'ได้เข้าศึกษา': 'decision'
            },
                      inplace=True)
        except Exception as e:
            print(e)
            return inner_res_helper.make_inner_response(
                False,
                "Please check your file or table head " + str(e.args[0]),
                "Please check your file or table head " + str(e.args[0]))
        # admission table
        admission_table = df.loc[:, [
            'application_no', 'firstname', 'lastname', 'gender', 'decision'
        ]]
        admission_table['admission_year'] = year
        admission_table['upload_date'] = datetime.now().timestamp()
        admission_table.loc[admission_table['gender'] == 'นาย',
                            ['gender']] = 'M'
        admission_table.loc[admission_table['gender'].str.contains('นาง'),
                            ['gender']] = 'F'
        admission_table.loc[admission_table['decision'] == 'ไม่',
                            ['decision']] = -1
        admission_table.loc[admission_table['decision'] == 'ใช่',
                            ['decision']] = 1
        admission_table['decision'].fillna(-1, inplace=True)

        # admission in branch table
        admission_branch = df.loc[:, ['application_no', 'branch']]

        # get branch data from database
        db = DatabaseHelper()
        branch = db.get_branch()
        branch = branch['value']

        for i in branch:
            branch_name = i['branch_name']
            if admission_branch.loc[admission_branch['branch'].str.
                                    contains(branch_name.split()[0]),
                                    ['branch']].shape[0] > 0:
                admission_branch.loc[admission_branch['branch'].str.
                                     contains(branch_name.split()[0]),
                                     ['branch']] = str(i['branch_id'])

        admission_branch.rename(columns={'branch': 'branch_id'}, inplace=True)

        # admission from table
        admission_from = df.loc[:, ['application_no']]
        admission_from['channel_id'] = channel

        # admission studied
        admission_studied = df.loc[:, ['application_no', 'GPAX', 'school_id']]
        # admission_studied['school_id'] = '1010335002'

        # make json data to send to database helper class
        out_function_data = {
            'admission_table': admission_table.to_json(orient='index'),
            'admission_branch': admission_branch.to_json(orient='index'),
            'admission_from': admission_from.to_json(orient='index'),
            'admission_studied': admission_studied.to_json(orient='index')
        }
        return inner_res_helper.make_inner_response(
            True, "Data for insert in to database", out_function_data)
Пример #25
0
    def analyze_publicize(self, year=None):
        connect = DatabaseHelper()
        data = connect.get_activity_publicize(year)
        if data['value']:
            data = pd.DataFrame(data['value'])
            activity = analyze_helper.set_fullname(connect.get_activity_list())
            if year:
                year_s = int(year)
                activity = activity.loc[(activity['education_year'] == year_s)
                                        |
                                        (activity['education_year'] == year_s -
                                         1)]

            dupli_activity = activity.activity_name.duplicated(keep=False)
            activity.loc[dupli_activity, 'activity_name'] = activity.loc[dupli_activity, 'activity_name'] + ' (' + \
                                                            activity['education_year'].astype(str) + ')'
            count_duplicate = 1
            for i in activity.loc[dupli_activity, 'activity_name'].index:
                activity.loc[i, 'activity_name'] = activity.loc[
                    i, 'activity_name'] + " " + str(count_duplicate)
                count_duplicate = count_duplicate + 1

            activityNoAr = activity[activity['project_type'] == 0]
            activity_data = activityNoAr.drop(columns='project_type')
            activityNoAr = activityNoAr[['activity_name']]

            activity_dict = analyze_helper.set_dict(activityNoAr.index,
                                                    activityNoAr.activity_name)
            data_year = data.copy()

            year_select = []
            if year:
                year = int(year)
                data_year = data[data['activity_year'] == year]
                year_select.append(int(year))
                year_select.append(int(year - 1))
                activity_data = activity_data[activity_data['education_year']
                                              == year]

            else:
                max_year = data.activity_year.max()
                year_select.append(int(max_year))
                year_select.append(int(max_year - 1))

            activity_data.set_index(['activity_name'], inplace=True)

            # data_compare is data all person who joined activity not ar
            data_compare = data[data['activity_year'].isin(year_select)]
            # data_student_compare is data all person who joined activity not ar and studied in KMUTT
            data_student_join = data_compare.dropna()

            compare_year = data_compare.groupby(
                ['activity_id', 'activity_year']).size().unstack(fill_value=0)
            # student_joined = data_student_join.groupby(['activity_id', 'activity_year']).size().unstack(fill_value=0)
            if not compare_year.empty:
                compare_year_data = analyze_helper.check_list(
                    activityNoAr.index, compare_year)
                compare_year_data = analyze_helper.check_list_column(
                    year_select, compare_year_data)
                compare_year_data = analyze_helper.set_fullname_index(
                    activity_dict, compare_year_data)

                # student_joined_compare = analyze_helper.check_list(activityNoAr.index, student_joined)
                # student_joined_compare = analyze_helper.check_list_column(year_select, student_joined_compare)
                # student_joined_compare = analyze_helper.set_fullname_index(activity_dict, student_joined_compare)

            else:
                compare_year_data = pd.DataFrame(columns=year_select)
                activity_name = activityNoAr.activity_name.tolist()
                compare_year_data['activity_name'] = activity_name
                compare_year_data.fillna(0, inplace=True)
                compare_year_data.set_index('activity_name', inplace=True)
                # student_joined_compare = compare_year_data.copy()

            activity_group = data_year.groupby('activity_id').size()
            activity_count_check = analyze_helper.check_list(
                activityNoAr.index, activity_group)
            activity_count = analyze_helper.set_fullname_index(
                activity_dict, activity_count_check)

            student_join = data_student_join.groupby('activity_id').size()
            student_join_check = analyze_helper.check_list(
                activityNoAr.index, student_join)
            student_join_count = analyze_helper.set_fullname_index(
                activity_dict, student_join_check)

            budget = activity.loc[(activity['education_year'] == year)]

            value = {
                'activity_count': activity_count.to_dict(),
                # 'student_join_count': student_join_count.to_dict(),
                'activity_year_compare': compare_year_data.to_dict(),
                # 'student_joined_compare': student_joined_compare.to_dict(),
                'budget': activity_data.to_dict('index')
            }

            response = True
            message = "Analyze Successfully"
        else:
            value = {}
            response = False
            message = "Don't have Data"

        return inner_res_helper.make_inner_response(response=response,
                                                    message=message,
                                                    value=value)
Пример #26
0
    def analyze_project_ar(self, year=None):
        connect = DatabaseHelper()
        data = connect.get_activity_ar(year)
        if data['value']:
            data = pd.DataFrame(data['value'])

            project = analyze_helper.set_fullname(connect.get_project_list())
            project = project[project['project_type'] == 1]
            project.drop(columns=['project_type'], inplace=True)
            project_dict = analyze_helper.set_dict(project.index,
                                                   project.project_name)

            # get_branch=connect.get_department(None)
            # branch=[]
            # for i in get_branch['value']:
            #     for index in range(len(i['branch'])):
            #         branch.append(i['branch'][index])
            # branch_data = analyze_helper.set_branch(branch)
            # branch_data.drop(columns=['amount_student'],inplace=True)
            # branch_dict = analyze_helper.set_dict(branch_data.index, branch_data.branch_name)

            get_branch = connect.get_department_ds()
            get_branch = pd.DataFrame(get_branch['value'])

            branch_data = get_branch[['branch_id', 'branch_name']]
            branch_data = branch_data.set_index('branch_id')
            branch_dict = analyze_helper.set_dict(branch_data.index,
                                                  branch_data.branch_name)

            list_project = project.index.tolist()
            project_set = []
            i = 0
            for pindex in list_project:
                df = data[data['project_id'] == pindex]
                name_project = project_dict[pindex]

                if not df.empty:
                    analyze_by_activity = df.groupby(['branch_name']).size()
                    # analyze_by_activity = analyze_helper.set_fullname_index(branch_dict, analyze_by_activity)

                    analyze_by_activity_gpax = df.groupby(['branch_name'
                                                           ])['gpax'].mean()
                    # analyze_by_activity_gpax = analyze_helper.set_fullname_index(branch_dict, analyze_by_activity_gpax)
                    analyze_by_activity_gpax = analyze_by_activity_gpax.round(
                        2)

                    list_pr = {
                        'project_name':
                        name_project,
                        'analyze_by_activity':
                        analyze_by_activity.to_dict(),
                        'analyze_by_activity_gpax':
                        analyze_by_activity_gpax.to_dict()
                    }

                    project_set.append(list_pr)

                else:

                    list_branch = branch_data.branch_name.tolist()
                    df_empty = pd.DataFrame(list_branch,
                                            columns=['branch_name'])
                    df_empty['value'] = 0
                    df_empty.set_index('branch_name', inplace=True)
                    list_pr = {
                        'project_name': name_project,
                        'analyze_by_activity': df_empty.value.to_dict(),
                        'analyze_by_activity_gpax': df_empty.value.to_dict()
                    }
                    project_set.append(list_pr)
                i = i + 1

            value = {
                'project_set': project_set,
            }

            response = True
            message = "Analyze Successfully"
        else:
            value = {}
            response = False
            message = "Don't have Data"

        return inner_res_helper.make_inner_response(response=response,
                                                    message=message,
                                                    value=value)
Пример #27
0
    def analyze_ar(self, year=None):
        connect = DatabaseHelper()
        data = connect.get_activity_ar(year)

        if data['value']:
            data = pd.DataFrame(data['value'])
            activity = analyze_helper.set_fullname(connect.get_activity_list())
            dupli_activity = activity.activity_name.duplicated(keep=False)
            activity.loc[dupli_activity, 'activity_name'] = activity.loc[dupli_activity, 'activity_name'] + ' (' + \
                                                            activity['education_year'].astype(str) + ')'
            activityAr = activity[activity['project_type'] == 1]
            activity_data = activityAr.drop(columns='project_type')
            activityAr = activityAr[['activity_name']]
            activity_dict = analyze_helper.set_dict(activityAr.index,
                                                    activityAr.activity_name)

            # get_branch=connect.get_department(None)

            # branch=[]
            # for i in get_branch['value']:
            #     for index in range(len(i['branch'])):
            #         branch.append(i['branch'][index])
            # branch_data = analyze_helper.set_branch(branch)
            # branch_data.drop(columns=['amount_student'],inplace=True)
            # branch_dict = analyze_helper.set_dict(branch_data.index, branch_data.branch_name)

            get_branch = connect.get_department_ds()
            get_branch = pd.DataFrame(get_branch['value'])

            branch_data = get_branch[['branch_id', 'branch_name']]
            branch_data = branch_data.set_index('branch_id')
            branch_dict = analyze_helper.set_dict(branch_data.index,
                                                  branch_data.branch_name)

            # activity_data keep data activity such as activity_year and activity_budget
            # activity_dict keep data activity such as activity_year and activity_budget in syntex dic

            count_school = data.school_name.value_counts()
            sort_count_school = count_school.sort_values(
                ascending=False).head()

            gpax_school = data.groupby(['school_name'])['gpax'].mean()
            sort_gpax_school = gpax_school.sort_values(ascending=False).head()
            analyze_by_activity = data.groupby(['project_id', 'branch_name'
                                                ]).size().unstack(fill_value=0)
            # analyze_by_activity = analyze_helper.check_list(activityAr.index, analyze_by_activity)
            # analyze_by_activity = analyze_helper.set_fullname_column(branch_dict, analyze_by_activity)
            # analyze_by_activity = analyze_helper.set_fullname_index(activity_dict, analyze_by_activity)

            analyze_by_activity_gpax = data.groupby(
                ['project_id',
                 'branch_name'])['gpax'].mean().unstack(fill_value=0)
            # analyze_by_activity_gpax = analyze_helper.check_list(activityAr.index, analyze_by_activity_gpax)
            # analyze_by_activity_gpax = analyze_helper.set_fullname_index(activity_dict, analyze_by_activity_gpax)
            # analyze_by_activity_gpax = analyze_helper.set_fullname_column(branch_dict, analyze_by_activity_gpax)
            analyze_by_activity_gpax = analyze_by_activity_gpax.round(2)

            value = {
                'count_school':
                sort_count_school.to_dict(),
                'gpax':
                sort_gpax_school.to_dict(),
                'activity_by_branch_count':
                [analyze_by_activity.to_dict('index')],
                'activity_by_branch_gpax':
                [analyze_by_activity_gpax.to_dict('index')]
            }

            response = True
            message = "Analyze Successfully"
        else:
            value = {}
            response = False
            message = "Don't have Data"

        return inner_res_helper.make_inner_response(response=response,
                                                    message=message,
                                                    value=value)
Пример #28
0
def get_admission_channel():
    db = DatabaseHelper()
    data = db.get_admission_channel()

    return api_helper.return_response(data)
Пример #29
0
def get_admission_list():
    db = DatabaseHelper()
    result = db.get_admission_list()
    return api_helper.return_response(result)
Пример #30
0
def get_round_admission_admin_list():
    db = DatabaseHelper()
    data = db.get_list_round_admission_admin()

    return api_helper.return_response(data)