Exemplo n.º 1
0
    def setUp(self):
        super().setUp()

        # Initial api auth application:
        self.initial_application_number = 1
        # Create neccessary data
        self.applications_data = [
            {
                'name': "Batman application",
                'description': "Bruce Wayne awesome application",
                'active': True,
            },
            {
                'name': "Spiderman application",
                'description': "Peter parker awesome application",
                'active': False,
            },
        ]

        self.applications = []
        for i in self.applications_data:
            a = Application(name=i['name'],
                            description=i['description'],
                            active=i['active'])
            a.save()
            self.applications.append(a)
Exemplo n.º 2
0
 def setUp(self):
     super(ApplicationResourceTest, self).setUp()
     self.api_list_url = '/api/v1/applications/'
     self.container_list_url = '/api/v1/containers/'
     self.username = '******'
     self.password = '******'
     self.user = User.objects.create_user(self.username,
         '*****@*****.**', self.password)
     self.api_key = self.user.api_key.key
     self.data = {
         'name': 'test-app',
         'description': 'test app',
         'domain_name': 'test.example.com',
         'backend_port': 1234,
         'protocol': 'http'
     }
     host = Host()
     host.name = 'local'
     host.hostname = '127.0.0.1'
     host.save()
     self.host = host
     self.container_data = {
         'image': 'base',
         'command': '/bin/bash',
         'description': 'test app',
         'ports': [],
         'hosts': ['/api/v1/hosts/1/']
     }
     resp = self.api_client.post(self.container_list_url, format='json',
         data=self.container_data, authentication=self.get_credentials())
     self.app = Application(**self.data)
     self.app.save()
Exemplo n.º 3
0
    def test_application_permissions_relation(self):
        applications_data = [
            {
                'name': "Batman application",
                'description': "Bruce Wayne awesome application",
                'active': True,
            },
            {
                'name': "Spiderman application",
                'description': "Peter parker awesome application",
                'active': False,
            },
        ]

        applications = []
        for i in applications_data:
            a = Application(name=i['name'],
                            description=i['description'],
                            active=i['active'])
            a.save()
            applications.append(a)

        for i in self.permissions_data:
            p = ProjectPermission.objects.get(key=i['key'])
            url = reverse('api:projectpermission-detail', args=[p.id])
            # Set the keys
            i['application_set'] = [x.id for x in applications]
            response = self.client.put(url, i)
            self.assertEqual(response.status_code, status.HTTP_200_OK)

            p.refresh_from_db()

            # Check
            self.assertEqual(len(applications_data),
                             len(p.application_set.all()))
Exemplo n.º 4
0
    def obj_create(self, bundle, **kwargs):
        """
        Creates a new application
        """
        try:
            user = User.objects.get(id=bundle.data['user_id'])
            print user
            company = Company.objects.get(id=bundle.data['company_id'])
            print company
            fair = Fair.objects.get(id=bundle.data['fair_id'])
            print fair
            if 'position' in bundle.data.keys():
                position = bundle.data['position']
            else:
                position = 'Any'
            if 'status' in bundle.data.keys():
                status = bundle.data['status']
            else:
                status = 1
            # auto-checkin the user
            old_checkin = Hunt.objects.filter(user=user, fair=fair)
            if not len(old_checkin) > 0:
                new_checkin = Hunt(user=user, fair=fair)
                new_checkin.save()
            # check if an application already exists
            old_application = Application.objects.filter(user=user,
                                                         company=company,
                                                         fair=fair)
            if len(old_application) > 0:
                bundle.obj = old_application[0]
            else:
                new_application = Application(user=user,
                                              company=company,
                                              fair=fair,
                                              status=status,
                                              position=position)
                new_application.save()
                bundle.obj = new_application

            # update user preferences for Graduation Date, Major, Degree
            try:
                grad_year = bundle.data['grad_year']
                user.student.graduation_year = grad_year
                user.student.save()
            except Exception, e:
                print e
                # raise e
            try:
                majors = bundle.data['majors']
                for major in majors:
                    major_obj = Major.objects.get(id=int(major))
                    user.student.major.add(major_obj)
                user.student.save()
            except Exception, e:
                print e
Exemplo n.º 5
0
def save_draft(request):
    d = DraftApplication()
    d.user = request.user
    form_keys = set(dict(forms.ApplicationForm().fields).keys())
    valid_keys = set(
        [field.name for field in Application()._meta.get_fields()])
    d.save_dict(
        dict((k, v) for k, v in request.POST.items()
             if k in valid_keys.intersection(form_keys) and v))
    d.save()
    return JsonResponse({'saved': True})
Exemplo n.º 6
0
 def test_payments_property(self):
     """
     Test payments property for Application class.
     """
     application = Application()
     application.name = "Test"
     application.agreement_id = "2"
     self.assertEqual(
         application.payments,
         "Payment ID: 1\nAmount: 24.00\nDate: 03-12-2017\n\nPayment ID: 5\n"
         + "Amount: 27.00\nDate: 01-12-2017\n\n")
Exemplo n.º 7
0
    def test_add_not(self):
        Application(id=52).save()
        for id in [18, 52, 59, 60]:
            av = AppVersion(application_id=id, version='1')
            av.save()
            ApplicationsVersions(application_id=id, min=av, max=av,
                                 version=self.version).save()

        res = self.client.get(self.url)
        doc = pq(res.content)
        assert not res.context['compat_form'].extra_forms
        assert doc('p.add-app')[0].attrib['class'] == 'add-app hide'
Exemplo n.º 8
0
def scored_applications(future_event_form, admin_user):
    Application.objects.bulk_create(
        Application(form=future_event_form, email=f"foo+{i}@email.com")
        for i in range(5))

    applications = Application.objects.filter(form=future_event_form)

    for i, application in enumerate(applications):
        Score.objects.create(user=admin_user,
                             application=application,
                             score=i + 1)

    return applications
Exemplo n.º 9
0
    def test_ap_is_authenticated(self):
        url = reverse('api:user-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        # Create an api token so we could test
        a = Application(name="Test permissions")
        a.save()
        authorized_client = APIClient()
        authorized_client.credentials(
            HTTP_AUTHORIZATION='Bearer {0}'.format(a.token))

        response = authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemplo n.º 10
0
    def match_with_offers(self, lender=None, return_existed=False):
        """
        Сопоставляет Анкету клиента с имеющимися актуальными Предложениями.
        Для найденных подходящих Предложений создаёт Заявки, но НЕ сохраняет их в базу.
        За сохранение в БД отвечает код, вызывающий этот метод. Это помогает оптимизировать взаимодействие с БД.

        :param lender: lenders.Lender.
                       Если задано, то подходящие Предложения ищутся только у этой Кредитной организации.

        :param return_existed: boolean, по умолчанию False.
                               Если True, то кроме новых Заявок возвращает уже существующие у этой Анкеты Заявки.

        :return: если return_existed=False (значение по умлочанию), то
                 list of applications.Application, список новых не сохранённых в базу Заявок

                 если return_existed=True, то
                 (list of applications.Application, list of applications.Application),
                 список уже имеющихся у этой Анкеты Заявок и список новых не сохранённых в базу Заявок
        """
        from applications.models import Application  # Импортируем тут, иначе получается циклический импорт.
        new_applications = []

        existed_apps_qs = self.application_set.all()
        if lender:
            existed_apps_qs = existed_apps_qs.filter(
                lender_offer__lender=lender)

        existed_matched_offers_ids = [
            app.lender_offer_id for app in existed_apps_qs
        ]

        matched_offers_qs = Offer.objects.filter(
            min_credit_score__lte=self.credit_score,
            max_credit_score__gte=self.credit_score,
            rotating_start__lte=datetime.now(),
            rotating_end__gte=datetime.now()).exclude(
                pk__in=existed_matched_offers_ids)
        if lender:
            matched_offers_qs = matched_offers_qs.filter(lender=lender)

        for offer in matched_offers_qs:
            new_applications.append(
                Application(customer=self, lender_offer=offer))

        if return_existed:
            return existed_apps_qs, new_applications

        return new_applications
Exemplo n.º 11
0
    def get_context_data(self, **kwargs):
        context = super(HackerDashboard, self).get_context_data(**kwargs)
        try:
            draft = DraftApplication.objects.get(user=self.request.user)
            form = forms.ApplicationForm(instance=Application(
                **draft.get_dict()))
        except:
            form = forms.ApplicationForm()
        context.update({'form': form})
        try:
            application = Application.objects.get(user=self.request.user)
            deadline = get_deadline(application)
            context.update({'invite_timeleft': deadline - timezone.now()})
        except:
            # We ignore this as we are okay if the user has not created an application yet
            pass

        return context
Exemplo n.º 12
0
    def save(self, *args, **kwargs):
        if not self.pk:
            is_new = True
        else:
            is_new = False

        super(CustomAccount, self).save(*args, **kwargs)

        if is_new and self.category:
            application = Application()
            application.user = self
            application.category = self.category.applicationcategory
            application.save()

            for question in application.category.questions.all():
                answer = ApplicationAnswer()
                answer.question = question
                answer.application = application
                answer.save()
Exemplo n.º 13
0
def newApplication(request):
    if not isRecruiter(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a recruiter.'
        })
    sample = string.lowercase + string.digits
    token = ''.join(random.sample(sample, 5))

    app = Application(token=token)
    app.save()
    c = Comment(app=app,
                author=request.user.userprofile,
                date=datetime.utcnow(),
                text="Generated the Token",
                auto_generated=True)
    c.save()
    return HttpResponse(
        request.build_absolute_uri(
            reverse('applications:apply', kwargs={'token': token})))
Exemplo n.º 14
0
def create_apps(apps, schema_editor):
    apps = (
        {
            "theme": "clancy",
            "description": "",
            "name": "App1"
        },
        {
            "theme": "clancy",
            "description": "",
            "name": "App2"
        },
        {
            "theme": "clancy",
            "description": "",
            "name": "App3"
        },
    )

    for a in apps:
        Application(name=a["name"], description=a["description"]).save()
Exemplo n.º 15
0
def scanning_generate_view(request):
    if request.method == 'GET':
        credentials = []
        count = int(request.GET.get('count', 1))

        if count > 10:
            return JsonResponse(
                {
                    'status':
                    500,
                    'message':
                    'The count in this request is not included or too high. Max. 10'
                },
                status=500)

        for x in range(count):
            user = User(email='tester' + str(randint(999, 9999999999)) +
                        '@ugahacks.com',
                        name='Tester Account')
            user.set_password('password1')
            user.save()

            application = Application(user=user,
                                      origin='test',
                                      first_timer=True,
                                      first_ugahacks=True,
                                      description="I'm a tester account",
                                      university="University of Georgia",
                                      degree="Computational Testing")
            application.save()
            credentials.append({
                'participantQr': application.uuid,
                'badgeQr': uuid.uuid4()
            })

        return JsonResponse({
            'status': 200,
            'message': credentials,
        },
                            status=200)
Exemplo n.º 16
0
def apply_anonymous(request):
    if not request.user.is_authenticated():
        return redirect("core:register")

    try:
        app = request.user.userprofile.application
        if app.status != Application.OFFERED:
            return redirect("applications:mystatus")
    except ObjectDoesNotExist:
        sample = string.lowercase + string.digits
        token = ''.join(random.sample(sample, 5))
        app = Application(token=token,
                          applicantProfile=request.user.userprofile)
        app.save()
        c = Comment(app=app,
                    author=request.user.userprofile,
                    date=datetime.utcnow(),
                    text="Started Application",
                    auto_generated=True)
        c.save()

    return apply_common(request, app)
Exemplo n.º 17
0
def apply(request, project_name):
    # this view shows the project name as well as the project questions
    # need to add user authentication

    # check to see if that partner project exists, if so, get the questions for it
    try:
        project = Project.objects.get(project_name=project_name)
        questions = Question.objects.filter(
            project=project)  # .order_by('question_num')
    except Question.DoesNotExist:
        raise Http404("Question does not exist.")
    except Project.DoesNotExist:
        raise Http404("Project does not exist.")

    email = None
    if request.user.is_authenticated:
        email = request.user.email
    else:
        messages.info(request, "You must be logged in to apply to a project.")
        return redirect('/')

    try:
        student = Student.objects.get(email_address=email)
    except ObjectDoesNotExist:
        if Partner.objects.filter(email_address=email).count() > 0:
            messages.info(request,
                          "You must be a student to apply to projects.")
            return redirect("/projects")
        else:
            messages.info(
                request,
                "You have not yet signed up. Please complete the signup form to continue."
            )
            return redirect("/profile/signup")

    if not config.APPLICATIONS_OPEN:
        messages.info(
            request,
            "Applications are currently closed. If you believe you have received "
            "this message in error, please email [email protected].")
        return redirect("/projects")

    count = Application.objects.filter(student=student,
                                       created_at__range=[
                                           config.APP_LIMIT_START_DATE,
                                           config.APP_LIMIT_END_DATE
                                       ]).count()

    if count > config.APP_LIMIT - 1 and not student.is_scholar:
        messages.info(
            request,
            f'You have already applied to {config.APP_LIMIT} projects.')
        return redirect('/projects')
    elif count > config.SCHOLAR_APP_LIMIT - 1 and student.is_scholar:
        messages.info(
            request,
            f'You have already applied to {config.SCHOLAR_APP_LIMIT} projects.'
        )
        return redirect('/projects')

    count = Application.objects.filter(student=student,
                                       project=project).count()

    if count > 0:
        # raise Http404("Student already has an application submitted")
        messages.info(request, 'You have already applied to this project.')
        return redirect('/projects')

    # if this form is submitted, then we want to save the answers
    if request.method == 'POST':

        post = request.POST.copy()

        def querydict_to_dict(query_dict):
            data = {}
            for key in query_dict.keys():
                v = query_dict.getlist(key)
                if len(v) == 1:
                    v = v[0]
                data[key] = v
            return data

        is_valid = True
        question_ids = list(post.keys())

        ans_list = []
        # creating individual answers
        for q_id in question_ids:
            if q_id == "csrfmiddlewaretoken":
                continue

            if len(post[q_id].strip()) == 0:
                is_valid = False
                break

            new_ans = request.POST.copy()
            new_ans_keys = list(new_ans.keys())
            q_num = 0
            answer_text = ""
            for new_k in new_ans_keys:
                if new_k == "csrfmiddlewaretoken":
                    continue
                if new_k == q_id:
                    q_num = new_k
                    # answer_text = post[new_k]
                    asDict = querydict_to_dict(post)
                    if type(asDict[q_id]) != list:
                        answer_text = asDict[q_id]
                    else:
                        answer_text = ";".join(asDict[q_id])

                new_ans.pop(new_k)

            new_ans['question'] = Question.objects.get(id=q_num)
            new_ans['answer_text'] = answer_text
            ans_list.append(new_ans)

        # print(ans_list)
        for skill in get_default_skills():
            if (skill not in student.skills.keys()) or (
                    not student.skills[skill]):
                messages.info(
                    request,
                    'Please ensure you have filled out your skill levels in your profile.'
                )
                return redirect("/profile/")

        if is_valid:

            try:
                application = Application.objects.get(student=student,
                                                      project=project)
            except:
                application = Application(student=student,
                                          project=project,
                                          status="SUB")

            application.save()

            answers = []
            for post in ans_list:
                # print(post)

                request.POST = post

                form = AnswerForm(request.POST)

                if form.is_valid():
                    # print("Is valid")

                    question = form.cleaned_data['question']

                    try:
                        a = Answer.objects.get(student=student,
                                               application=application,
                                               question=question)
                        a.answer_text = form.cleaned_data['answer_text']

                    except:
                        a = Answer(
                            student=student,
                            application=application,
                            question=question,
                            answer_text=form.cleaned_data['answer_text'])

                    a.save()
                    answers.append(a)

                else:
                    # cleanup on failure
                    application.delete()
                    for a in answers:
                        a.delete()

                    logger.error(
                        f"Invalid answer for application {application}:\n{form}"
                    )
                    messages.info(
                        request,
                        'Your application was invalid and could not be processed. If this error persists, '
                        'please contact [email protected].')
                    return redirect('/projects')

            # TODO: allow students to update rank
            # studentUpdater = Student.objects.filter(email_address = email)
            # if not student.first_choice:
            #     studentUpdater.update(first_choice = project.project_name)
            # elif not student.second_choice:
            #     studentUpdater.update(second_choice = project.project_name)
            # elif not student.third_choice:
            #     studentUpdater.update(third_choice = project.project_name)
            # else:
            #     # raise Http404("Student has applied to 3 applications")
            #     messages.info(request, 'You have already applied to 3 projects.')
            #     return redirect('/projects')

            # application.save()
            send_app_confirmation_email(application)

            messages.info(request,
                          'Your application has been submitted successfully!')
            return redirect('/projects')

        else:
            messages.info(
                request,
                'Your application was invalid and could not be processed. If this error persists, '
                'please contact [email protected].')
            return redirect(request.path_info)
    else:  # GET
        form = AnswerForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form
    # print(project, type(project))
    # print(questions)

    if request.user.is_authenticated:
        print(questions)
        return render(request, 'projects/application.html', {
            'questions': questions,
            'project': project,
            'form': form
        })
    else:
        raise PermissionDenied("User is not logged in.")
Exemplo n.º 18
0
 def setUp(self):
     # Create an api token so we could test
     a = Application(name="Test wiggum")
     a.save()
     self.client.credentials(
         HTTP_AUTHORIZATION='Bearer {0}'.format(a.token))
Exemplo n.º 19
0
    def handle(self, *args, **options) -> None:
        # admin / staff user
        logger.info("creating admin user: user=admin; pw=admin")
        User.objects.create_admin_user(email="*****@*****.**", password="******")

        logger.info("creating staff user: user=staff; pw=staff")
        User.objects.create_staff_user(email="*****@*****.**", password="******")

        # user with nothing
        new_user("nothing")

        # user with confirmed email
        new_user("with_confirmed_email", with_email_confirmation())

        # user with confirmed email
        new_user("with_accepted_coc", with_accepted_coc())

        # user with profiles
        new_user(
            "profile_student",
            with_profile(
                full_name="User With Student Profile",
                profession="Student",
                gender=ProfileGenders.female,
                ticket_type=ProfileTicketTypes.student,
            ),
        )
        new_user(
            "profile_regular",
            with_profile(
                full_name="User With Regular Profile",
                profession="Worker",
                gender=ProfileGenders.male,
                ticket_type=ProfileTicketTypes.regular,
            ),
        )
        new_user(
            "profile_company",
            with_profile(
                full_name="User With Company Profile",
                profession="Spotify",
                gender=ProfileGenders.other,
                ticket_type=ProfileTicketTypes.company,
            ),
        )

        # users with applications
        new_user("with_application_not_started", with_application())
        new_user("with_submissions_ongoing",
                 with_application(coding_test_started_at=datetime.now()))
        new_user(
            "with_submissions_passed",
            with_application(coding_test_started_at=datetime.now()),
            with_submission(SubmissionTypes.coding_test, 85),
            with_submission(SubmissionTypes.slu01, 91),
            with_submission(SubmissionTypes.slu02, 82),
            with_submission(SubmissionTypes.slu03, 76),
        )
        new_user(
            "with_submissions_failed",
            with_application(coding_test_started_at=datetime.now() -
                             timedelta(hours=4)))

        # users with payments
        # new_user("with_regular_payment", with_profile(ticket_type=ProfileTicketTypes.regular), with_payment())
        # new_user(
        #     "with_regular_payment_with_docs",
        #     with_profile(ticket_type=ProfileTicketTypes.regular),
        #     with_payment(), with_document()
        # )
        # new_user(
        #     "with_student_payment_with_docs",
        #     with_profile(ticket_type=ProfileTicketTypes.student),
        #     with_payment(),
        #     with_document(),
        #     with_document(doc_type="student_id", file_location=ASSET_STUDENT_ID_PNG),
        # )
        # new_user("with_company_payment", with_profile(ticket_type=ProfileTicketTypes.company),
        # with_payment(), with_document())

        # randoms (will be bulk created)
        users: List[User] = []
        # random - users
        logger.info(
            f"creating {_random_n} random users with profiles and applications"
        )
        for i in range(0, _random_n):
            u = User(email=f"random_{i}@adm.com")
            users.append(u)

        User.objects.bulk_create(users)
        users = User.objects.filter(email__in=[u.email for u in users])

        # random - profiles
        profiles: List[Profile] = []
        for prof_u in users:
            gender = random.choice([
                ProfileGenders.female, ProfileGenders.male,
                ProfileGenders.other
            ])
            ticket_type = random.choice([
                ProfileTicketTypes.regular, ProfileTicketTypes.company,
                ProfileTicketTypes.student
            ])
            p = Profile(
                user=prof_u,
                full_name=f"Random User {prof_u.id}",
                profession=f"Random Profession {prof_u.id}",
                gender=gender,
                ticket_type=ticket_type,
            )
            profiles.append(p)
        Profile.objects.bulk_create(profiles)

        # random - applications
        applications: List[Application] = []
        for app_u in users:
            minutes_delta = random.randrange(0, 300, 20)
            a = Application(user=app_u,
                            coding_test_started_at=datetime.now() -
                            timedelta(minutes=minutes_delta))
            applications.append(a)
        Application.objects.bulk_create(applications)
        applications = Application.objects.filter(user__in=users)

        # random - submissions
        submissions: List[Submission] = []
        for sub_a in applications:
            for j in range(0, 15):
                s_type = random.choice([
                    SubmissionTypes.coding_test.uname,
                    SubmissionTypes.slu01.uname,
                    SubmissionTypes.slu02.uname,
                    SubmissionTypes.slu03.uname,
                ])
                score = random.randrange(60, 100, 2)
                s = Submission(application=sub_a,
                               submission_type=s_type,
                               score=score,
                               feedback_location="404")
                submissions.append(s)

        Submission.objects.bulk_create(submissions)

        logger.info(self.summary())
Exemplo n.º 20
0
def app_view(request):
    form = ApplicationForm(request.POST or None)
    print(form.errors)
    msg = None
    smsg = None
    if request.method == "POST":
        if form.is_valid():
            firstName = form.cleaned_data.get("firstname")
            lastName = form.cleaned_data.get("lastname")
            gender = form.cleaned_data.get("gender")
            employeeId = form.cleaned_data.get("employeeId")
            phone = form.cleaned_data.get("phone")
            doj = form.cleaned_data.get("doj")
            dob = form.cleaned_data.get("dob")
            maritalstatus = form.cleaned_data.get("maritalstatus")
            physical = form.cleaned_data.get("physical")
            chronicillness = form.cleaned_data.get("chronicillness")
            email = form.cleaned_data.get("email")
            school = form.cleaned_data.get("school")
            try:
                isApp = Application.objects.get(employee_id=employeeId)
                msg = "Employee alredy created."
                form = ApplicationForm()
            except Application.DoesNotExist:
                app_ref = get_random_string().upper()[:8]
                user_ob = get_user_model()(username=app_ref)
                user_ob.set_password("app_" + app_ref)
                user_ob.save()
                points = 0
                status = 'Pending'
                expYrs = calculateExp(doj)
                try:
                    sch = School.objects.get(id=school)
                    schcategory = SchoolCategory.objects.get(
                        id=sch.category_id)
                except School.DoesNotExist:
                    sch = None
                except SchoolCategory.DoesNotExist:
                    schcategory = None
                if schcategory:
                    points = schcategory.point
                if expYrs >= 8:
                    print('{} {}'.format(maritalstatus, gender))
                    if maritalstatus == '0' and gender == '2':
                        points += 5
                    if physical == '1':
                        points += 10

                    app = Application(app_ref_no=app_ref,
                                      first_name=firstName,
                                      last_name=lastName,
                                      gender=gender,
                                      employee_id=employeeId,
                                      phone_no=phone,
                                      date_of_join=doj,
                                      email=email,
                                      marital_status=maritalstatus,
                                      physical_disabled=physical,
                                      chronic_illness='0',
                                      created_by=user_ob,
                                      years_of_exp=expYrs,
                                      status=status,
                                      points=points,
                                      school=sch,
                                      date_of_birth=dob)
                    app.save()
                    sendAppMail(email, '{} {}'.format(firstName, lastName),
                                app_ref)
                    form = ApplicationForm()
                    smsg = 'Employee saved successfully and sent email with ref no'
                else:
                    msg = 'Employee is not eligible for transfer.'
        else:
            msg = 'Error validating the form'

    choices = getSchools()
    c = []
    for choice in choices:
        c.append((choice.id, '{} - {}'.format(choice.school_name,
                                              choice.village)))
        form.fields['school'].widget.choices = c
    return render(request, "newapp.html", {
        "form": form,
        "msg": msg,
        'segment': 'newapp',
        'smsg': smsg
    })
Exemplo n.º 21
0
def app_view(request):
    form = ApplicationForm(request.POST or None)
    print(form.errors)
    msg = None
    if request.method == "POST":
        if form.is_valid():
            firstName = form.cleaned_data.get("firstname")
            lastName = form.cleaned_data.get("lastname")
            gender = form.cleaned_data.get("gender")
            employeeId = form.cleaned_data.get("employeeId")
            phone = form.cleaned_data.get("phone")
            doj = form.cleaned_data.get("doj")
            maritalstatus = form.cleaned_data.get("maritalstatus")
            physical = form.cleaned_data.get("physical")
            chronicillness = form.cleaned_data.get("chronicillness")
            email = form.cleaned_data.get("email")
            try:
                isApp = Application.objects.get(employee_id=employeeId)
                msg = "Application alredy created, plz try in Edit/Submit Application"
                form = ApplicationForm()
            except Application.DoesNotExist:
                app_ref = get_random_string().upper()[:8]
                user_ob = get_user_model()(username=app_ref)
                user_ob.set_password("app_" + app_ref)
                user_ob.save()
                points = 0
                status = 'Pending'
                date_doj = datetime.strptime(doj, '%Y-%m-%d')
                expYrs = calculateExp(date_doj)
                if expYrs >= 8:
                    points = 1
                    print('{} {}'.format(maritalstatus, gender))
                    if maritalstatus == '0' and gender == '2':
                        points += 5
                    if physical == '1':
                        points += 10
                    if chronicillness != '0':
                        points += 1000  # This points is consider as the user can choose any location
                else:
                    status = 'NotEligible'
                app = Application(app_ref_no=app_ref,
                                  first_name=firstName,
                                  last_name=lastName,
                                  gender=gender,
                                  employee_id=employeeId,
                                  phone_no=phone,
                                  date_of_join=doj,
                                  email=email,
                                  marital_status=maritalstatus,
                                  physical_disabled=physical,
                                  chronic_illness=chronicillness,
                                  created_by=user_ob,
                                  years_of_exp=expYrs,
                                  status=status,
                                  points=points)
                app.save()
                # sendAppMail(email, '{} {}'.format(
                #     firstName, lastName), app_ref)
                msg = 'Application Submitted/Saved Successfully'
                # form = ApplicationForm()
        else:
            msg = 'Error validating the form'

    return render(request, "accounts/newapp.html", {"form": form, "msg": msg})
Exemplo n.º 22
0
            print("partner_created", created)
        except:
            pass

    # seeding applications
    for _, row in df_student.iterrows():
        # find corresponding Student
        try:
            student = Student.objects.get(email_address=row["Email Address"])
        except ObjectDoesNotExist:
            continue

        choices = []
        choices.append(row["1) What is your FIRST choice?"])
        choices.append(row["2) What is your SECOND choice?"])
        choices.append(row["3) What is your THIRD choice?"])

        for i in range(3):
            # find corresponding Project
            try:
                project = Project.objects.get(project_name=choices[i])
                application = Application(
                    student=student,
                    project=project,
                    rank=i + 1,
                    status="SUB",
                )
                application.save()
            except ObjectDoesNotExist:
                continue
Exemplo n.º 23
0
    def test_subsequent_applications_fail(self):
        application = Application.objects.create(
            first_names=self.person.first_names,
            last_names=self.person.last_names,
            primary_phone=self.person.primary_phone,
            national_id_number=self.person.natid,
            address_line_one='ma-haus',
            email=self.person.email,
        )

        app2 = Application(
            first_names=self.person.first_names,
            last_names=self.person.last_names,
            primary_phone=self.person.primary_phone,
            national_id_number=self.person.natid,
            address_line_one='ma-haus',
            email=self.person.email,
        )

        self.assertRaises(ValidationError, app2.save)
#     def test_can_create_customer_with_user(self):
#         customer = Customer.objects.create(
#             first_name='Waldo',
#             last_name='The Unfindable',
#             display_name='waldo',
#             primary_phone='5555555555',
#             secondary_phone='1234567893',
#             user=self.user['object']
#         )
#         self.assertEqual(Customer.objects.first().user.email, '*****@*****.**')

#     def test_picture_uploads_successfully(self):
#         customer = Customer.objects.create(
#             first_name='Waldo',
#             last_name='The Unfindable',
#             display_name='waldo',
#             primary_phone='5555555555',
#             secondary_phone='1234567893',
#             picture=SimpleUploadedFile(
#                 name='my_awesome_face.jpg',
#                 content=open(TEST_IMAGE_PATH, 'rb').read(),
#                 content_type='image/jpeg'
#             ),
#             user=self.user['object']
#         )
#         self.assertIn(
#             'my_awesome_face.jpg',
#             os.listdir(
#                 os.path.join(
#                     settings.MEDIA_ROOT,
#                     'users',
#                     f'user_{self.user["object"].id}'
#                 )
#             )            
#         )

#     def test_reverse_relation_to_user_model(self):
#         customer = Customer.objects.create(
#             first_name='Waldo',
#             last_name='The Unfindable',
#             display_name='waldo',
#             primary_phone='5555555555',
#             secondary_phone='1234567893',
#             picture=SimpleUploadedFile(
#                 name='my_awesome_face.jpg',
#                 content=open(TEST_IMAGE_PATH, 'rb').read(),
#                 content_type='image/jpeg'
#             ),
#             user=self.user['object']
#         )
#         self.assertEqual(customer.user, self.user['object'])
    

# class AddressModelTests(TestCase):

#     @classmethod
#     def setUpTestData(cls):
#         user = User.objects.create_user(
#                             email='*****@*****.**',
#                             password='******'
#                         )
#         user.save()
#         customer = Customer.objects.create(
#             first_name='Waldo',
#             last_name='The Unfindable',
#             display_name='waldo',
#             primary_phone='5555555555',
#             secondary_phone='1234567893',
#             picture=SimpleUploadedFile(
#                 name='my_awesome_face.jpg',
#                 content=open(TEST_IMAGE_PATH, 'rb').read(),
#                 content_type='image/jpeg'
#             ),
#             user=user
#         )
#         cls.customer = customer

#     def test_cannot_create_address_without_customer(self):
#         address = Address(
#             full_name='My first address',
#             state_province_region='Santo Domingo',
#             city='DN',
#             sector='Los Cacicazgos',
#             address_line_one='c/ Hatuey',
#             phone_number='5555555555',
#             is_primary=False
#         )
#         self.assertRaises(ValidationError, address.save)

    # def test_can_create_address_with_customer(self):
    #     address = Address.objects.create(
    #         full_name='My first address',
    #         state_province_region='Santo Domingo',
    #         city='DN',
    #         sector='Los Cacicazgos',
    #         address_line_one='c/ Hatuey',
    #         phone_number='5555555555',
    #         is_primary=False,
    #         owner=self.customer
    #     )
    #     self.assertEqual(
    #         Address.objects.first().full_name,
    #         address.full_name
    #     )

    # @patch('googlemaps.Client.geocode')
    # def test_geocode_is_called_properly(self, mock_geocode):
    #     address = Address.objects.create(
    #         full_name='My first address',
    #         state_province_region='Santo Domingo',
    #         city='DN',
    #         sector='Los Cacicazgos',
    #         address_line_one='c/ Hatuey, no. 102',
    #         phone_number='5555555555',
    #         is_primary=False,
    #         owner=self.customer
    #     )
    #     print(address.address_line_two)

    #     gmaps = googlemaps.Client(key=settings.GOOGLEMAPS_SECRET_KEY)
    #     gmaps.geocode('c/ Hatuey, no. 102, Los Cacicazgos, Santo Domingo, Dominican Republic')

    #     self.assertTrue(mock_geocode.called)


    # @patch('googlemaps.Client.geocode')
    # def test_address_is_geocoded_properly(self, mock_geocode):
    #     address = Address.objects.create(
    #         full_name='My first address',
    #         state_province_region='Santo Domingo',
    #         city='DN',
    #         sector='Los Cacicazgos',
    #         address_line_one='c/ Hatuey, no. 102',
    #         phone_number='5555555555',
    #         is_primary=False,
    #         owner=self.customer
    #     )
    #     print(address.address_line_two)

    #     gmaps = googlemaps.Client(key=settings.GOOGLEMAPS_SECRET_KEY)
    #     gmaps.geocode('c/ Hatuey, no. 102, Los Cacicazgos, Santo Domingo, Dominican Republic')

    #     self.assertTrue(mock_geocode.called)
    #     self.assertEqual(
    #         'c/ Hatuey, no. 102, Los Cacicazgos, DN, Santo Domingo, Dominican Republic',
    #         address.formatted_name
    #     )