示例#1
0
def test_draw_all(client):
    """attempt to draw all lotteries
        1. make some applications to some lotteries
        2. draws all the lotteries in one time index
        3. test: status code
        4. test: DB is properly changed
        target_url: /draw_all [POST]
    """
    time_index = 1

    with client.application.app_context():
        target_lotteries = Lottery.query.filter_by(index=time_index)
        non_target_lotteries = Lottery.query.filter_by(index=time_index + 1)
        users = (user for user in User.query.all()
                 if user.authority != "admin")
        for i, user in enumerate(users):
            target_lottery = target_lotteries[i % len(list(target_lotteries))]
            non_target_lottery = non_target_lotteries[i % len(
                list(non_target_lotteries))]
            application1 = Application(lottery=target_lottery, user_id=user.id)
            application2 = Application(lottery=non_target_lottery,
                                       user_id=user.id)
            db.session.add(application1)
            db.session.add(application2)
        db.session.commit()

    token = login(client, admin['secret_id'],
                  admin['g-recaptcha-response'])['token']
    _, en = client.application.config['TIMEPOINTS'][time_index]
    en_margin = client.application.config['TIMEPOINT_END_MARGIN']
    draw_time = mod_time(en, en_margin)
    with mock.patch('api.time_management.get_current_datetime',
                    return_value=draw_time):
        resp = client.post('/draw_all',
                           headers={'Authorization': f'Bearer {token}'})

    assert resp.status_code == 200

    winners_id = [winner['id'] for winner in resp.get_json()]
    assert all(lottery.done for lottery in target_lotteries)
    assert all(not lottery.done for lottery in non_target_lotteries)

    with client.application.app_context():
        users = User.query.all()
        for user in users:
            for lottery in target_lotteries:
                application = Application.query.filter_by(
                    lottery=lottery, user_id=user.id).first()
                if application:
                    status = 'won' if user.id in winners_id else 'lose'
                    assert application.status == status

            for lottery in non_target_lotteries:
                application = Application.query.filter_by(
                    lottery=lottery, user_id=user.id).first()
                if application:
                    assert application.status == "pending"
示例#2
0
def test_draw_all(client):
    """attempt to draw all lotteries
        1. make some applications to some lotteries
        2. draws all the lotteries in one time index
        3. test: status code
        4. test: DB is properly changed
        target_url: /draw_all [POST]
    """
    time_index = 1

    with client.application.app_context():
        target_lotteries = Lottery.query.filter_by(index=time_index)
        non_target_lotteries = Lottery.query.filter_by(index=time_index+1)
        users = (user for user in User.query.all()
                 if user.authority != "admin")
        for i, user in enumerate(users):
            target_lottery = target_lotteries[i % len(list(target_lotteries))]
            non_target_lottery = non_target_lotteries[i % len(
                list(non_target_lotteries))]
            application1 = Application(lottery=target_lottery, user_id=user.id)
            application2 = Application(
                lottery=non_target_lottery, user_id=user.id)
            db.session.add(application1)
            db.session.add(application2)
        db.session.commit()

    token = login(client,
                  admin['secret_id'],
                  admin['g-recaptcha-response'])['token']
    _, en = client.application.config['TIMEPOINTS'][time_index]
    en_margin = client.application.config['TIMEPOINT_END_MARGIN']
    draw_time = mod_time(en, en_margin)

    resp = draw_all(client, token, time=draw_time)

    assert resp.status_code == 200

    winners_id = [winner['id'] for winner in resp.get_json()]

    with client.application.app_context():
        users = User.query.all()
        for user in users:
            for lottery in target_lotteries:
                application = Application.query.filter_by(
                    lottery=lottery, user_id=user.id).first()
                if application:
                    if user.id in winners_id:
                        assert application.status == "won"
                    else:
                        assert application.status in {"lose", "waiting"}

            for lottery in non_target_lotteries:
                application = Application.query.filter_by(
                    lottery=lottery, user_id=user.id).first()
                if application:
                    assert application.status == "pending"
示例#3
0
def test_draw_lots_of_groups_and_normal(client, cnt):
    """attempt to draw a lottery as 2 groups of 2 members and 2 normal
            while WINNERS_NUM is 3
        1. make some applications to one lottery as groups
        2. draws the lottery
        3. test: status code
        4. test: DB is changed
        5. test: result of each member
        6. test: number of winners is less than 3
        target_url: /lotteries/<id>/draw [POST]
    """
    idx = 1
    members = (0, 1)
    reps = (2, 3)
    normal = (4, 5)

    with client.application.app_context():
        target_lottery = Lottery.query.filter_by(id=idx).first()
        index = target_lottery.index
        users = User.query.all()
        members_app = [
            Application(lottery=target_lottery, user_id=users[i].id)
            for i in chain(members, normal)
        ]
        reps_app = (Application(lottery=target_lottery,
                                user_id=users[reps[i]].id,
                                is_rep=True,
                                group_members=[group_member(members_app[i])])
                    for i in range(2))

        for application in chain(members_app, reps_app):
            db.session.add(application)
        db.session.commit()

        token = login(client, admin['secret_id'],
                      admin['g-recaptcha-response'])['token']

        with mock.patch('api.routes.api.get_draw_time_index',
                        return_value=index):
            resp = client.post(f'/lotteries/{idx}/draw',
                               headers={'Authorization': f'Bearer {token}'})

        assert resp.status_code == 200

        winners = resp.get_json()
        assert len(winners) == client.application.config['WINNERS_NUM']

        users = User.query.all()
        target_lottery = Lottery.query.filter_by(id=idx).first()
        assert target_lottery.done
        for i, j in zip(reps, members):
            rep_status = Application.query.filter_by(
                lottery=target_lottery, user_id=users[i].id).first().status
            member_status = Application.query.filter_by(
                lottery=target_lottery, user_id=users[j].id).first().status
            assert rep_status == member_status
示例#4
0
def test_group_losers_advantage(client):
    """
        user with the lose_count of 3 and others with that of 0 attempt to
        apply a lottery
        test loser is more likely to win
        target_url: /lotteries/<id>/draw
    """
    idx = 1
    groups = [(0, (1, ))]
    win_count = {i: 0 for i in range(1, 7)}

    for i in range(6):
        print(i, win_count)  # display when test failed
        with client.application.app_context():
            target_lottery = Lottery.query.get(idx)
            index = target_lottery.index

            users = User.query.order_by(User.id).all()[:6]
            users[0].lose_count = 6
            user0_id = users[0].id

            normal_apps = (Application(lottery=target_lottery,
                                       user_id=users[i].id)
                           for i in range(len(users)) for rep, _ in groups
                           if i != rep)  # not rep
            rep_apps = (Application(
                lottery=target_lottery,
                user_id=users[rep].id,
                is_rep=True,
                group_members=[group_member(app) for app in normal_apps])
                        for rep, members in groups)

            for app in chain(rep_apps, normal_apps):
                db.session.add(app)
            db.session.commit()

            token = login(client, admin['secret_id'],
                          admin['g-recaptcha-response'])['token']

            with mock.patch('api.routes.api.get_draw_time_index',
                            return_value=index):
                resp = client.post(
                    f'/lotteries/{idx}/draw',
                    headers={'Authorization': f'Bearer {token}'})

                for winner_json in resp.get_json():
                    winner_id = winner_json['id']
                    win_count[winner_id] += 1

        # re-configure and reset test environment
        client = next(conftest.client())

    won_most = max(win_count.items(), key=itemgetter(1))[0]
    print(win_count)
    assert won_most == user0_id
示例#5
0
def test_draw_group(client):
    """attempt to draw a lottery as a group
        1. make some applications to one lottery as a group
        2. draws the lottery
        3. test: status code
        4. test: DB is changed
        5. test: result of each member
        target_url: /lotteries/<id>/draw [POST]
    """
    idx = 1
    group_size = 3

    with client.application.app_context():
        target_lottery = Lottery.query.get(idx)
        index = target_lottery.index
        users = User.query.all()
        members_app = [
            Application(lottery=target_lottery, user_id=user.id)
            for user in users[1:]
        ]
        for application in members_app:
            db.session.add(application)
        rep_application = Application(
            lottery=target_lottery,
            user_id=users[0].id,
            is_rep=True,
            group_members=[group_member(app) for app in members_app])

        db.session.add(rep_application)
        db.session.commit()

        token = login(client, admin['secret_id'],
                      admin['g-recaptcha-response'])['token']

        with mock.patch('api.routes.api.get_draw_time_index',
                        return_value=index):
            resp = client.post(f'/lotteries/{idx}/draw',
                               headers={'Authorization': f'Bearer {token}'})

        assert resp.status_code == 200

        users = User.query.all()
        target_lottery = Lottery.query.filter_by(id=idx).first()
        assert target_lottery.done
        rep_status = Application.query.filter_by(
            lottery=target_lottery, user_id=users[0].id).first().status
        for user in users[1:group_size]:
            application = Application.query.filter_by(lottery=target_lottery,
                                                      user_id=user.id).first()
            assert application.status == rep_status
示例#6
0
def user2application(user, target_lottery, **kwargs):
    if isinstance(target_lottery, int):
        # when target_lottery is id
        if isinstance(user, int):
            # when user is id
            return Application(lottery_id=target_lottery,
                               user_id=user,
                               **kwargs)
        else:
            return Application(lottery_id=target_lottery, user=user, **kwargs)
    else:
        if isinstance(user, int):
            return Application(lottery=target_lottery, user_id=user, **kwargs)
        else:
            return Application(lottery=target_lottery, user=user, **kwargs)
示例#7
0
def test_apply_group_same_lottery(client):
    """attempt to make application to the same lottery as member of group
        target_url: /lotteries/<id> [POST]

        1. make an application as member
        2. attempt to apply
    """
    idx = 1
    user = test_user
    members = [
        test_user1['secret_id'], test_user2['secret_id'],
        test_user3['secret_id']
    ]
    token = login(client, user['secret_id'],
                  user['g-recaptcha-response'])['token']

    with client.application.app_context():
        index = Lottery.query.get(idx).index
        lottery = Lottery.query.get(idx)
        violation_user = User.query.filter_by(secret_id=members[0]).first()
        application = Application(lottery=lottery, user_id=violation_user.id)
        db.session.add(application)
        db.session.commit()

    with mock.patch('api.routes.api.get_time_index', return_value=index):
        resp = client.post(f'/lotteries/{idx}',
                           headers={'Authorization': f'Bearer {token}'},
                           json={'group_members': members})

        assert resp.status_code == 400
        assert 'Someone in the group is already applying to this lottery' in \
            resp.get_json()['message']
示例#8
0
def test_apply_same_period_same_lottery(client):
    """attempt to apply to the same lottery in the same period
        1. test: error is returned
        target_url: /lotteries/<id> [POST]
    """
    idx = 1
    token = login(client, test_user['secret_id'],
                  test_user['g-recaptcha-response'])['token']

    with client.application.app_context():
        target_lottery = Lottery.query.filter_by(id=idx).first()
        index = target_lottery.index
        user = User.query.filter_by(secret_id=test_user['secret_id']).first()
        application = Application(lottery=target_lottery, user_id=user.id)
        db.session.add(application)
        db.session.commit()

    with mock.patch('api.routes.api.get_time_index', return_value=index):
        resp = client.post(f'/lotteries/{idx}',
                           headers={'Authorization': f'Bearer {token}'},
                           json={'group_members': []})

    message = resp.get_json()['message']

    assert resp.status_code == 400
    assert 'already accepted' in message
示例#9
0
def test_get_winners(client):
    """test proper public_id's are returned from the API
        target_url: /lotteries/<id>/winners
    """
    idx = 1

    with client.application.app_context():
        target_lottery = Lottery.query.get(idx)
        index = target_lottery.index
        users = User.query.all()
        for user in users:
            application = Application(lottery=target_lottery, user_id=user.id)
            db.session.add(application)
        db.session.commit()

        token = login(client, admin['secret_id'],
                      admin['g-recaptcha-response'])['token']

        with mock.patch('api.routes.api.get_draw_time_index',
                        return_value=index):
            draw_resp = client.post(
                f'/lotteries/{idx}/draw',
                headers={'Authorization': f'Bearer {token}'})
            winners_resp = client.get(
                f'/lotteries/{idx}/winners',
                headers={'Authorization': f'Bearer {token}'})

        winners_id = set(
            User.query.get(winner['id']).public_id
            for winner in draw_resp.get_json())
        assert winners_id == set(winners_resp.get_json())
示例#10
0
def test_checker(client, def_status):
    """use `/checker` endpoint with winner user
        target_url: /checker/{classroom_id}/{secret_id}
    """
    classroom_id = 1
    index = 1
    target_user = test_user
    staff = checker
    secret_id = target_user['secret_id']

    with client.application.app_context():
        lottery_id = Lottery.query.filter_by(classroom_id=classroom_id,
                                             index=index).first().id
        user = User.query.filter_by(secret_id=secret_id).first()
        application = Application(user_id=user.id,
                                  lottery_id=lottery_id, status=def_status)
        db.session.add(application)
        db.session.commit()

    with mock.patch('api.routes.api.get_prev_time_index',
                    return_value=index):
        resp = as_user_get(client, staff['secret_id'],
                           staff['g-recaptcha-response'],
                           f'/checker/{classroom_id}/{secret_id}')

    assert resp.status_code == 200
    assert resp.get_json()['status'] == def_status
示例#11
0
    def post(self, request: Request):
        uid = request.user.id
        if not uid:
            return HttpResponseForbidden("Missing user ID")

        body = request.data
        if not body:
            return HttpResponseBadRequest("Missing request body")

        (steps_key_id, steps_enc) = self.encrypt_steps(body["steps"])

        db_app = Application(
            last_updated=body.get("lastUpdate"),
            last_printed=body.get("lastPrinted"),
            app_type=body.get("type"),
            current_step=body.get("currentStep"),
            all_completed=body.get("allCompleted"),
            steps=steps_enc,
            user_type=body.get("userType"),
            applicant_name=body.get("applicantName"),
            user_name=body.get("userName"),
            key_id=steps_key_id,
            respondent_name=body.get("respondentName"),
            protected_party_name=body.get("protectedPartyName"),
            protected_child_name=body.get("protectedChildName"),
            application_location=body.get("applicationLocation"),
            user_id=uid)

        db_app.save()
        return Response({"app_id": db_app.pk})
示例#12
0
def test_application_is_member(client):
    with client.application.app_context():
        target_lot = Lottery.query.first()

        users = User.query.all()
        member = users[0]

        member_app = Application(lottery=target_lot, user=member)
        rep = users[1]
        rep_app = Application(lottery=target_lot, user=rep, is_rep=True,
                              group_members=[app2member(member_app)])

        db.session.add(member_app)
        db.session.add(rep_app)
        db.session.commit()

        dumpdata = application_schema.dump(member_app)[0]
        assert dumpdata['is_member']
示例#13
0
def test_application_not_member(client):
    with client.application.app_context():
        target_lot = Lottery.query.first()

        member = User.query.first()

        member_app = Application(lottery=target_lot, user=member)

        db.session.add(member_app)
        db.session.commit()

        dumpdata = application_schema.dump(member_app)[0]
        assert not dumpdata['is_member']
示例#14
0
文件: utils.py 项目: Cj-bc/backend
def make_application(client, secret_id, lottery_id):
    """make an application with specified user and lottery id
         client (class Flask.testing.FlaskClient): the client
         secret_id (str): the secret_id to apply
         lottery_id (int): the lottery id to create application from.
         Return (int): The created application's id
   """
    with client.application.app_context():
        user = User.query.filter_by(secret_id=secret_id).first()
        newapplication = Application(lottery_id=lottery_id,
                                     user_id=user.id,
                                     status="pending")
        db.session.add(newapplication)
        db.session.commit()
        return newapplication.id
示例#15
0
def test_losers_advantage(client):
    """
        user with the lose_count of 3 and others with that of 0 attempt to
        apply a lottery
        test loser is more likely to win
        target_url: /lotteries/<id>/draw
    """
    idx = 1
    win_count = {i: 0 for i in range(1, 7)}

    for i in range(6):
        with client.application.app_context():
            target_lottery = Lottery.query.get(idx)
            index = target_lottery.index

            users = User.query.order_by(User.id).all()[:6]
            users[0].lose_count = 6
            user0_id = users[0].id

            apps = (Application(lottery=target_lottery, user_id=user.id)
                    for user in users)

            for app in apps:
                db.session.add(app)
            db.session.commit()

            token = login(client, admin['secret_id'],
                          admin['g-recaptcha-response'])['token']

            with mock.patch('api.routes.api.get_draw_time_index',
                            return_value=index):
                resp = client.post(
                    f'/lotteries/{idx}/draw',
                    headers={'Authorization': f'Bearer {token}'})

                for winner_json in resp.get_json():
                    winner_id = winner_json['id']
                    win_count[winner_id] += 1

        # re-configure and reset test environment
        client = next(conftest.client())

    won_most = max(win_count.items(), key=itemgetter(1))[0]
    print('final results of applications (1 is rep)')
    print(win_count)
    assert won_most == user0_id
示例#16
0
def make_application(client, secret_id, lottery_id, group_member_apps=[]):
    """make an application with specified user and lottery id
         client (class Flask.testing.FlaskClient): the client
         secret_id (str): the secret_id to apply
         lottery_id (int): the lottery id to create application from.
         Return (int): The created application's id
   """
    with client.application.app_context():
        user = User.query.filter_by(secret_id=secret_id).first()
        group_member_apps = (Application.query.get(app_id)
                             for app_id in group_member_apps)
        new_application = Application(
            lottery_id=lottery_id,
            user_id=user.id,
            group_members=apps2members(group_member_apps))
        db.session.add(new_application)
        db.session.commit()
        return new_application.id
示例#17
0
def test_draw(client):
    """attempt to draw a lottery
        1. make some applications to one lottery
        2. draws the lottery
        3. test: status code
        4. test: DB is changed
        target_url: /lotteries/<id>/draw [POST]
    """
    idx = 1

    with client.application.app_context():
        target_lottery = Lottery.query.get(idx)
        index = target_lottery.index
        users = User.query.all()
        for user in users:
            application = Application(lottery=target_lottery, user_id=user.id)
            db.session.add(application)
        db.session.commit()

        token = login(client, admin['secret_id'],
                      admin['g-recaptcha-response'])['token']

        _, end = client.application.config['TIMEPOINTS'][index]
        end_margin = client.application.config['TIMEPOINT_END_MARGIN']
        end_with_margin = mod_time(end, end_margin)
        with mock.patch('api.time_management.get_current_datetime',
                        return_value=end_with_margin):
            resp = client.post(f'/lotteries/{idx}/draw',
                               headers={'Authorization': f'Bearer {token}'})

        assert resp.status_code == 200

        winners_id = [winner['id'] for winner in resp.get_json()]
        users = User.query.all()
        target_lottery = Lottery.query.filter_by(id=idx).first()
        assert target_lottery.done
        for user in users:
            application = Application.query.filter_by(lottery=target_lottery,
                                                      user_id=user.id).first()
            if application:
                status = 'won' if user.id in winners_id else 'lose'
            assert application.status == status
示例#18
0
def test_draw_all_multiple(client):
    """hit /draw_all twice in one time index
        test: the result does not change
        target_url: /draw_all [POST]
    """
    idx = 1

    with client.application.app_context():
        target_lottery = Lottery.query.get(idx)
        index = target_lottery.index
        users = (user for user in User.query.all()
                 if user.authority == 'normal')
        for user in users:
            app = Application(lottery=target_lottery, user_id=user.id)
            db.session.add(app)
        db.session.commit()

        token = login(client,
                      admin['secret_id'],
                      admin['g-recaptcha-response'])['token']

        resp1 = draw_all(client, token, index=index)
        assert resp1.status_code == 200
        win1 = {
            app.id for app in Application.query.filter_by(status='won')}
        lose1 = {
            app.id for app in Application.query.filter_by(status='lose')}
        waiting1 = {
            app.id for app in Application.query.filter_by(status='waiting')}

        resp2 = draw_all(client, token, index=index)
        assert resp2.status_code == 200
        win2 = {
            app.id for app in Application.query.filter_by(status='won')}
        lose2 = {
            app.id for app in Application.query.filter_by(status='lose')}
        waiting2 = {
            app.id for app in Application.query.filter_by(status='waiting')}

        assert win1 == win2
        assert lose1 == lose2
        assert waiting1 == waiting2
示例#19
0
def apply_lottery(idx):
    """
        apply to the lottery.
        specify the lottery id in the URL.
        1. check request errors
        2. check whether all group_member's secret_id are correct
        3. check wehter nobody in members made application to the same period
        4. get all `user_id` of members
        5. make application of token's owner
        6. if length of 'group_members' list is 0, goto *8.*
        7. set 'is_rep' to True,
           add 'user_id's got in *3.* to 'group_members' list
        8. make members application based on 'user_id' got in *3.*
        9. return application_id as result
        Variables:
            group_members_secret_id (list of str): list of members' secret_id
            lottery: (Lottery): specified Lottery object
            rep_user (User): token's owner's user object
            group_members (list of User): list of group members' User object
    """
    # 1.
    group_members_secret_id = request.get_json()['group_members']
    lottery = Lottery.query.get(idx)
    if lottery is None:
        return error_response(7)  # Not found
    try:
        current_index = get_time_index()
    except (OutOfHoursError, OutOfAcceptingHoursError):
        # We're not accepting any application in this hours.
        return error_response(14)
    if lottery.index != current_index:
        return error_response(11)  # This lottery is not acceptable now.

    # 2. 3. 4.
    group_members = []
    if len(group_members_secret_id) != 0:
        if len(group_members_secret_id) > 3:
            return error_response(21)
        for sec_id in group_members_secret_id:
            try:
                user = todays_user(secret_id=sec_id)
            except (UserNotFoundError, UserDisabledError):
                return error_response(1)  # Invalid group member secret id
            group_members.append(user)
        for user in group_members:
            previous = Application.query.filter_by(user_id=user.id)
            if any(app.lottery.index == lottery.index and
                   app.lottery.id != lottery.id
                   for app in previous.all()):
                # Someone in the group is
                # already applying to a lottery in this period
                return error_response(8)
            if any(app.lottery.index == lottery.index and
                   app.lottery.id == lottery.id
                   for app in previous.all()):

                # someone in the group is already
                # applying to this lottery
                return error_response(9)

    # 5.
    rep_user = User.query.filter_by(id=g.token_data['user_id']).first()
    previous = Application.query.filter_by(user_id=rep_user.id)
    if any(app.lottery.index == lottery.index and
            app.lottery.id != lottery.id
            for app in previous.all()):
        # You're already applying to a lottery in this period
        return error_response(17)
    if any(app.lottery.index == lottery.index and
            app.lottery.id == lottery.id
            for app in previous.all()):
        # Your application is already accepted
        return error_response(16)
    application = previous.filter_by(lottery_id=lottery.id).first()
    # access DB
    # 6. 7.
    if application:
        result = application_schema.dump(application)[0]
        return jsonify(result)
    else:
        if len(group_members) == 0:
            newapplication = Application(
                lottery_id=lottery.id, user_id=rep_user.id, status="pending")
            db.session.add(newapplication)
            db.session.commit()
            result = application_schema.dump(newapplication)[0]
            return jsonify(result)
        else:
            # 8.
            members_app = [Application(
                    lottery_id=lottery.id, user_id=member.id, status="pending")
                    for member in group_members]

            for application in members_app:
                db.session.add(application)
            db.session.commit()
            rep_application = Application(
                lottery_id=lottery.id, user_id=rep_user.id, status="pending",
                is_rep=True,
                group_members=[group_member(app)
                               for app in members_app])
            db.session.add(rep_application)

    # 9.
    db.session.commit()
    result = application_schema.dump(rep_application)[0]
    return jsonify(result)
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SignMeUpAPIGraphQL.settings')
import django

django.setup()

from api.models import Student, FieldOfStudy, Subject, Application, SubjectGroup

if __name__ == '__main__':
    Application.objects.all().delete()
    SubjectGroup.objects.all().delete()
    field_of_study = FieldOfStudy.objects.all()[0]
    students = Student.objects.filter(field_of_study=field_of_study)[0:2]
    subjects = Subject.objects.filter(
        subject_type__field_of_study=field_of_study)[0:2]
    SubjectGroup(student=students[0], subject=subjects[0]).save()
    SubjectGroup(student=students[1], subject=subjects[1]).save()
    Application(unwanted_subject=subjects[0],
                wanted_subject=subjects[1],
                student=students[0]).save()
    print(students[1])
    print(subjects[0].id, subjects[1].id)
示例#21
0
    def obj_create(self, bundle, request=None, **kwargs):
        registrationForm = bundle.data['registrationForm']

        tenantDetails = registrationForm['personalDetails']
        ownerDetails = registrationForm['otherParty']
        leaseApplicationDetails = registrationForm['leaseApplicationDetails']
        depositDetails = registrationForm['depositDetails']

        tenant_first_name = tenantDetails['firstName']
        tenant_last_name = tenantDetails['lastName']
        owner_first_name = ownerDetails['firstName']
        owner_last_name = ownerDetails['lastName']

        try:  ##try to find if registrant user exist
            tenant = User.objects.get(email=tenantDetails['email'])
            generated_tenant_id = tenant.account_id
        except User.DoesNotExist:  ##if doesn't exist create a new object

            ##excuse my shit way of doing this, randomly generating user_id
            random_uid = str(uuid.uuid4().hex)
            generated_tenant_id = random_uid
            #generated_tenant_id = str(tenant_first_name)[0] + str(tenant_last_name)[0] + random_uid[0] + random_uid[1] + random_uid[2] + random_uid[3]
            generated_tenant_password = random_uid[4] + random_uid[
                5] + random_uid[6] + random_uid[7] + str(
                    tenant_first_name)[0] + str(tenant_last_name)[0]
            name = generate_random_username()
            print('tenant username: '******'tenant password: '******'phoneNumber'],
                          email=tenantDetails['email'],
                          username=name)
            tenant.set_password(generated_tenant_password)
            tenant.save()

            send_account_creation_email(tenant, generated_tenant_password)

            ##Log the event
            registrationEvent = Event(
                referenceid=generated_tenant_id,
                what="TENANT REGISTRATION",
                who=generated_tenant_id,
                #when=bundle.data['createdAt']
            )
            registrationEvent.save()

        try:  ##try to find if owner user exist
            owner = User.objects.get(email=ownerDetails['email'])

            generated_owner_id = owner.account_id
        except User.DoesNotExist:  ##if doesn't exist create a new object

            random_uid = str(uuid.uuid4().hex)
            generated_owner_id = random_uid
            #generated_owner_id = str(owner_first_name)[0] + str(owner_last_name)[0] + random_uid[0] + random_uid[1] + random_uid[2] + random_uid[3]
            generated_owner_password = random_uid[4] + random_uid[
                5] + random_uid[6] + random_uid[7] + str(
                    owner_first_name)[0] + str(owner_last_name)[0]
            name = generate_random_username()
            print('owner username: '******'owner password: '******'firstName'],
                         last_name=ownerDetails['lastName'],
                         contact_number=ownerDetails['phoneNumber'],
                         email=ownerDetails['email'],
                         username=name)
            owner.set_password(generated_owner_password)
            owner.save()
            send_account_creation_email(owner, generated_owner_password)

            ##Log the event
            registrationEvent = Event(
                referenceid=generated_owner_id,
                what="OWNER REGISTRATION",
                who=generated_owner_id,
            )
            registrationEvent.save()

        try:  ##try to find if application allready exist
            owner = Application.objects.get(
                ejari_no=leaseApplicationDetails['contractNo'])
        except Application.DoesNotExist:  ##if doesn't exist create a new object
            random_uid = str(uuid.uuid4().hex)
            #generated_application_id = str(owner_first_name)[0] + str(tenant_first_name)[0] + \
            #                           random_uid[0] + random_uid[1] + random_uid[2] + random_uid[3]
            generated_application_id = random_uid
            new_application = Application(
                ejari_no=leaseApplicationDetails['contractNo'],
                premis_no=leaseApplicationDetails['premiseNo'],
                total_contract_value=leaseApplicationDetails[
                    'securityDepositAmount'],
                address=leaseApplicationDetails['address'],
                start_date=leaseApplicationDetails['contractStartDate'],
                end_date=leaseApplicationDetails['contractEndDate'],
                annual_rent=leaseApplicationDetails['annualRent'],
                property_size=leaseApplicationDetails['propertySize'],
                property_usage=leaseApplicationDetails['propertyUsage'],
                currency_type=leaseApplicationDetails['currencyType'],
                deposit_term=depositDetails['term'],
                deposit_amount=depositDetails['amount'],
                term_percent=depositDetails['termPercent'],
                internal_id=generated_application_id,
                tenant_id=generated_tenant_id,
                owner_id=generated_owner_id)
            new_application.save()

            ##Log the event
            registrationEvent = Event(
                referenceid=generated_application_id,
                what="APPLICATION REGISTRATION",
                who=generated_tenant_id,
            )
            registrationEvent.save()
            send_application_confirm_email(tenant, owner, new_application)