Beispiel #1
0
def get_status_history(request):
    jobapp_id = request.GET.get('jopapp_id')
    success = True
    code = 0
    slist = []
    if jobapp_id is None:
        success = False
        code = 10
    else:
        statuses = StatusHistory.objects.filter(job_post__pk=jobapp_id)
        try:
            slist = StatusHistorySerializer(instance=statuses, many=True).data
        except Exception as e:
            print(e)
            success = False
            code = 11
    print(slist)
    return JsonResponse(create_response(slist, success, code), safe=False)
Beispiel #2
0
def positions(request):
    q = request.GET.get('q')
    if q:
        positions = JobPosition.objects.filter(job_title__icontains=q)
    else:
        positions = JobPosition.objects.all()

    if request.GET.get('count') is not None:
        cnt = int(request.GET.get('count'))
        positions = positions[:cnt]

    paginator = pagination.CustomPagination()
    positions = paginator.paginate_queryset(positions, request)
    serialized_positions = JobPositionSerializer(instance=positions,
                                                 many=True).data
    return JsonResponse(create_response(data=serialized_positions,
                                        paginator=paginator),
                        safe=False)
Beispiel #3
0
def colleges(request):
    q = request.GET.get('q')
    if q is None:
        colleges = College.objects.all()
    else:
        colleges = College.objects.filter(short_name__icontains=q)
        if colleges.count() == 0:
            colleges = College.objects.filter(
                Q(name__icontains=q) | Q(short_name__icontains=q))
    paginator = pagination.CustomPagination()
    colleges = paginator.paginate_queryset(colleges, request)
    serialized_colleges = CollegeSerializer(
        instance=colleges,
        many=True,
    ).data
    return JsonResponse(create_response(data=serialized_colleges,
                                        paginator=paginator),
                        safe=False)
Beispiel #4
0
def get_jobapp_detail(request):
    id = request.GET.get('jopapp_id')
    try:
        details = JobPostDetail.objects.all().get(job_post__pk=id)
        jobapp_detail = {}
        jobapp_detail['posterInformation'] = json.loads(
            details.posterInformation)
        jobapp_detail['decoratedJobPosting'] = json.loads(
            details.decoratedJobPosting)
        jobapp_detail['topCardV2'] = json.loads(details.topCardV2)
        success = True
        code = 0
    except Exception as e:
        print(e)
        success = False
        code = 11
        jobapp_detail = None
    return JsonResponse(create_response(jobapp_detail, success, code),
                        safe=False)
Beispiel #5
0
def update_gmail_token(request):
    token = request.POST['token']
    try:
        user_profile = UserSocialAuth.objects.get(user=request.user)
        print(user_profile)
        if user_profile is not None:
            user_profile.extra_data['access_token'] = token
            user_profile.save()
            success = True
            code = 0
            scheduleFetcher(request.user.id)
        else:
            success = False
            code = 2
    except Exception as e:
        print(e)
        success = False
        code = 3
    return JsonResponse(create_response(None, success, code), safe=False)
Beispiel #6
0
def apply(request):
    body = request.data
    position_id = body['position_id']

    first_name = body['first_name']
    last_name = body['last_name']
    email = body['email']
    phone_number = body['phone_number']
    reference = body['reference']
    candidate_resume = body['candidate_resume']

    jt = PositionDetail.objects.get(pk=position_id)

    job_application = PositionApplication(position=jt,
                                          company_object=jt.company,
                                          first_name=first_name,
                                          last_name=last_name,
                                          email=email,
                                          apply_date=datetime.datetime.today(),
                                          reference=reference,
                                          phone_number=phone_number,
                                          user=None)

    ext = candidate_resume.name.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    name = candidate_resume.name.replace(('.' + ext), '')
    filename = name + '_' + filename
    job_application.candidate_resume.save(filename,
                                          candidate_resume,
                                          save=True)

    if ApplicationStatus.objects.filter(default=True).count() == 0:
        status = ApplicationStatus(value='Applied', default=True)
        status.save()
    else:
        status = ApplicationStatus.objects.get(default=True)
    job_application.application_status = status

    job_application.save()

    utils.send_applicant_email_to_admins(job_application.id)
    return JsonResponse(create_response(data=None), safe=False)
Beispiel #7
0
def logout(request):
    body = JSONParser().parse(request)
    post_data = {
        'token': body['token'],
        'client_id': body['client_id'],
        'client_secret': body['client_secret']
    }
    headers = {'content-type': 'application/json'}
    response = requests.post('http://localhost:8001/auth/revoke-token',
                             data=json.dumps(post_data),
                             headers=headers)
    if response.status_code is 204 or response.status_code is 200:
        success = True
        code = ResponseCodes.success
    else:
        success = False
        code = ResponseCodes.couldnt_logout_user
    return JsonResponse(create_response(data=None,
                                        success=success,
                                        error_code=code),
                        safe=False)
Beispiel #8
0
def refresh_token(request):
    body = JSONParser().parse(request)
    post_data = {
        'client_id': body['client_id'],
        'client_secret': body['client_secret'],
        'grant_type': 'refresh_token',
        'refresh_token': body['refresh_token']
    }
    response = requests.post('http://localhost:8001/auth/token',
                             data=json.dumps(post_data),
                             headers={'content-type': 'application/json'})
    json_res = json.loads(response.text)
    if 'error' in json_res:
        success = False
        code = ResponseCodes.invalid_credentials
    else:
        success = True
        code = ResponseCodes.success
    return JsonResponse(create_response(data=json_res,
                                        success=success,
                                        error_code=code),
                        safe=False)
Beispiel #9
0
def update_gmail_token(request):
    body = request.data
    token = body['token']
    try:
        user_profile = UserSocialAuth.objects.get(user=request.user)
        if user_profile is not None:
            user_profile.extra_data['access_token'] = token
            user_profile.save()
            success = True
            request.user.is_gmail_read_ok = True
            request.user.save()
            code = ResponseCodes.success
        else:
            success = False
            code = ResponseCodes.user_profile_not_found
    except Exception as e:
        log(traceback.format_exception(None, e, e.__traceback__), 'e')
        success = False
        code = ResponseCodes.couldnt_update_google_token
    return JsonResponse(create_response(data=None,
                                        success=success,
                                        error_code=code),
                        safe=False)
Beispiel #10
0
def update_jobapp(request):
    status_id = request.POST.get('status_id')
    rejected = get_boolean_from_request(request, 'rejected', 'POST')
    jobapp_id = request.POST.get('jobapp_id')
    success = True
    code = 0
    if jobapp_id is None:
        success = False
        code = 10
    elif rejected is None and status_id is None:
        success = False
        code = 10
    else:
        user_job_app = JobApplication.objects.filter(pk=jobapp_id)
        if len(user_job_app) == 0:
            success = False
            code = 11
        else:
            user_job_app = user_job_app[0]
            if status_id is None:
                user_job_app.isRejected = rejected
            else:
                new_status = ApplicationStatus.objects.filter(pk=status_id)
                if len(new_status) == 0:
                    success = False
                    code = 11
                else:
                    if rejected is None:
                        user_job_app.applicationStatus = new_status[0]
                    else:
                        user_job_app.applicationStatus = new_status[0]
                        user_job_app.isRejected = rejected
                    status_history = StatusHistory(
                        job_post=user_job_app, applicationStatus=new_status[0])
                    status_history.save()
            user_job_app.save()
    return JsonResponse(create_response(None, success, code), safe=False)
Beispiel #11
0
def dhamma(request):
    dhamma = Dhamma.objects.all().order_by('id')
    title = request.GET.get('title')
    sangha = request.GET.get('sangha')
    category = request.GET.get('category')
    mediatype = request.GET.get('mediatype')
    language = request.GET.get('language')

    if is_valid_queryparam(title):
        dhamma = dhamma.filter(title__icontains=title)
    if is_valid_queryparam(sangha):
        dhamma = dhamma.filter(sangha_name__name=sangha)
    if is_valid_queryparam(category):
        dhamma = dhamma.filter(categories__name=category)
    if is_valid_queryparam(mediatype):
        dhamma = dhamma.filter(media_type__name=mediatype)
    if is_valid_queryparam(language):
        dhamma = dhamma.filter(language__name=language)

    paginator = pagination.CustomPagination()
    dhamma = paginator.paginate_queryset(dhamma, request)
    serialized_dhamma = DhammaSerializer(instance=dhamma, many=True).data

    return JsonResponse(create_response(data=serialized_dhamma, paginator=paginator), safe=False)
Beispiel #12
0
def position_applications(request):
    body = request.data
    if 'recaptcha_token' in body and utils.verify_recaptcha(
            None, body['recaptcha_token'],
            'add_job') == ResponseCodes.verify_recaptcha_failed:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.verify_recaptcha_failed),
                            safe=False)
    if request.method == "GET":
        status_id = request.GET.get('status_id')
        if status_id is not None:
            user_job_apps = PositionApplication.objects.filter(
                Q(user__id=request.user.id)
                | Q(position__company=request.user.company),
                application_status__id=status_id,
                is_deleted=False).order_by('-apply_date')
        else:
            user_job_apps = PositionApplication.objects.filter(
                Q(user__id=request.user.id)
                | Q(position__company=request.user.company),
                is_deleted=False).order_by('-apply_date')
        job_applications_list = PositionApplicationSerializer(
            instance=user_job_apps, many=True, context={
                'user': request.user
            }).data
        return JsonResponse(create_response(data=job_applications_list),
                            safe=False)
    elif request.method == "POST":
        position_id = body['position_id']
        company = body['company']
        application_date = body['application_date']
        status = int(body['status_id'])
        first_name = body['first_name']
        last_name = body['last_name']
        jt = PositionDetail.objects.get(pk=position_id)
        jc = get_or_create_company(company)
        job_application = PositionApplication(position=jt,
                                              company_object=jc,
                                              first_name=first_name,
                                              last_name=last_name,
                                              apply_date=application_date,
                                              user=request.user)
        job_application.application_status = ApplicationStatus.objects.get(
            pk=status)
        job_application.save()
        return JsonResponse(create_response(
            data=PositionApplicationSerializer(instance=job_application,
                                               many=False,
                                               context={
                                                   'user': request.user
                                               }).data),
                            safe=False)
    elif request.method == "PUT":
        status_id = body.get('status_id')
        rejected = body.get('rejected')
        job_application_ids = []
        if 'jobapp_ids' in body:
            job_application_ids = body['jobapp_ids']
        if 'jobapp_id' in body:
            job_application_ids.append(body['jobapp_id'])
        if len(job_application_ids) == 0:
            return JsonResponse(create_response(
                success=False, error_code=ResponseCodes.record_not_found),
                                safe=False)
        elif rejected is None and status_id is None:
            return JsonResponse(create_response(
                success=False, error_code=ResponseCodes.record_not_found),
                                safe=False)
        else:
            user_job_apps = PositionApplication.objects.filter(
                pk__in=job_application_ids)
            if user_job_apps.count() == 0:
                return JsonResponse(create_response(
                    success=False, error_code=ResponseCodes.record_not_found),
                                    safe=False)
            else:
                for user_job_app in user_job_apps:
                    if user_job_app.user == request.user:
                        if status_id is None:
                            user_job_app.is_rejected = rejected
                        else:
                            new_status = ApplicationStatus.objects.filter(
                                pk=status_id)
                            if new_status.count() == 0:
                                return JsonResponse(
                                    create_response(data=None,
                                                    success=False,
                                                    error_code=ResponseCodes.
                                                    invalid_parameters),
                                    safe=False)
                            else:
                                if rejected is None:
                                    user_job_app.application_status = new_status[
                                        0]
                                else:
                                    user_job_app.application_status = new_status[
                                        0]
                                    user_job_app.is_rejected = rejected
                                status_history = StatusHistory(
                                    pos_app=user_job_app,
                                    application_status=new_status[0])
                                status_history.save()
                        if rejected is not None:
                            user_job_app.rejected_date = timezone.now()
                        user_job_app.updated_date = timezone.now()
                        user_job_app.save()
                return JsonResponse(create_response(data=None), safe=False)
    elif request.method == "PATCH":
        job_app_id = body.get('jobapp_id')
        if job_app_id is None:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.record_not_found),
                                safe=False)
        user_job_app = PositionApplication.objects.get(pk=job_app_id)

        if user_job_app.user != request.user:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.record_not_found),
                                safe=False)

        job_title = body.get('job_title')
        company = body.get('company')
        application_date = body.get('application_date')
        source = body.get('source')

        if application_date is not None:
            user_job_app.apply_date = application_date
        if job_title is not None:
            user_job_app.position = get_or_insert_position(job_title)
        if company is not None:
            user_job_app.company_object = get_or_create_company(company)
        user_job_app.updated_date = timezone.now()
        user_job_app.save()
        return JsonResponse(create_response(data=PositionApplicationSerializer(
            instance=user_job_app, many=False, context={
                'user': request.user
            }).data),
                            safe=False)
    elif request.method == "DELETE":
        job_application_ids = []
        if 'jobapp_ids' in body:
            job_application_ids = body['jobapp_ids']
        if 'jobapp_id' in body:
            job_application_ids.append(body['jobapp_id'])
        if len(job_application_ids) == 0 or PositionApplication.objects.filter(
                pk__in=job_application_ids).count() == 0:
            return JsonResponse(create_response(
                success=False, error_code=ResponseCodes.record_not_found),
                                safe=False)
        else:
            user_job_apps = PositionApplication.objects.filter(
                pk__in=job_application_ids)
            for user_job_app in user_job_apps:
                if user_job_app.user == request.user:
                    user_job_app.deleted_date = timezone.now()
                    user_job_app.is_deleted = True
                    user_job_app.save()
            return JsonResponse(create_response(data=None), safe=False)
Beispiel #13
0
def company_positions(request):
    body = request.data
    if request.method == "GET":
        company_id = request.GET.get('id')
        q = request.GET.get('q')
        department = request.GET.get('department')
        job_type = request.GET.get('type')
        if q is not None and company_id is not None:
            # jobs = JobPosition.objects.filter(job_title__icontains=q)
            positions = PositionDetail.objects.filter(
                company_id=company_id, is_deleted=False,
                job__icontains=q).order_by("-updated_date")
        elif q is None and company_id is None:
            positions = PositionDetail.objects.filter(
                is_deleted=False).order_by("-updated_date")
        elif q is None and company_id is not None:
            positions = PositionDetail.objects.filter(
                company_id=company_id,
                is_deleted=False).order_by("-updated_date")
        elif q is not None and company_id is None:
            positions = PositionDetail.objects.filter(
                is_deleted=False, job__icontains=q).order_by("-updated_date")

        if department is not None:
            positions = positions.filter(department=department)
        if job_type is not None:
            positions = positions.filter(job_type=job_type)
        paginator = pagination.CustomPagination()
        positions = paginator.paginate_queryset(positions, request)
        serialized_positions = PositionDetailSerializer(instance=positions,
                                                        many=True).data
        return JsonResponse(create_response(data=serialized_positions,
                                            paginator=paginator),
                            safe=False)
    elif request.method == "POST":
        job_title = body["job_title"]
        responsibilities = body["responsibilities"]
        requirements = body["requirements"]
        department = body["department"]
        job_type = body["job_type"]
        city = body["city"]
        company_id = int(body["company_id"])
        #job = JobPosition.objects.get(job_title=job_title)
        job = job_title
        state = State.objects.get(pk=body["state_id"])
        country = Country.objects.get(pk=body["country_id"])
        company = Company.objects.get(pk=body["company_id"])
        new_position = PositionDetail(job=job,
                                      responsibilities=responsibilities,
                                      requirements=requirements,
                                      department=department,
                                      job_type=job_type,
                                      city=city,
                                      country=country,
                                      state=state,
                                      company=company)

        new_position.save()
        return JsonResponse(create_response(data=PositionDetailSerializer(
            instance=new_position, many=False, context={
                'user': request.user
            }).data),
                            safe=False)
    elif request.method == "DELETE":
        position_id = body["position_id"]
        position = PositionDetail.objects.get(pk=position_id)
        position.is_deleted = True
        position.save()
        return JsonResponse(create_response(data=None), safe=False)
    elif request.method == "PATCH":
        position_id = body["position_id"]
        position = PositionDetail.objects.get(pk=position_id)
        job = body.get('job_title')
        responsibilities = body.get('responsibilities')
        requirements = body.get('requirements')
        department = body.get('department')
        job_type = body.get('job_type')
        city = body.get('city')
        state_id = body.get('state_id')
        country_id = body.get('country_id')

        if responsibilities is not None:
            position.responsibilities = responsibilities
        if job is not None:
            position.job = job
        if requirements is not None:
            position.requirements = requirements
        if department is not None:
            position.department = department
        if job_type is not None:
            position.job_type = job_type
        if city is not None:
            position.city = city
        if state_id is not None:
            position.state_id = state_id
        if country_id is not None:
            position.country_id = country_id

        position.save()
        return JsonResponse(create_response(data=PositionDetailSerializer(
            instance=position, many=False, context={
                'user': request.user
            }).data),
                            safe=False)
Beispiel #14
0
def delete_user(request):
    request.user.delete()
    return JsonResponse(create_response(data=None), safe=False)
Beispiel #15
0
def faqs(request):
    faq = Faq.objects.filter(is_published=True)
    slist = FaqSerializer(instance=faq, many=True).data
    return JsonResponse(create_response(data=slist), safe=False)
Beispiel #16
0
def states(request, country_pk):
    states = State.objects.filter(country__pk=country_pk)
    slist = StateSerializer(instance=states, many=True).data
    return JsonResponse(create_response(data=slist), safe=False)
Beispiel #17
0
def employment_statuses(request):
    statuses = EmploymentStatus.objects.all()
    return JsonResponse(create_response(
        data=EmploymentStatusSerializer(instance=statuses, many=True).data),
                        safe=False)
Beispiel #18
0
def update_profile(request):
    body = request.data
    if 'recaptcha_token' in body and utils.verify_recaptcha(
            request.user.email, body['recaptcha_token'],
            'update_profile') == ResponseCodes.verify_recaptcha_failed:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.verify_recaptcha_failed),
                            safe=False)

    user = request.user
    if 'password' in body:
        user.set_password(body['password'])
    if 'username' in body:
        if User.objects.filter(username=body['username']).exists():
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.username_exists),
                                safe=False)
        user.username = body['username']
    if 'first_name' in body:
        user.first_name = body['first_name']
    if 'last_name' in body:
        user.last_name = body['last_name']
    if 'gender' in body:
        user.gender = body['gender']
    if 'dob' in body:
        user.dob = datetime.strptime(body['dob'], "%Y-%m-%d").date()
    if 'student_email' in body:
        user.student_email = body['student_email']
    if 'is_email_public' in body:
        user.is_email_public = body['is_email_public']
    if 'phone_number' in body:
        user.phone_number = body['phone_number']
    if 'emp_status_id' in body:
        if EmploymentStatus.objects.filter(
                pk=body['emp_status_id']).count() > 0:
            user.emp_status = EmploymentStatus.objects.get(
                pk=body['emp_status_id'])
    user_type, new = UserType.objects.get_or_create(name__iexact='Employer')

    if 'college_id' in body:
        if College.objects.filter(pk=body['college_id']).count() > 0:
            user.college = College.objects.get(pk=body['college_id'])
    if 'major' in body:
        user.major = insert_or_update_major(body['major'])
    if 'grad_year' in body:
        user.grad_year = body['grad_year']
    if 'job_title' in body:
        job_title = body['job_title']
        user.job_position = get_or_insert_position(job_title)
    if 'company' in body:
        company = body['company']
        user.company = get_or_create_company(company)

    if 'country_id' in body and 'state_id' in body:
        state = State.objects.get(pk=body['state_id'])
        if state.country.id != body['country_id']:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.invalid_parameters),
                                safe=False)
        country = Country.objects.get(pk=body['country_id'])
        user.country = country
        user.state = state

    user.signup_flow_completed = True
    user.save()
    return JsonResponse(create_response(
        data=ProfileSerializer(instance=user, many=False).data),
                        safe=False)
Beispiel #19
0
def link_social_account(request):
    body = request.data
    if 'recaptcha_token' in body and utils.verify_recaptcha(
            None, body['recaptcha_token'],
            'signin') == ResponseCodes.verify_recaptcha_failed:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.verify_recaptcha_failed),
                            safe=False)

    post_data = {
        'client_id': body['client_id'],
        'client_secret': body['client_secret'],
        'grant_type': 'convert_token'
    }
    provider = body['provider']
    post_data['backend'] = provider
    if provider == 'linkedin-oauth2':
        if request.user.social_auth.filter(
                provider='linkedin-oauth2').count() == 0:
            post_data['token'] = get_access_token_with_code(body['token'])
        else:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.account_already_linked),
                                safe=False)
    else:
        if request.user.social_auth.filter(
                provider='google-oauth2').count() == 0:
            post_data['token'] = body['token']
        else:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.account_already_linked),
                                safe=False)
    response = requests.post('http://localhost:8001/auth/convert-token',
                             data=json.dumps(post_data),
                             headers={'content-type': 'application/json'})
    json_res = json.loads(response.text)
    log(json_res, 'e')
    if 'error' in json_res:
        success = False
        code = ResponseCodes.invalid_credentials
    else:
        social_user = UserSocialAuth.objects.get(
            extra_data__icontains=post_data['token'])

        if social_user.user.email != request.user.email:
            social_user.user.delete()

        social_user.user = request.user
        social_user.save()

        post_data = {
            'token': json_res['access_token'],
            'client_id': body['client_id'],
            'client_secret': body['client_secret']
        }
        headers = {'content-type': 'application/json'}
        response = requests.post('http://localhost:8001/auth/revoke-token',
                                 data=json.dumps(post_data),
                                 headers=headers)

        log(str(response), 'e')
        if provider == 'google-oauth2':
            request.user.is_gmail_read_ok = True
            request.user.save()
        return JsonResponse(create_response(
            data=ProfileSerializer(instance=request.user, many=False).data),
                            safe=False)
    return JsonResponse(create_response(data=None,
                                        success=success,
                                        error_code=code),
                        safe=False)
Beispiel #20
0
def register(request):
    # Get form values
    body = JSONParser().parse(request)
    if 'recaptcha_token' in body and utils.verify_recaptcha(
            None, body['recaptcha_token'],
            'signup') == ResponseCodes.verify_recaptcha_failed:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.verify_recaptcha_failed),
                            safe=False)

    first_name = ''
    last_name = ''
    linkedin_auth_code = None
    google_access_token = None
    if 'first_name' in body:
        first_name = body['first_name']
    if 'last_name' in body:
        last_name = body['last_name']
    if 'linkedin_auth_code' in body:
        linkedin_auth_code = body['linkedin_auth_code']
    if 'google_access_token' in body:
        google_access_token = body['google_access_token']
    user_type, new = UserType.objects.get_or_create(name__iexact='Employer')
    username = body['username']
    email = body['email']
    password = body['password']
    password2 = body['password2']

    if '@' in username:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.invalid_username),
                            safe=False)

    # Check if passwords match
    if password == password2:
        # Check username
        if User.objects.filter(username__iexact=username).exists():
            success = False
            code = ResponseCodes.username_exists
        else:
            if User.objects.filter(email__iexact=email).exists():
                success = False
                code = ResponseCodes.email_exists
            else:
                # Looks good
                user = User.objects.create_user(username=username,
                                                password=password,
                                                email=email,
                                                first_name=first_name,
                                                user_type=user_type,
                                                last_name=last_name,
                                                approved=False,
                                                activation_key=None,
                                                key_expires=None)
                user.save()
                if linkedin_auth_code is None and google_access_token is None:
                    activation_key, expiration_time = utils.generate_activation_key_and_expiredate(
                        body['username'])
                    user.activation_key = activation_key
                    user.key_expires = expiration_time
                    user.save()
                    utils.send_email(user.email, activation_key, 'activate')

                    post_data = {
                        'client_id': body['client_id'],
                        'client_secret': body['client_secret'],
                        'grant_type': 'password',
                        'username': username,
                        'password': password
                    }

                    response = requests.post(
                        'http://localhost:8001/auth/token',
                        data=json.dumps(post_data),
                        headers={'content-type': 'application/json'})
                    json_res = json.loads(response.text)
                    if 'error' in json_res:
                        success = False
                        code = ResponseCodes.couldnt_login
                    else:
                        success = True
                        code = ResponseCodes.success
                        json_res['user_type'] = UserTypeSerializer(
                            instance=user.user_type, many=False).data
                        json_res[
                            'signup_flow_completed'] = user.signup_flow_completed
                    return JsonResponse(create_response(data=json_res,
                                                        success=success,
                                                        error_code=code),
                                        safe=False)
                else:
                    post_data = {
                        'client_id': body['client_id'],
                        'client_secret': body['client_secret'],
                        'grant_type': 'convert_token'
                    }
                    if linkedin_auth_code is not None:
                        post_data['backend'] = 'linkedin-oauth2'
                        post_data['token'] = get_access_token_with_code(
                            body['linkedin_auth_code'])
                    else:
                        post_data['backend'] = 'google-oauth2'
                        post_data['token'] = body['google_access_token']
                    response = requests.post(
                        'http://localhost:8001/auth/convert-token',
                        data=json.dumps(post_data),
                        headers={'content-type': 'application/json'})
                    jsonres = json.loads(response.text)
                    log(jsonres, 'e')
                    if 'error' in jsonres:
                        success = False
                        code = ResponseCodes.invalid_credentials
                    else:
                        social_user = UserSocialAuth.objects.get(
                            extra_data__icontains=post_data['token'])

                        if social_user.user.email != user.email:
                            social_user.user.delete()

                        social_user.user = user
                        social_user.save()

                        success = True
                        code = ResponseCodes.success
                        user = AccessToken.objects.get(
                            token=jsonres['access_token']).user
                        jsonres['user_type'] = UserTypeSerializer(
                            instance=user.user_type, many=False).data
                        jsonres[
                            'signup_flow_completed'] = user.signup_flow_completed
                        user.approved = True
                        user.save()
                    return JsonResponse(create_response(data=jsonres,
                                                        success=success,
                                                        error_code=code),
                                        safe=False)
    else:
        success = False
        code = ResponseCodes.passwords_do_not_match
    return JsonResponse(create_response(data=None,
                                        success=success,
                                        error_code=code),
                        safe=False)
Beispiel #21
0
def countries(request):
    countries = Country.objects.all()
    slist = CountrySerializer(instance=countries, many=True).data
    return JsonResponse(create_response(data=slist), safe=False)
Beispiel #22
0
def feedbacks(request, pos_app_pk):
    body = request.data
    if request.method == "GET":
        if pos_app_pk is None:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.invalid_parameters),
                                safe=False)
        else:
            feedbacks_list = Feedback.objects.filter(
                pos_app__pk=pos_app_pk).order_by('-updated_date',
                                                 '-created_date')
            feedbacks_list = FeedbackSerializer(instance=feedbacks_list,
                                                many=True).data
            return JsonResponse(create_response(
                data=feedbacks_list,
                success=True,
                error_code=ResponseCodes.success),
                                safe=False)
    elif request.method == "POST":
        if pos_app_pk is None:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.invalid_parameters),
                                safe=False)
        else:
            pos_app = PositionApplication.objects.get(pk=pos_app_pk)
            interviewer = body.get('interviewer')
            interview_round = body.get('interview_round')
            rate = body.get('rate')
            description = body.get('description')
            interview_date = body.get('interview_date')
            feedback = Feedback(pos_app=pos_app,
                                interviewer=interviewer,
                                interview_round=interview_round,
                                rate=rate,
                                description=description,
                                interview_date=interview_date)
            feedback.save()
            data = FeedbackSerializer(instance=feedback, many=False).data
            return JsonResponse(create_response(
                data=data, success=True, error_code=ResponseCodes.success),
                                safe=False)
    elif request.method == "PUT":
        if pos_app_pk is None:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.invalid_parameters),
                                safe=False)
        else:
            feedback_id = body.get('feedback_id')
            if feedback_id is None:
                return JsonResponse(create_response(
                    data=None,
                    success=False,
                    error_code=ResponseCodes.invalid_parameters),
                                    safe=False)
            else:
                interviewer = body.get('interviewer')
                interview_round = body.get('interview_round')
                rate = body.get('rate')
                description = body.get('description')
                interview_date = body.get('interview_date')
                feedback = Feedback.objects.get(pk=feedback_id)
                if interviewer is not None:
                    feedback.interviewer = interviewer
                if interview_round is not None:
                    feedback.interview_round = interview_round
                if rate is not None:
                    feedback.rate = rate
                if description is not None:
                    feedback.description = description
                if interview_date is not None:
                    feedback.interview_date = interview_date
                feedback.save()
                data = FeedbackSerializer(instance=feedback, many=False).data
                return JsonResponse(create_response(
                    data=data, success=True, error_code=ResponseCodes.success),
                                    safe=False)
    elif request.method == "DELETE":
        feedback_id = body.get('feedback_id')
        if feedback_id is None:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.invalid_parameters),
                                safe=False)
        else:
            feedback = Feedback.objects.get(pk=feedback_id)
            feedback.delete()
            return JsonResponse(create_response(
                data=None, success=True, error_code=ResponseCodes.success),
                                safe=False)
Beispiel #23
0
def agg_detailed(request):
    response = []
    user_profile = request.user
    User = get_user_model()
    filter_by_college = False
    public = get_boolean_from_request(request, 'public')
    if user_profile.user_type >= int(User.UserTypes.student) and not public:
        college_users = User.objects.filter(id__in=[
            p.id for p in User.objects.filter(college=user_profile.college,
                                              is_demo=False)
        ])
        filter_by_college = True

    if user_profile.user_type < int(User.UserTypes.student) and not public:
        return JsonResponse(create_response(
            data=None,
            success=False,
            error_code=ResponseCodes.not_supported_user),
                            safe=False)

    for graph in range(4):
        item = {}
        if graph == 0:
            item['graph'] = {}
            item['graph']['type'] = 'bar'
            item['graph']['series'] = []
            item['graph']['title'] = 'Top Companies Applied'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Companies Applied'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-1)
            months = []
            months_string = []

            if filter_by_college:
                distinct_jobapps = JobApplication.objects.filter(
                    user__in=college_users).distinct('company_object', 'user')
            else:
                distinct_jobapps = JobApplication.objects.filter(
                    user__is_demo=False).distinct('company_object', 'user')
            #  ~Q(application_status__pk = 2) indicates not 'To Apply' statuses in the prod DB.
            top_companies = JobApplication.objects.filter(
                ~Q(application_status=None),
                ~Q(application_status__pk=2),
                apply_date__range=[last_year, today],
                is_deleted=False).values(
                    company=F('company_object__company')).annotate(
                        count=Count('company_object')).filter(
                            id__in=distinct_jobapps).order_by('-count')

            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
                months_string.insert(0, d.strftime("%B"))
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                months_string.insert(0, dec.strftime("%B"))
                dec = dec + relativedelta(months=-1)

            item['graph']['xAxis'] = months_string

            if top_companies.count() > 10:
                top_companies = top_companies[:10]

            total = 0
            for company in top_companies:
                serie = {'name': company['company'], 'type': 'bar'}
                data = [0] * 12
                for j in range(0, 12):
                    count = JobApplication.objects.filter(
                        company_object__company=company['company'],
                        apply_date__year=months[j].year,
                        apply_date__month=months[j].month,
                        is_deleted=False,
                        id__in=distinct_jobapps)
                    data[j] = count.count()
                serie['data'] = data
                serie['stack'] = 'Company'
                item['graph']['series'].append(serie)
                item['list']['data'].append({
                    'id': company['company'],
                    'value': company['count']
                })
                total += company['count']
            item['list']['total'] = total

        elif graph == 1:
            item['graph'] = {}
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['graph']['title'] = 'Peak Season'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Peak Season'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-1)
            months = []
            months_string = []

            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
                months_string.insert(0, d.strftime("%B"))
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                months_string.insert(0, dec.strftime("%B"))
                dec = dec + relativedelta(months=-1)

            item['graph']['xAxis'] = months_string

            system_sources = Source.objects.filter(system=True)
            sources = ['Others', 'Total']
            for s in system_sources:
                sources.insert(0, s.value)

            for i in sources:
                if i == 'Total':
                    if filter_by_college:
                        apps = JobApplication.objects.filter(
                            user__in=college_users,
                            apply_date__range=[last_year, today],
                            is_deleted=False)
                    else:
                        apps = JobApplication.objects.filter(
                            apply_date__range=[last_year, today],
                            is_deleted=False,
                            user__is_demo=False)
                    apps_by_months = apps.values(
                        'apply_date__year',
                        'apply_date__month').annotate(count=Count('pk'))
                elif i != 'Others':
                    if filter_by_college:
                        apps = JobApplication.objects.filter(
                            user__in=college_users,
                            app_source__value=i,
                            apply_date__range=[last_year, today],
                            is_deleted=False)
                    else:
                        apps = JobApplication.objects.filter(
                            app_source__value=i,
                            apply_date__range=[last_year, today],
                            is_deleted=False,
                            user__is_demo=False)
                    apps_by_months = apps.values(
                        'apply_date__year',
                        'apply_date__month').annotate(count=Count('pk'))
                else:
                    if filter_by_college:
                        apps = JobApplication.objects.filter(
                            user__in=college_users,
                            app_source__system=False,
                            apply_date__range=[last_year, today],
                            is_deleted=False)
                    else:
                        apps = JobApplication.objects.filter(
                            app_source__system=False,
                            apply_date__range=[last_year, today],
                            is_deleted=False,
                            user__is_demo=False)
                    apps_by_months = apps.values(
                        'apply_date__year',
                        'apply_date__month').annotate(count=Count('pk'))

                serie = {'name': i}
                data = [0] * 12
                for j in range(0, 12):
                    count = apps_by_months.filter(
                        apply_date__year=months[j].year,
                        apply_date__month=months[j].month)
                    if len(count) > 0:
                        data[j] = count[0]['count']
                serie['data'] = data
                serie['type'] = "line"
                # serie['stack'] = 'Source'
                item['graph']['series'].append(serie)

            total = 0
            for idx, month in enumerate(months):
                if filter_by_college:
                    apps = JobApplication.objects.filter(
                        user__in=college_users,
                        apply_date__year=month.year,
                        apply_date__month=month.month,
                        is_deleted=False)
                else:
                    apps = JobApplication.objects.filter(
                        apply_date__year=month.year,
                        apply_date__month=month.month,
                        is_deleted=False,
                        user__is_demo=False)
                item['list']['data'].append({
                    'id':
                    months_string[idx] + ' ' + str(month.year),
                    'value':
                    apps.count()
                })
                total += apps.count()
            item['list']['data'].sort(key=lambda x: x['value'], reverse=True)
            item['list']['total'] = total
        elif graph == 2:
            item['graph'] = {}
            item['graph']['type'] = 'radar'
            item['graph']['polar'] = []
            item['graph']['series'] = []
            item['graph']['title'] = 'Skill Analysis'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Skills'

            # dummy data
            serie = {'value': [9, 8, 9, 7, 5, 3], 'name': 'Market Demand'}
            item['graph']['series'].append(serie)
            serie = {'value': [10, 8, 5, 7, 3, 2], 'name': 'Overall Skills'}
            item['graph']['series'].append(serie)
            indicators = []
            indicator = {'text': 'Java', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'Python', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'R', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'React Native', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'GO', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'React', 'max': 10}
            indicators.append(indicator)
            item['graph']['polar'].append({'indicator': indicators})

            item['list']['data'].append({'id': 'Java', 'value': 27})
            item['list']['data'].append({'id': 'GO', 'value': 18})
            item['list']['data'].append({'id': 'React', 'value': 16})
            item['list']['data'].append({'id': 'R', 'value': 14})
            item['list']['data'].append({'id': 'Python', 'value': 12})
            item['list']['data'].append({'id': 'React Native', 'value': 8})

            item['list']['total'] = 32
        elif graph == 3:
            item['graph'] = {}
            item['graph']['type'] = 'bar'
            item['graph']['series'] = []
            item['graph']['title'] = 'Top Positions Applied'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Positions Applied'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-1)
            months = []
            months_string = []

            if filter_by_college:
                distinct_positions = JobApplication.objects.filter(
                    user__in=college_users).distinct('position', 'user')
            else:
                distinct_positions = JobApplication.objects.filter(
                    user__is_demo=False).distinct('position', 'user')
            #  ~Q(application_status__pk = 2) indicates not 'To Apply' statuses in the prod DB.
            top_positions = JobApplication.objects.filter(
                ~Q(application_status=None),
                ~Q(application_status__pk=2),
                apply_date__range=[last_year, today],
                is_deleted=False).values(
                    position_=F('position__job_title')).annotate(
                        count=Count('position')).filter(
                            id__in=distinct_positions).order_by(
                                '-count').order_by('-count')

            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
                months_string.insert(0, d.strftime("%B"))
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                months_string.insert(0, dec.strftime("%B"))
                dec = dec + relativedelta(months=-1)

            item['graph']['xAxis'] = months_string

            if top_positions.count() > 10:
                top_positions = top_positions[:10]

            total = 0
            for position in top_positions:
                serie = {'name': position['position_'], 'type': 'bar'}
                data = [0] * 12
                for j in range(0, 12):
                    count = JobApplication.objects.filter(
                        ~Q(application_status=None),
                        ~Q(application_status__pk=2),
                        position__job_title=position['position_'],
                        apply_date__year=months[j].year,
                        apply_date__month=months[j].month,
                        is_deleted=False,
                        id__in=distinct_positions)
                    data[j] = count.count()
                serie['data'] = data
                item['graph']['series'].append(serie)
                serie['stack'] = 'Company'
                item['list']['data'].append({
                    'id': position['position_'],
                    'value': position['count']
                })
                total += position['count']
            item['list']['total'] = total

        response.append(item)
    return JsonResponse(create_response(data=response), safe=False)
Beispiel #24
0
def detailed(request):
    response = []
    for graph in range(4):
        item = {}
        if graph == 0:
            item['graph'] = {}
            item['graph']['type'] = 'bar'
            item['graph']['series'] = []
            item['graph']['title'] = 'Monthly Applications'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Job Sources'

            system_sources = Source.objects.filter(system=True)
            sources = ['Others']
            for s in system_sources:
                sources.insert(0, s.value)
            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-1)
            months = []
            months_string = []

            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
                months_string.insert(0, d.strftime("%B"))
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                months_string.insert(0, dec.strftime("%B"))
                dec = dec + relativedelta(months=-1)
            for i in sources:
                if i != 'Others':
                    apps = JobApplication.objects.filter(
                        user=request.user,
                        app_source__value=i,
                        apply_date__range=[last_year, today],
                        is_deleted=False)
                    apps_by_months = apps.values(
                        'apply_date__year',
                        'apply_date__month').annotate(count=Count('pk'))
                else:
                    apps = JobApplication.objects.filter(
                        user=request.user,
                        app_source__system=False,
                        apply_date__range=[last_year, today],
                        is_deleted=False)
                    apps_by_months = apps.values(
                        'apply_date__year',
                        'apply_date__month').annotate(count=Count('pk'))
                item['list']['data'].append({'id': i, 'value': apps.count()})
                serie = {'name': i}
                data = [0] * 12
                for j in range(0, 12):
                    count = apps_by_months.filter(
                        apply_date__year=months[j].year,
                        apply_date__month=months[j].month)
                    if len(count) > 0:
                        data[j] = count[0]['count']
                serie['data'] = data
                serie['type'] = "bar"
                serie['stack'] = 'Source'
                item['graph']['series'].append(serie)

            item['list']['data'].sort(key=lambda x: x['value'], reverse=True)
            item['list']['total'] = JobApplication.objects.filter(
                user=request.user,
                apply_date__range=[last_year, today],
                is_deleted=False).count()
            item['graph']['xAxis'] = months_string
        elif graph == 1:
            item['graph'] = {}
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['graph']['title'] = 'Status Change'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Job Statuses'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-1)
            months = []
            months_string = []

            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
                months_string.insert(0, d.strftime("%B"))
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                months_string.insert(0, dec.strftime("%B"))
                dec = dec + relativedelta(months=-1)

            statuses = list(ApplicationStatus.objects.all())
            status_total = ApplicationStatus(value='Total')
            statuses.append(status_total)
            for status in statuses:
                if status.value == 'Total':
                    apps = JobApplication.objects.filter(
                        user=request.user,
                        apply_date__range=[last_year, today],
                        is_deleted=False)
                else:
                    apps = JobApplication.objects.filter(
                        user=request.user,
                        application_status=status,
                        apply_date__range=[last_year, today],
                        is_deleted=False)
                    item['list']['data'].append({
                        'id': status.value.upper(),
                        'value': apps.count()
                    })
                apps = apps.values(
                    'apply_date__year',
                    'apply_date__month').annotate(count=Count('pk'))
                serie = {'name': status.value.upper()}
                data = [0] * 12
                for j in range(0, 12):
                    count = apps.filter(apply_date__year=months[j].year,
                                        apply_date__month=months[j].month)
                    if len(count) > 0:
                        data[j] = count[0]['count']
                serie['data'] = data
                serie['type'] = "line"
                item['graph']['series'].append(serie)
            item['list']['data'].sort(key=lambda x: x['value'], reverse=True)
            item['list']['total'] = JobApplication.objects.filter(
                user=request.user,
                apply_date__range=[last_year, today],
                is_deleted=False).count()
            item['graph']['xAxis'] = months_string
        elif graph == 2:
            item['graph'] = {}
            item['graph']['type'] = 'radar'
            item['graph']['polar'] = []
            item['graph']['series'] = []
            item['graph']['title'] = 'Skill Analysis'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Skills'

            # dummy data
            serie = {'value': [9, 8, 9, 7, 5, 3], 'name': 'Market Demand'}
            item['graph']['series'].append(serie)
            serie = {'value': [10, 8, 5, 7, 3, 2], 'name': 'Your Skills'}
            item['graph']['series'].append(serie)
            indicators = []
            indicator = {'text': 'Java', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'Python', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'R', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'React Native', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'GO', 'max': 10}
            indicators.append(indicator)
            indicator = {'text': 'React', 'max': 10}
            indicators.append(indicator)
            item['graph']['polar'].append({'indicator': indicators})

            item['list']['data'].append({'id': 'GO', 'value': 27})
            item['list']['data'].append({'id': 'Java', 'value': 18})
            item['list']['data'].append({'id': 'React', 'value': 16})
            item['list']['data'].append({'id': 'R', 'value': 14})
            item['list']['data'].append({'id': 'Python', 'value': 12})
            item['list']['data'].append({'id': 'React Native', 'value': 8})

            item['list']['total'] = 32
        elif graph == 3:
            item['graph'] = {}
            item['graph']['type'] = 'bar'
            item['graph']['series'] = []
            item['graph']['title'] = 'Top Companies'
            item['list'] = {}
            item['list']['data'] = []
            item['list']['title'] = 'Top Companies'

            item['graph']['xAxis'] = []

            top_companies = JobApplication.objects.filter(
                ~Q(application_status=None),
                user=request.user,
                is_deleted=False).values(
                    company=F('company_object__company')).annotate(
                        count=Count('company_object')).order_by('-count')
            if top_companies.count() > 10:
                top_companies = top_companies[:10]

            total = 0
            for company in top_companies:
                item['list']['data'].append({
                    'id': company['company'],
                    'value': company['count']
                })
                total += company['count']
            item['list']['total'] = total

            statuses = ApplicationStatus.objects.all()
            for status in statuses:
                item['graph']['xAxis'].append(status.value.upper())
            for company in top_companies:
                serie = {
                    'name': company['company'],
                    'type': "bar",
                    'stack': 'Company'
                }
                data = [0] * statuses.count()
                for idx, status in enumerate(statuses):
                    data[idx] = JobApplication.objects.filter(
                        ~Q(application_status=None),
                        user=request.user,
                        company_object__company=company['company'],
                        application_status=status).count()
                serie['data'] = data
                item['graph']['series'].append(serie)

        response.append(item)
    return JsonResponse(create_response(data=response), safe=False)
Beispiel #25
0
def get_user_google_mails(request):
    mails = GoogleMail.objects.all()
    slist = GoogleMailSerializer(instance=mails, many=True).data
    return JsonResponse(create_response(slist), safe=False)
Beispiel #26
0
def get_linkedin_profile(request):
    result, text = get_profile(request.user)
    if result:
        return JsonResponse(create_response(text), safe=False)
    else:
        return JsonResponse(create_response(None, False, 2))
Beispiel #27
0
def generic(request):
    response = []
    total_jobs_applied = JobApplication.objects.filter(user=request.user,
                                                       is_deleted=False)
    for graph in range(4):
        item = {}
        if graph == 0:
            item['graph'] = {}
            item['graph']['type'] = 'pie'
            item['graph']['legend'] = []
            item['graph']['series'] = []
            item['title'] = 'Phone Screen Rate'
            if total_jobs_applied.count() == 0:
                item['value'] = '0%'
            else:
                item['value'] = str(
                    round(
                        total_jobs_applied.filter(
                            application_status__value='PHONE SCREEN').count() /
                        total_jobs_applied.count() * 100, 2)) + '%'
            item['description'] = '13% INCREASE from last month'
            statuses = total_jobs_applied.filter(~Q(
                application_status=None)).values(
                    'application_status').annotate(count=Count('pk'))
            for status in statuses:
                status_text = ApplicationStatus.objects.get(
                    pk=status['application_status']).value.upper()
                item['graph']['legend'].append(status_text)
                serie = {'name': status_text, 'value': status['count']}
                if status_text == 'PHONE SCREEN':
                    serie['selected'] = True
                item['graph']['series'].append(serie)
        elif graph == 1:
            item['graph'] = {}
            item['graph']['type'] = 'pie'
            item['graph']['legend'] = []
            item['graph']['series'] = []
            item['title'] = 'Onsite Interview Rate'
            if total_jobs_applied.count() == 0:
                item['value'] = '0%'
            else:
                item['value'] = str(
                    round(
                        total_jobs_applied.filter(
                            application_status__value='ONSITE INTERVIEW').
                        count() / total_jobs_applied.count() * 100, 2)) + '%'
            item['description'] = '4% DECREASE from last month'
            statuses = total_jobs_applied.filter(~Q(
                application_status=None)).values(
                    'application_status').annotate(count=Count('pk'))
            for status in statuses:
                status_text = ApplicationStatus.objects.get(
                    pk=status['application_status']).value.upper()
                item['graph']['legend'].append(status_text)
                serie = {'name': status_text, 'value': status['count']}
                if status_text == 'ONSITE INTERVIEW':
                    serie['selected'] = True
                item['graph']['series'].append(serie)
        elif graph == 2:
            item['graph'] = {}
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['title'] = 'Total Applied Jobs'
            item['value'] = total_jobs_applied.count()
            item['description'] = '21% INCREASE from last month'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-2)
            months = []
            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                dec = dec + relativedelta(months=-1)
            apps_by_month = total_jobs_applied.filter(
                apply_date__range=[last_year, today]).values(
                    'apply_date__year',
                    'apply_date__month').annotate(count=Count('pk'))

            serie = {'name': item['title'], 'type': 'line'}
            data = [0] * 12
            for j in range(0, 12):
                count = apps_by_month.filter(apply_date__year=months[j].year,
                                             apply_date__month=months[j].month)
                if count.count() > 0:
                    data[j] = count[0]['count']
            serie['data'] = data
            item['graph']['series'].append(serie)
        elif graph == 3:
            item['graph'] = {}
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['title'] = 'Total Rejected Jobs'
            item['value'] = str(
                total_jobs_applied.filter(
                    is_rejected=True).count()) + '/' + str(
                        total_jobs_applied.count())
            item['description'] = '3% DECREASE from last month'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-2)
            months = []
            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                dec = dec + relativedelta(months=-1)
            apps_by_month = total_jobs_applied.filter(
                apply_date__range=[last_year, today], is_rejected=True).values(
                    'apply_date__year',
                    'apply_date__month').annotate(count=Count('pk'))

            serie = {'name': item['title'], 'type': 'line'}
            data = [0] * 12
            for j in range(0, 12):
                count = apps_by_month.filter(
                    rejected_date__year=months[j].year,
                    rejected_date__month=months[j].month)
                if count.count() > 0:
                    data[j] = count[0]['count']
            serie['data'] = data
            item['graph']['series'].append(serie)
        response.append(item)
    return JsonResponse(create_response(data=response), safe=False)
Beispiel #28
0
def home_page(request):
    user_profile = request.user
    if user_profile.user_type.name == 'Alumni' or user_profile.user_type.name == 'Career Service':
        body = request.data
        if 'type' in body:
            type = body['type']
        if request.method == "GET":
            if HomePage.objects.filter(college=user_profile.college).exists():
                home_page = HomePage.objects.get(college=user_profile.college)
            elif HomePage.objects.filter(college=None).exists():
                home_page = HomePage.objects.get(college=None)
            else:
                return JsonResponse(create_response(
                    data=None,
                    success=False,
                    error_code=ResponseCodes.record_not_found),
                                    safe=False)
            serialized_home_page = HomePageSerializer(
                instance=home_page,
                many=False,
            ).data
            return JsonResponse(create_response(data=serialized_home_page),
                                safe=False)
        elif request.method == "DELETE" and user_profile.user_type.name == 'Career Service':
            home_page = HomePage.objects.get(college=user_profile.college)
            if type == 'header_banner':
                header_banner = home_page.header_banners
                del header_banner[int(body['order'])]
                home_page.header_banners = header_banner
            elif type == 'additional_banner':
                additional_banner = home_page.additional_banners
                del additional_banner[int(body['order'])]
                home_page.additional_banners = additional_banner
            elif type == 'social_media_account':
                social_media_account = home_page.social_media_accounts
                del social_media_account[int(body['order'])]
                home_page.social_media_accounts = social_media_account
            home_page.save()
            return JsonResponse(create_response(data=None), safe=False)
        elif request.method == "POST" and user_profile.user_type.name == 'Career Service':
            home_page = HomePage.objects.get(college=user_profile.college)
            if type == 'header_banner':
                header_banner = {}
                if body['link'].startswith('http'):
                    header_banner['internal_link'] = False
                else:
                    header_banner['internal_link'] = True
                header_banner['link'] = body['link']

                file = body['image']
                ext = file.name.split('.')[-1]
                filename = "%s.%s" % (uuid.uuid4(), ext)
                save_path = os.path.join(settings.MEDIA_ROOT, filename)
                path = default_storage.save(save_path, file)
                header_banner['image'] = settings.MEDIA_URL + filename

                header_banners = home_page.header_banners
                header_banners.append(header_banner)
                home_page.header_banners = header_banners
            elif type == 'additional_banner':
                additional_banner = {}
                if body['link'].startswith('http'):
                    additional_banner['internal_link'] = False
                else:
                    additional_banner['internal_link'] = True
                additional_banner['link'] = body['link']

                file = body['image']
                ext = file.name.split('.')[-1]
                filename = "%s.%s" % (uuid.uuid4(), ext)
                save_path = os.path.join(settings.MEDIA_ROOT, filename)
                path = default_storage.save(save_path, file)
                additional_banner['image'] = settings.MEDIA_URL + filename

                additional_banners = home_page.additional_banners
                additional_banners.append(additional_banner)
                home_page.additional_banners = additional_banners
            elif type == 'social_media_account':
                social_media_account = {}
                social_media_account['link'] = body['link']

                file = body['image']
                ext = file.name.split('.')[-1]
                filename = "%s.%s" % (uuid.uuid4(), ext)
                save_path = os.path.join(settings.MEDIA_ROOT, filename)
                path = default_storage.save(save_path, file)
                social_media_account['icon'] = settings.MEDIA_URL + filename

                social_media_accounts = home_page.social_media_accounts
                social_media_accounts.append(social_media_account)
                home_page.social_media_accounts = social_media_accounts
            home_page.save()
            return JsonResponse(create_response(
                data=HomePageSerializer(instance=home_page, many=False).data),
                                safe=False)
        elif request.method == "PUT" and user_profile.user_type.name == 'Career Service':
            home_page = HomePage.objects.get(college=user_profile.college)
            if type == 'header_banner':
                header_banner = home_page.header_banners[int(body['order'])]
                if 'link' in body:
                    if body['link'].startswith('http'):
                        header_banner['internal_link'] = False
                    else:
                        header_banner['internal_link'] = True
                    header_banner['link'] = body['link']
                if 'image' in body:
                    file = body['image']
                    ext = file.name.split('.')[-1]
                    filename = "%s.%s" % (uuid.uuid4(), ext)
                    save_path = os.path.join(settings.MEDIA_ROOT, filename)
                    path = default_storage.save(save_path, file)
                    header_banner['image'] = settings.MEDIA_URL + filename

                header_banners = home_page.header_banners
                header_banners[int(body['order'])] = header_banner
                home_page.header_banners = header_banners
            elif type == 'additional_banner':
                additional_banner = home_page.additional_banners[int(
                    body['order'])]
                if 'link' in body:
                    if body['link'].startswith('http'):
                        additional_banner['internal_link'] = False
                    else:
                        additional_banner['internal_link'] = True
                    additional_banner['link'] = body['link']
                if 'image' in body:
                    file = body['image']
                    ext = file.name.split('.')[-1]
                    filename = "%s.%s" % (uuid.uuid4(), ext)
                    save_path = os.path.join(settings.MEDIA_ROOT, filename)
                    path = default_storage.save(save_path, file)
                    additional_banner['image'] = settings.MEDIA_URL + filename

                additional_banners = home_page.additional_banners
                additional_banners[int(body['order'])] = additional_banner
                home_page.additional_banners = additional_banners
            elif type == 'social_media_account':
                social_media_account = home_page.social_media_accounts[int(
                    body['order'])]
                if 'link' in body:
                    social_media_account['link'] = body['link']
                if 'image' in body:
                    file = body['image']
                    ext = file.name.split('.')[-1]
                    filename = "%s.%s" % (uuid.uuid4(), ext)
                    save_path = os.path.join(settings.MEDIA_ROOT, filename)
                    path = default_storage.save(save_path, file)
                    social_media_account[
                        'icon'] = settings.MEDIA_URL + filename

                social_media_accounts = home_page.social_media_accounts
                social_media_accounts[int(
                    body['order'])] = social_media_account
                home_page.social_media_accounts = social_media_accounts
            home_page.save()
            return JsonResponse(create_response(
                data=HomePageSerializer(instance=home_page, many=False).data),
                                safe=False)
    return JsonResponse(create_response(
        data=None, success=False, error_code=ResponseCodes.not_supported_user),
                        safe=False)
Beispiel #29
0
def agg_generic(request):
    response = []
    user_profile = request.user
    User = get_user_model()
    filter_by_college = False
    public = get_boolean_from_request(request, 'public')
    if user_profile.user_type >= int(User.UserTypes.student) and not public:
        college_users = get_user_model().objects.filter(id__in=[
            p.id for p in User.objects.filter(college=user_profile.college,
                                              is_demo=False)
        ])
        filter_by_college = True
        total_jobs_applied = JobApplication.objects.filter(
            user__in=college_users, is_deleted=False)
    else:
        if user_profile.user_type < int(User.UserTypes.student) and not public:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.not_supported_user),
                                safe=False)
        total_jobs_applied = JobApplication.objects.filter(is_deleted=False)
    for graph in range(4):
        item = dict(graph={})
        if graph == 0:
            item['graph']['type'] = 'pie'
            item['graph']['legend'] = []
            item['graph']['series'] = []
            item['title'] = 'Phone Screen Rate'
            if total_jobs_applied.count() == 0:
                item['value'] = '0%'
            else:
                item['value'] = str(
                    round(
                        total_jobs_applied.filter(
                            application_status__value='PHONE SCREEN').count() /
                        total_jobs_applied.count() * 100, 2)) + '%'
            item['description'] = '13% INCREASE from last month'
            statuses = total_jobs_applied.filter(~Q(
                application_status=None)).values(
                    'application_status').annotate(count=Count('pk'))
            for status in statuses:
                status_text = ApplicationStatus.objects.get(
                    pk=status['application_status']).value.upper()
                item['graph']['legend'].append(status_text)
                serie = {'name': status_text, 'value': status['count']}
                if status_text == 'PHONE SCREEN':
                    serie['selected'] = True
                item['graph']['series'].append(serie)
        elif graph == 1:
            item['graph']['type'] = 'pie'
            item['graph']['legend'] = []
            item['graph']['series'] = []
            item['title'] = 'Onsite Interview Rate'
            if total_jobs_applied.count() == 0:
                item['value'] = '0%'
            else:
                item['value'] = str(
                    round(
                        total_jobs_applied.filter(
                            application_status__value='ONSITE INTERVIEW').
                        count() / total_jobs_applied.count() * 100, 2)) + '%'
            item['description'] = '4% DECREASE from last month'
            statuses = total_jobs_applied.filter(~Q(
                application_status=None)).values(
                    'application_status').annotate(count=Count('pk'))
            for status in statuses:
                status_text = ApplicationStatus.objects.get(
                    pk=status['application_status']).value.upper()
                item['graph']['legend'].append(status_text)
                serie = {'name': status_text, 'value': status['count']}
                if status_text == 'ONSITE INTERVIEW':
                    serie['selected'] = True
                item['graph']['series'].append(serie)
        elif graph == 2:
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['title'] = 'Total Applied Jobs'
            item['value'] = total_jobs_applied.count()
            item['description'] = '21% INCREASE from last month'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-2)
            months = []
            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                dec = dec + relativedelta(months=-1)
            apps_by_month = total_jobs_applied.filter(
                apply_date__range=[last_year, today]).values(
                    'apply_date__year',
                    'apply_date__month').annotate(count=Count('pk'))

            serie = {'name': item['title'], 'type': 'line'}
            data = [0] * 12
            for j in range(0, 12):
                count = apps_by_month.filter(apply_date__year=months[j].year,
                                             apply_date__month=months[j].month)
                if count.count() > 0:
                    data[j] = count[0]['count']
            serie['data'] = data
            item['graph']['series'].append(serie)
        elif graph == 3:
            item['graph']['type'] = 'line'
            item['graph']['series'] = []
            item['title'] = 'Total Users'
            User = get_user_model()
            if filter_by_college:
                total_user = User.objects.filter(id__in=[
                    p.id
                    for p in User.objects.filter(college=user_profile.college,
                                                 is_demo=False)
                ])
            else:
                total_user = User.objects.filter(is_demo=False)
            total_user_count = total_user.count()
            item['value'] = total_user_count
            total_application = total_jobs_applied.count()
            total_average = total_application / total_user_count
            item['description'] = 'Average ' + str(
                round(total_average,
                      2)) + ' & ' + 'Total ' + str(total_application) + ' Jobs'

            today = datetime.date.today() + relativedelta(days=+1)
            last_year = datetime.date.today() + relativedelta(years=-2)
            months = []
            for i in range(0, today.month):
                d = today + relativedelta(months=-1 * i)
                months.insert(0, d)
            dec = today + relativedelta(months=-1 * today.month)
            while len(months) != 12:
                months.insert(0, dec)
                dec = dec + relativedelta(months=-1)
            apps_by_month = total_user.filter(
                date_joined__range=[last_year, today]).values(
                    'date_joined__year',
                    'date_joined__month').annotate(count=Count('pk'))

            serie = {'name': item['title'], 'type': 'line'}
            data = [0] * 12
            for j in range(0, 12):
                count = apps_by_month.filter(
                    date_joined__year=months[j].year,
                    date_joined__month=months[j].month)
                if count.count() > 0:
                    if j == 0:
                        data[j] = count[0]['count']
                    else:
                        data[j] = data[j - 1] + count[0]['count']
            serie['data'] = data
            item['graph']['series'].append(serie)
        response.append(item)
    return JsonResponse(create_response(data=response), safe=False)
Beispiel #30
0
def coaches(request):
    user_profile = request.user
    body = request.data
    if request.method == "GET":
        if not request.user.user_type.coach_listing_enabled:
            return JsonResponse(create_response(
                data=None,
                success=False,
                error_code=ResponseCodes.not_supported_user),
                                safe=False)
        college_coaches = CollegeCoach.objects.filter(
            college=request.user.college)
        paginator = pagination.CustomPagination()
        college_coaches = paginator.paginate_queryset(college_coaches, request)
        serialized_college_coaches = CollegeCoachSerializer(
            instance=college_coaches, many=True).data
        return JsonResponse(create_response(data=serialized_college_coaches,
                                            paginator=paginator),
                            safe=False)
    elif user_profile.user_type.name == 'Career Service':
        if request.method == "DELETE":
            coach = HomePageVideo.objects.get(pk=body['coach_id'])
            coach.delete()
            return JsonResponse(create_response(data=None), safe=False)
        elif request.method == "POST" and user_profile.user_type.name == 'Career Service':
            coach = CollegeCoach()
            coach.first_name = body['first_name']
            coach.last_name = body['last_name']
            coach.title = body['title']
            if 'email' in body:
                coach.email = body['email']
            coach.content = body['content']
            coach.calendar_link = body['calendar_link']
            if 'online_conference_link' in body:
                coach.online_conference_link = body['online_conference_link']
            coach.college = user_profile.college

            if 'is_publish' in body:
                coach.is_publish = get_boolean_from_request(
                    request, 'is_publish', 'POST')
            else:
                coach.is_publish = True

            file = body['profile_photo']
            ext = file.name.split('.')[-1]
            filename = "%s.%s" % (uuid.uuid4(), ext)
            coach.profile_photo.save(filename, file, save=True)

            file = body['summary_photo']
            ext = file.name.split('.')[-1]
            filename = "%s.%s" % (uuid.uuid4(), ext)
            coach.summary_photo.save(filename, file, save=True)

            coach.save()
            return JsonResponse(create_response(
                data=CollegeCoachSerializer(instance=coach, many=False).data),
                                safe=False)
        elif request.method == "PUT" and user_profile.user_type.name == 'Career Service':
            coach = CollegeCoach.objects.get(pk=body['coach_id'])
            if 'first_name' in body:
                coach.first_name = body['first_name']
            if 'last_name' in body:
                coach.last_name = body['last_name']
            if 'title' in body:
                coach.title = body['title']
            if 'email' in body:
                coach.email = body['email']
            if 'content' in body:
                coach.content = body['content']
            if 'calendar_link' in body:
                coach.calendar_link = body['calendar_link']
            if 'online_conference_link' in body:
                coach.online_conference_link = body['online_conference_link']
            if 'profile_photo' in body:
                file = body['profile_photo']
                ext = file.name.split('.')[-1]
                filename = "%s.%s" % (uuid.uuid4(), ext)
                coach.profile_photo.save(filename, file, save=True)
            if 'summary_photo' in body:
                file = body['summary_photo']
                ext = file.name.split('.')[-1]
                filename = "%s.%s" % (uuid.uuid4(), ext)
                coach.summary_photo.save(filename, file, save=True)
            if 'is_publish' in body:
                coach.is_publish = get_boolean_from_request(
                    request, 'is_publish', 'POST')
            coach.save()
            return JsonResponse(create_response(
                data=CollegeCoachSerializer(instance=coach, many=False).data),
                                safe=False)
    return JsonResponse(create_response(
        data=None, success=False, error_code=ResponseCodes.not_supported_user),
                        safe=False)