Esempio n. 1
0
    def test_get_users_as_teacher(self):

        school = add_school(name='Holy Family Catholic School')
        school2 = add_school(name='Trinity College')
        # admin1
        add_user(name='Oliver Mansell',
                 staff_code='MAO',
                 role_code=TEACHER,
                 email='*****@*****.**',
                 password='******',
                 school_id=school.id,
                 admin=True)
        # admin2
        add_user(name='Oliver Mansell',
                 staff_code='MAO',
                 email='*****@*****.**',
                 password='******',
                 school_id=school2.id,
                 admin=True,
                 role_code=TEACHER)

        wb, staff = extract_users("project/api/staffinfo.xlsx")
        wb, staff2 = extract_users("project/api/staffinfo_school2.xlsx")

        for s in staff:
            if s['email'] == "*****@*****.**":
                continue

            new_user = add_user(name=s['name'],
                                email=s['email'],
                                role_code=s['role_code'],
                                staff_code=s['staff_code'],
                                school_id=school.id,
                                password='******')
            db.session.add(new_user)

        for s in staff2:
            if s['email'] == "*****@*****.**":
                continue

            new_user = add_user(name=s['name'],
                                email=s['email'],
                                role_code=s['role_code'],
                                staff_code=s['staff_code'],
                                school_id=school2.id,
                                password='******')
            db.session.add(new_user)
        db.session.commit()

        with self.client:
            resp_login = self.client.post(
                '/auth/login',
                data=json.dumps({
                    'email': '*****@*****.**',
                    'password': '******'
                }),
                content_type='application/json')
            token = json.loads(resp_login.data.decode())['user']['token']

            response = self.client.get(
                '/users',
                content_type='application/json',
                headers={'Authorization': f'Bearer {token}'})

            data = json.loads(response.data.decode())

            self.assertIn("fail", data['status'])
            self.assertIn("You must be admin to do that.", data['message'])
            self.assertEqual(response.status_code, 401)
Esempio n. 2
0
def prepare_staff_accounts(resp, school_id):

    school = School.query.get(school_id)

    if not school:
        response_object = {
            'status': 'fail',
            'message': 'That school does not exist.'
        }
        return jsonify(response_object), 401

    filename = request.get_json()

    if not filename:
        response_object = {'status': 'fail', 'message': 'Invalid payload.'}
        return jsonify(response_object), 401

    wb_staff, staff = extract_users(filename['filename'])

    # will return string error code if doesn't work - check, then return
    if isinstance(staff, str):
        response_object = {'status': 'fail', 'message': staff}
        return jsonify(response_object), 401
    """ PERFORM CHECKS ON EXTRACTED DATA """

    response_object = {'status': 'fail', 'message': 'User import failed'}

    EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")

    for staff_member in staff:
        if not EMAIL_REGEX.match(staff_member['email']):
            response_object['message'] = 'Emails are incorrect.'
            return jsonify(response_object), 401
        if staff_member['name'] is None:
            response_object['message'] = (
                'Names are missing from the uploaded file.')
            return jsonify(response_object), 401
        if (staff_member['staff_code'] is None
                and staff_member['role_code'] is TEACHER):
            response_object['message'] = (
                'Staff codes are missing from the uploaded file.')
            return jsonify(response_object), 401

    # get list of emails already signed up to the school, to ensure imported
    # emails are unique without raising db Exception

    emails = [
        user.email for user in User.query.filter_by(school_id=school_id).all()
    ]

    skipped_emails = []
    for s in staff:
        # skip any emails already in database
        if s['email'] in emails:
            skipped_emails.append(s['email'])
            continue

        new_user = add_user(name=s['name'],
                            email=s['email'],
                            password='******',
                            role_code=s['role_code'],
                            staff_code=s['staff_code'],
                            school_id=school.id)

        try:
            db.session.add(new_user)
            db.session.commit()
        except Exception as e:
            return jsonify({'status': 'fail', 'message': str(e)}), 401

    # if emails needed to be skipped (admin should be one) send list in
    # warning message of response dict
    if len(skipped_emails) > 0:
        response_object['warning'] = {'skipped_users': skipped_emails}

    response_object['status'] = 'success'
    response_object['data'] = \
        {'staff': [user.asdict() for user in User.query.filter_by(
            school_id=school.id).all()]}
    response_object['message'] = 'Please ensure these users are correct.'

    return jsonify(response_object), 200
Esempio n. 3
0
def populate_school_db(school_id,
                       reqs_number=150,
                       lessons_file='project/api/SciTT2017.xlsx',
                       staff_file="project/api/staffinfo.xlsx"):

    school = School.query.get(school_id)

    site1 = Site()
    site1.name = 'Wiseman Upstairs'
    site1.school_id = school.id
    db.session.add(site1)

    site3 = Site()
    site3.name = 'Wiseman Downstairs'
    site3.school_id = school.id
    db.session.add(site3)

    site2 = Site()
    site2.name = 'Walthamstow'
    site2.school_id = school.id
    db.session.add(site2)
    db.session.commit()

    if not school:
        return False

    lessons = extract_lessons(lessons_file)
    wb, staff = extract_users(staff_file)

    taken_emails = [
        u.email for u in User.query.filter_by(school_id=school_id).all()
    ]

    for s in staff:
        if s['email'] in taken_emails:
            continue

        add_user(name=s['name'],
                 email=s['email'],
                 password='******',
                 role_code=s['role_code'],
                 staff_code=s['staff_code'],
                 school_id=school.id)

    q = User.query.filter_by(
        email="*****@*****.**").first()
    q.role_code = TEACHER
    db.session.commit()

    school.preferences = {
        "dates_processed":
        False,
        "days_notice":
        7,
        "term_dates": [
            HalfTerm("20170904", "20171020"),
            HalfTerm("20171030", "20171220"),
            HalfTerm("20180103", "20180209"),
            HalfTerm("20180219", "20180329"),
            HalfTerm("20180416", "20180525"),
            HalfTerm("20180604", "20180720")
        ],
        "period_start_times": {
            '1': '0900',
            '2': '1000',
            '3': '1120',
            '4': '1220',
            '5': '1410',
            '6': '1510'
        },
        "period_length_in_minutes":
        60,
        "weeks_timetable":
        2,
        "sites":
        True,
        "reminder_emails":
        False,
        "reminder_day":
        3,  # ISO WEEKDAY
    }
    try:
        process_preferences(school.preferences)
    except ValueError:
        raise ValueError("Could not process preferences")

    for lesson in lessons:

        # rudimentary error checking that what should be numbers are numbers
        try:
            int(lesson['day'])
            int(lesson['period'])
            int(lesson['week'])
        except ValueError:
            continue

        teacher = User.query.filter_by(school_id=school_id).\
            filter_by(staff_code=lesson['staff_code']).first()

        if not teacher:
            return False

        room = Room.query.filter_by(school_id=school_id).\
            filter_by(name=lesson['room']).first()
        classgroup = Classgroup.query.filter_by(school_id=school_id).\
            filter_by(name=lesson['class']).first()

        if not room:

            room = Room(name=lesson['room'], school_id=school_id)

            if lesson['room'][0] is 'L':
                room.site = Site.query.filter_by(name='Walthamstow').first()
            elif int(lesson['room'][1] + lesson['room'][2]) < 18:

                room.site = Site.query.filter_by(
                    name='Wiseman Downstairs').first()
            else:

                room.site = Site.query.filter_by(
                    name='Wiseman Upstairs').first()

            room.site_id = random.randrange(1, 4)

            db.session.add(room)
            db.session.flush()
        if not classgroup:
            classgroup = Classgroup(name=lesson['class'], school_id=school_id)
            db.session.add(classgroup)
            db.session.flush()

        start_time = datetime.strptime(
            school.preferences['period_start_times'][str(lesson['period'])],
            TIME_FORMAT)

        end_time = start_time + timedelta(
            minutes=int(school.preferences['period_length_in_minutes']))

        lesson = Lesson(room=room,
                        classgroup=classgroup,
                        school=school,
                        period=lesson['period'],
                        week_number=lesson['week'],
                        teacher=teacher,
                        start_time=start_time,
                        end_time=end_time,
                        day_code=int(lesson['day']))

        db.session.add(lesson)
        db.session.flush()
    """should now have all teachers, lessons, and rooms in DB """
    db.session.commit()