Beispiel #1
0
def rolling_deadline_end(request, id, extra_context=None):
    if request.method == "POST":
        try:
            event = Event.objects.get(pk=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        else:
            if not event.is_rolling_deadline():
                raise Http403(
                    'You cannot end anything other than a rolling deadline.')
            if is_recruiter(event.owner):
                if not is_recruiter(
                        request.user
                ) or request.user.recruiter.employer != event.owner.recruiter.employer:
                    raise Http403(
                        'You are not allowed to end this rolling deadline.')
            elif is_campus_org(event.owner):
                if not is_campus_org(
                        request.user
                ) or request.user.campusorg != event.owner.campusorg:
                    raise Http403(
                        'You are not allowed to end this rolling deadline.')
            event.end_datetime = datetime.now() - timedelta(minutes=1)
            event.save()
            return HttpResponse()
    else:
        try:
            event = Event.objects.get(id=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        context = {'event': event}
        context.update(extra_context or {})
        return context
Beispiel #2
0
def employer_new(request, form_class=CreateEmployerForm, extra_context=None):
    if not (request.user.is_authenticated() and hasattr(request.user, "campusorg") or hasattr(request.user, "student")):
        raise Http403("You must be logged in.")
    if request.method == 'POST':
        form = form_class(data=request.POST)
        if form.is_valid():
            new_employer = form.save()
            recipients = [mail_tuple[1] for mail_tuple in s.MANAGERS]
            
            context = Context({'first_name':request.user.first_name,
                               'last_name': request.user.last_name,
                               'email':request.user.email,
                               'new_employer':new_employer,
                               'new_employer_industries':" ".join(map(lambda x: x.name, new_employer.industries.all()))})
            context.update(get_basic_email_context())
             
            body = render_to_string('employer_new_email_body.txt', context)
                                    
            subject = ''.join(render_to_string('email_admin_subject.txt', {
                'message': "New Employer: %s" % new_employer 
            }, context).splitlines())
                            
            send_email(subject, body, recipients)
            
            data = {"name": new_employer.name, "id": new_employer.id}
        else:
            data = {'errors': form.errors }
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")
    else:
        form = form_class()
    context = {'form': form }
    context.update(extra_context or {}) 
    return context
Beispiel #3
0
def get_location_suggestions(request):
    if not request.GET.has_key('query'):
        raise Http403("Request GET is missing the query.")
    num_of_suggestions = 7
    query = request.GET['query']
    suggestions = []
    if len(query.split("-")) > 1 and query.split(
            "-")[1] and Location.objects.filter(
                building_num=query.split("-")[0]).exists():
        locations = Location.objects.filter(
            building_num__iexact=query.split("-")[0])[:num_of_suggestions]
        for l in locations:
            suggestions.append({
                'name': "%s" % query,
                'lat': l.latitude,
                'lng': l.longitude
            })
    else:
        locations = SearchQuerySet().models(Location).filter(
            reduce(operator.__and__, [
                SQ(text=word.strip())
                for word in request.GET['query'].strip().split(' ')
            ]))[:num_of_suggestions]
        for l in locations:
            suggestions.append({
                'name': "%s" % str(l.object),
                'lat': l.object.latitude,
                'lng': l.object.longitude
            })
    context = {'suggestions': suggestions}
    return context
Beispiel #4
0
def checkout(request, plan, form_class=CheckoutForm, extra_context=None):
    context = {}
    customer = request.META.get('customer', None)

    try:
        plan_uids = map(lambda x: x[1], s.SUBSCRIPTION_UIDS[plan].values()) 
    except KeyError as e:
        raise Http403("You cannot upgrade to the %s plan." % plan)
    
    if customer.subscription and customer.subscription.plan.id in plan_uids:
        return redirect(reverse("subscription_change"))
    
    if request.method == 'POST':
        form = form_class(plan, None, request.POST)
        if form.is_valid():
            token = form.cleaned_data['stripe_token']
            card = None
            if token:
                card = token
            billing_cycle = form.cleaned_data['billing_cycle']
            customer.update_subscription(plan=s.SUBSCRIPTION_UIDS[plan][billing_cycle][1], card=card)
            return redirect("%s%s" % (reverse('employer_account'), "?msg=upgraded_to_premium&tab=subscription"))
    else:
        form = form_class(plan, None)
        context['customer'] = customer
    context['form'] = form
    context.update(extra_context or {})
    return context
Beispiel #5
0
def receipt_view(request, charge_id):
    customer = request.META.get('customer', None)
    employer = request.user.recruiter.employer
    
    try:
        charge_ids = map(lambda x: x.id, stripe.Charge.all(count=100, customer = customer.id).data)
    except InvalidRequestError as e:
        raise Http404(e)
    
    try:
        charge = stripe.Charge.retrieve(id=charge_id)
    except InvalidRequestError as e:
        raise Http404(e)
            
    if not charge.id in charge_ids:
        raise Http403("You do not have permission to view the receipt for charge %s." % charge_id)
    try:
        invoice = stripe.Invoice.retrieve(charge.invoice)
    except InvalidRequestError as e:
        raise Http404(e)
    pdf_path = get_or_create_receipt_pdf(charge, invoice, employer.name)
    pdf_name = pdf_path.split("/")[-1]
    
    mimetype = "application/pdf"
    response = HttpResponse(file(pdf_path, "rb").read(), mimetype=mimetype)
    response["Content-Disposition"] = 'inline; filename="%s"' % pdf_name
    return response
Beispiel #6
0
def employer_recruiter_new(request, form_class=RecruiterForm, extra_context=None):
    employer = request.user.recruiter.employer
    has_at_least_premium = request.META['has_at_least_premium']
    recruiter_num = len(Recruiter.objects.filter(employer=employer))
    if not has_at_least_premium and recruiter_num >= s.MAX_USERS_FOR_BASIC_USERS:
        raise Http403("In order to create more than %d accounts for your firm, you must subscribe to a paid plan." % (s.MAX_USERS_FOR_BASIC_USERS))
    if request.method == 'POST':
        form = form_class(data=request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            if len(user.email)>30:
                username = user.email.split("@")[0]
                if len(username) > 30:
                    username = username[:30]
            else:
                username = user.email
            user.username = username
            user.save()
            form.save_m2m()
            Recruiter.objects.create(user = user, employer = request.user.recruiter.employer)
            data = {}
        else:
            data = {'errors': form.errors }
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")
    else:
        form = form_class()
    context = {'form': form }
    context.update(extra_context or {}) 
    return context
Beispiel #7
0
def specific_student_resume(request, student_id):
    was_limited = getattr(request, 'limited', False)
    if was_limited:
        raise Http403("You have exceeded the resume viewing per minute limit. " +
                      "Please wait before trying again and consider using the resume book tool for collecting resumes in batches.")
    try:
        student = Student.objects.get(id=student_id)
    except Student.DoesNotExist:
        raise Http404("A student with the id %s does not exist." % student_id)
    employer = request.user.recruiter.employer
    if not student in get_unlocked_students(employer, request.META['has_at_least_premium']):
        raise Http403("You have not unlocked this student yet and thus can't view their resume. To unlock him/her either upgrade your subscription or have him/her RSVP to or attend one of your events.")
    resume = student.resume.read()
    response = HttpResponse(resume, mimetype='application/pdf')
    response['Content-Disposition'] = 'inline; filename=%s_%s_%s.pdf' % (student.id, student.user.last_name.lower(), student.user.first_name.lower())
    return response
Beispiel #8
0
def event_edit(request, id=None, extra_context=None):
    try:
        event = Event.objects.get(pk=id)
    except Event.DoesNotExist:
        raise Http404("Event with id '%s' does not exist." % id)

    context = {'event': event}
    if not admin_of_event(event, request.user):
        raise Http403('You are not allowed to edit this event.')
    if is_recruiter(event.owner):
        form_class = EventForm
    elif is_campus_org(event.owner):
        context['max_industries'] = s.EP_MAX_INDUSTRIES
        context['attending_employers'] = event.attending_employers
        form_class = CampusOrgEventForm
    if request.method == 'POST':
        form = form_class(request.POST, instance=event)
        if form.is_valid():
            event = form.save(commit=False)
            event.edits.add(Edit.objects.create(user=request.user))
            for employer in event.attending_employers.all():
                event.previously_attending_employers.add(employer)
            event.save()
            form.save_m2m()
            # Update index
            event.save()
            notify_about_event(event, "new_event", [
                e for e in list(event.attending_employers.all())
                if e not in list(event.previously_attending_employers.all())
            ])
            return HttpResponseRedirect(
                reverse('event_page',
                        kwargs={
                            'id': event.id,
                            'slug': event.slug
                        }))
    else:
        form = form_class(instance=event)
    context['edit'] = True
    context['hours'] = map(lambda x, y: str(x) + y,
                           [12] + range(1, 13) + range(1, 12),
                           ['am'] * 12 + ['pm'] * 12)
    context['form'] = form
    context['today'] = datetime.now().strftime('%m/%d/%Y')
    if event.type.name == "Hard Deadline":
        context['event_scheduler_date'] = event.end_datetime.strftime(
            '%m/%d/%Y')
    elif event.type.name == "Rolling Deadline":
        context['event_scheduler_date'] = datetime.now().strftime('%m/%d/%Y')
    else:
        context['event_scheduler_date'] = event.start_datetime.strftime(
            '%m/%d/%Y')
    context.update(extra_context or {})
    return context
Beispiel #9
0
def employer_account_delete(request):
    if request.user.recruiter.employer.recruiter_set.exclude(id=request.user.recruiter.id).exists():
        if request.method == "POST":
            for sk in request.user.sessionkey_set.all():
                Session.objects.filter(session_key=sk.session_key).delete()
            request.user.sessionkey_set.all().delete()
            request.user.recruiter.delete()
            request.user.delete()
            return HttpResponse()
        else:
            context = {}
            return context
    else:
        raise Http403("You cannot delete your account when you are the only recruiter with credentials for Umeqo.") 
Beispiel #10
0
def event_rsvp_message(request, extra_context=None):
    if not request.GET.has_key("event_id"):
        raise Http403("Request GET is missing the event_id.")
    id = request.GET['event_id']
    try:
        event = Event.objects.get(id=id)
    except Event.DoesNotExist:
        raise Http404("Event with id '%s' does not exist." % id)
    context = {}
    if event.rsvp_message:
        context['event'] = event
        if is_campus_org(event.owner):
            context['is_campus_org_event'] = True
        return context
    return HttpResponse()
Beispiel #11
0
def event_archive(request, id, extra_context=None):
    try:
        event = Event.objects.get(id=id)
    except Event.DoesNotExist:
        raise Http404("Event with id '%s' does not exist." % id)
    else:
        if not admin_of_event(event, request.user):
            raise Http403('You are not allowed to arhive this event.')
        event.archived = True
        event.save()
        data = {}
        if event.is_deadline():
            data['type'] = "deadline"
        else:
            data['type'] = "event"
        return HttpResponse(simplejson.dumps(data),
                            mimetype="application/json")
Beispiel #12
0
def event_cancel(request, id, extra_context=None):
    if request.method == "POST":
        try:
            event = Event.objects.get(id=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        else:
            if not admin_of_event(event, request.user):
                raise Http403('You are not allowed to delete this event.')
            event.cancelled = True

            # Notify RSVPS.
            rsvps = map(lambda n: n.student.user,
                        event.rsvp_set.filter(attending=True))
            employers = event.attending_employers.all()
            has_word = "has" if len(employers) == 1 else "have"
            employer_names = english_join(map(lambda n: n.name, employers))
            notification.send(
                rsvps, 'cancelled_event', {
                    'employer_names': employer_names,
                    'has_word': has_word,
                    'event': event
                })

            event.save()

            data = {}
            if event.is_deadline():
                data['type'] = "deadline"
            else:
                data['type'] = "event"
            return HttpResponse(simplejson.dumps(data),
                                mimetype="application/json")
    else:
        try:
            event = Event.objects.get(id=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        context = {'event': event}
        context.update(extra_context or {})
        return context
Beispiel #13
0
def employer_resume_book_add_students(request):
    if not request.POST.has_key('student_ids'):
        raise Http400("Request POST is missing the student_ids.")
    try:
        resume_book = ResumeBook.objects.get(recruiter = request.user.recruiter, delivered=False)
        if len(resume_book.students.visible()) >= s.RESUME_BOOK_CAPACITY:
            raise Http403("You already have the max number (%d) of allowed students in you resumebook!" % (s.RESUME_BOOK_CAPACITY))
    except ResumeBook.DoesNotExist:
        resume_book = ResumeBook.objects.create(recruiter = request.user.recruiter)
    employer = request.user.recruiter.employer
    unlocked_students = get_unlocked_students(employer, request.META['has_at_least_premium'])
    if request.POST['student_ids']:
        for id in request.POST['student_ids'].split('~'):
            student = Student.objects.get(id=id)
            if student in unlocked_students:
                if student not in resume_book.students.visible():
                    resume_book.students.add(student)
                if request.user.recruiter.employer.name != "Umeqo":
                    student.studentstatistics.add_to_resumebook_count += 1
                    student.studentstatistics.save()
    return HttpResponse()
Beispiel #14
0
def event_rsvp(request, event_id):
    try:
        event = Event.objects.get(pk=event_id)
    except:
        raise Http404("Event with id '%s' does not exist." % event_id)
    else:
        # if method is GET then get a list of RSVPed students
        if request.method == 'GET' and is_campus_org(
                request.user) or is_recruiter(request.user):
            data = map(
                lambda n: {
                    'id': n.student.id,
                    'email': n.student.user.email
                }, event.rsvp_set.all())
            return HttpResponse(simplejson.dumps(data),
                                mimetype="application/json")
        # if POST then record student's RSVP
        elif request.method == 'POST' and is_student(request.user):
            isAttending = request.POST.get('attending', 'true')
            isAttending = True if isAttending == 'true' else False
            rsvp, created = RSVP.objects.get_or_create(
                student=request.user.student, event=event)
            rsvp.attending = isAttending
            rsvp.save()
            if isAttending:
                DroppedResume.objects.get_or_create(
                    event=event, student=request.user.student)
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(
                    reverse('event_page',
                            kwargs={
                                'id': id,
                                'slug': event.slug
                            }))
        else:
            raise Http403("You do not have access to this view.")
Beispiel #15
0
def employer_resume_book_toggle_student(request):
    if not request.POST.has_key('student_id'):
        raise Http400("Request POST is missing the student_id.")
    student = Student.objects.get(id=request.POST['student_id'])
    try:
        resume_book = ResumeBook.objects.get(recruiter = request.user.recruiter, delivered=False)
    except ResumeBook.DoesNotExist:
        resume_book = ResumeBook.objects.create(recruiter = request.user.recruiter)
    data = {}
    if student in resume_book.students.visible():
        resume_book.students.remove(student)
        data['action'] = employer_enums.REMOVED
    else:
        employer = request.user.recruiter.employer
        if student in get_unlocked_students(employer, request.META['has_at_least_premium']):
            if len(resume_book.students.visible()) >= s.RESUME_BOOK_CAPACITY:
                raise Http403("You already have the max number (%d) of allowed students in you resumebook!" % (s.RESUME_BOOK_CAPACITY))
            resume_book.students.add(student)
            if not request.user.recruiter.employer.name != "Umeqo":
                student.studentstatistics.add_to_resumebook_count += 1
                student.studentstatistics.save()
            data['action'] = employer_enums.ADDED
    return HttpResponse(simplejson.dumps(data), mimetype="application/json")
Beispiel #16
0
 def __call__(self, request, *args, **kwargs):
     if not request.META['has_at_least_premium']:
         raise Http403(
             "You need to have a Umeqo Premium subscription to perform this action."
         )
     return self.orig_func(request, *args, **kwargs)
Beispiel #17
0
def event_page(request, id, slug, extra_context=None):
    if is_student(request.user) and not request.user.student.profile_created:
        return redirect('student_profile')
    try:
        event = Event.objects.get(pk=id)
    except:
        raise Http404("Event with id '%s' does not exist." % id)
    if not event.is_public:
        if not request.user.is_authenticated():
            raise Http403(
                "This event is private. You do not have permission to view it."
            )
        elif is_campus_org(request.user):
            if request.user != event.owner:
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )
        elif is_recruiter(request.user):
            if request.user != event.owner and request.user.recruiter.employer not in event.attending_employers.all(
            ):
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )
        elif is_student(request.user):
            try:
                Invitee.objects.get(event=event, student=request.user.student)
            except:
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )

    current_site = Site.objects.get(id=s.SITE_ID)

    page_url = 'http://' + current_site.domain + event.get_absolute_url()
    #google_description is the description + stuff to link back to umeqo
    google_description = event.description + '\n\nRSVP and more at %s' % page_url

    context = {
        'page_url': page_url,
        'DOMAIN': current_site.domain,
        'current_site': "http://" + current_site.domain,
        'google_description': google_description
    }

    if len(event.audience.all()) > 0:
        context['audience'] = event.audience.all()

    if is_campus_org(event.owner):
        context['campus_org_event'] = True
        context['attending_employers'] = event.attending_employers
        if is_campus_org(request.user):
            context['can_edit'] = (event.owner == request.user)
            context['show_admin'] = (event.owner == request.user)
            context['recruiters_with_access'] = map(
                lambda x: {
                    'name': "%s %s" % (x.first_name, x.last_name),
                    'email': x.email
                },
                User.objects.filter(
                    recruiter__employer__in=event.attending_employers.all()).
                order_by("first_name"))
        elif is_recruiter(request.user):
            context[
                'show_admin'] = request.user.recruiter.employer in event.attending_employers.all(
                )
    elif is_recruiter(event.owner):
        if is_recruiter(request.user):
            context[
                'can_edit'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all(
                )
            context[
                'show_admin'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all(
                )

    if context.has_key('show_admin'):
        attendees = get_attendees(event)
        rsvps = get_rsvps(event)
        context['invitees'] = get_invitees(event)

        if event.is_drop:
            dropped_resumes = get_dropped_resumes(event)
        else:
            dropped_resumes = []

        if not event.is_public:
            no_rsvps = get_no_rsvps(event)
        else:
            no_rsvps = []

        context.update({
            'rsvps': rsvps,
            'no_rsvps': no_rsvps,
            'dropped_resumes': dropped_resumes,
            'attendees': attendees
        })

    # Increase the view count if we're not admin, a campus org or a recruiter (aka for now just student & anonymous)
    if not is_campus_org(request.user) and not is_recruiter(
            request.user) and not request.user.is_staff:
        event.view_count += 1
        event.save()

    if is_student(request.user):
        responded, attending, dropped_resume, attended, event = event_map(
            event, request.user)
        context['responded'] = responded
        context['attending'] = attending
        context['dropped_resume'] = dropped_resume
        context['attended'] = attended
    else:
        context['email_delivery_type'] = core_enums.EMAIL
    context['event'] = event
    context.update(extra_context or {})
    return context
Beispiel #18
0
def event_upload_recruiters_list(request,
                                 form_class=EventUploadRecruitersForm,
                                 extra_context=None):
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        data = {}
        if form.is_valid():
            event_id = form.cleaned_data.get('event_id', '')

            try:
                event = Event.objects.get(id=event_id)
            except Event.DoesNotExist:
                raise Http404("The event with event id %s does not exist" %
                              event_id)

            if request.user != event.owner:
                raise Http403(
                    "You must be the event owner in order to perform this action."
                )

            open_csv_file = csv.DictReader(request.FILES['csv_file'])

            for i, fieldname in enumerate(open_csv_file.fieldnames):
                open_csv_file.fieldnames[i] = fieldname.lower()

            recipients = [mail_tuple[1] for mail_tuple in s.MANAGERS]
            context = Context({})
            context.update(get_basic_email_context())

            event.attending_employers.clear()

            def send_event_company_representative_access_instructions():
                context['event'] = event

                text_body = render_to_string(
                    'recruiter_event_participant_access_instructions.txt',
                    context)
                html_body = render_to_string(
                    'recruiter_event_participant_access_instructions.html',
                    context)

                subject = ''.join(
                    render_to_string('email_subject.txt', {
                        'message':
                        "%s Student Browsing Instructions" % event.name
                    }, context).splitlines())

                send_email(subject, text_body, recipients, html_body)

            for row in open_csv_file:
                email = row.get('email', '')
                user = None
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    password = User.objects.make_random_password()
                    email = row['email'].lower()
                    user = User.objects.create(
                        first_name=row['first name'],
                        last_name=row['last name'],
                        email=email,
                        username=email,
                    )
                    user.set_password(password)
                    user.save()
                    user.userattributes.is_verified = True
                    user.userattributes.save()
                    employer, created = Employer.objects.get_or_create(
                        name=row['employer'])
                    if created:
                        recipients = [
                            mail_tuple[1] for mail_tuple in s.MANAGERS
                        ]
                        context = Context({
                            'first_name': request.user.first_name,
                            'last_name': request.user.last_name,
                            'email': request.user.email,
                            'new_employer': employer
                        })
                        context.update(get_basic_email_context())

                        body = render_to_string('employer_new_email_body.txt',
                                                context)

                        subject = ''.join(
                            render_to_string(
                                'email_admin_subject.txt', {
                                    'message': "New Employer: %s" % employer
                                }, context).splitlines())

                        send_email(subject, body, recipients)
                    Recruiter.objects.create(employer=employer, user=user)
                    event.attending_employers.add(employer)

                    recipients = [user.email]
                    context.update({
                        "first_name": user.first_name,
                        "email": user.email,
                        "username": user.email,
                        "password": password,
                        "has_account": False,
                    })

                    send_event_company_representative_access_instructions()

                else:
                    if is_recruiter(user):
                        if not user.recruiter.employer in event.attending_employers.all(
                        ):
                            employer = user.recruiter.employer
                            event.attending_employers.add(employer)

                            recipients = [user.email]
                            context.update({
                                "first_name": user.first_name,
                                "email": user.email,
                                "has_account": True,
                            })

                            send_event_company_representative_access_instructions(
                            )
                    else:
                        context.update({
                            "first_name":
                            row.get("first name", ""),
                            "last_name":
                            row.get("last name", ""),
                            "email":
                            row.get("email", ""),
                            "supposed_employer":
                            row.get("employer", "")
                        })

                        body = render_to_string(
                            'attending_recruiter_problem.txt', context)

                        subject = ''.join(
                            render_to_string(
                                'email_admin_subject.txt', {
                                    'message':
                                    "%s has a problem with a recruiter" %
                                    event.name
                                }, context).splitlines())

                        send_email(subject, body, recipients)
        else:
            data['errors'] = form.errors
        return HttpResponse(simplejson.dumps(data),
                            mimetype="application/json")
    else:
        form = form_class(initial={'event_id': request.GET['event_id']})
    context = {'form': form, 'TEMPLATE': 'event_upload_recruiters_list.html'}
    context.update(extra_context or {})
    return context