Esempio n. 1
0
    def get_context_data(self, **kwargs):
        context = super(CompanyProfileFormView, self).get_context_data(
            **kwargs)
        company = get_company(self.request)
        context.setdefault('company', company)

        return context
Esempio n. 2
0
def view_request(request, pk, model=None):
    template = 'postajob/request/{model}.html'
    company = get_company(request)
    model = model or Request

    request_kwargs = {
        'pk': pk,
        'owner': company
    }

    request_made = get_object_or_404(model, **request_kwargs)
    if model == Request:
        activity = "read request"
        request_object = request_made.request_object()
    else:
        activity = "read offline purchase"
        request_object = request_made

    content_type = ContentType.objects.get_for_model(type(request_object))

    data = {
        'company': company,
        'content_type': content_type,
        'object': request_object,
        'request_obj': request_made,
    }

    if not request.user.can(company, activity):
        return MissingActivity()

    return render_to_response(template.format(model=content_type.model),
                              data, RequestContext(request))
Esempio n. 3
0
def product_listing(request):
    site = settings.SITE
    company = get_company(request)

    # Get all site packages and products for a site.
    site_packages = site.sitepackage_set.all()
    products = Product.objects.filter(package__sitepackage__in=site_packages)

    # Group products by the site package they belong to.
    groupings = set()
    for product in products:
        profile = get_object_or_none(CompanyProfile, company=product.owner)
        if product.cost < 0.01 or (profile and profile.authorize_net_login and
                                   profile.authorize_net_transaction_key):
            groupings = groupings.union(
                set(product.productgrouping_set.filter(is_displayed=True,
                                                       products__isnull=False)))

    # Sort the grouped packages by the specified display order.
    groupings = sorted(groupings, key=lambda grouping: grouping.display_order)

    return render_to_response('postajob/%s/package_list.html'
                              % settings.PROJECT,
                              {'product_groupings': groupings,
                               'company': company},
                              RequestContext(request))
Esempio n. 4
0
def has_access(feature):
    """
    Decorator that signifies which feature permissions are required in order to
    access the view.

    Inputs:
        :feature: Name of feature to check permissiosn for.

    Returns:
        A decorator that raises a 404 if the supplied feature's permission
        requirements are not met. If no permissions are specified for the given
        feature, it is assumed that the feature should never be available.
    """

    # mapping from feature name to a list of conditions to be met.
    conditions = {
        'prm': [
            # not a member company
            lambda req: not getattr(get_company(req), 'prm_access', False)
        ]
    }

    return not_found_when(
        condition=lambda req: all(c(req) for c in conditions.get(feature, [])),
        message="Must have %s access to proceed." % feature,
        feature=feature, enabled=False)
Esempio n. 5
0
def view_request(request, pk, model=None):
    template = 'postajob/{project}/request/{model}.html'
    company = get_company(request)
    model = model or Request

    request_kwargs = {
        'pk': pk,
        'owner': company
    }

    request_made = get_object_or_404(model, **request_kwargs)
    if model == Request:
        request_object = request_made.request_object()
    else:
        request_object = request_made

    content_type = ContentType.objects.get_for_model(type(request_object))

    data = {
        'company': company,
        'content_type': content_type,
        'object': request_object,
        'request_obj': request_made,
    }

    if not data['object'].user_has_access(request.user):
        raise Http404

    return render_to_response(template.format(project=settings.PROJECT,
                                              model=content_type.model),
                              data, RequestContext(request))
Esempio n. 6
0
def purchasedmicrosite_admin_overview(request):
    company = get_company(request)
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        products = Product.objects.filter_by_sites(sites)
        purchased = PurchasedProduct.objects.filter_by_sites(sites)
        groupings = ProductGrouping.objects.filter_by_sites(sites)
        offline_purchases = OfflinePurchase.objects.filter_by_sites(sites)
        requests = Request.objects.filter_by_sites(sites)
    else:
        products = Product.objects.all()
        purchased = PurchasedProduct.objects.all()
        groupings = ProductGrouping.objects.all()
        offline_purchases = OfflinePurchase.objects.all()
        requests = Request.objects.all()

    data = {
        'products': products.filter(owner=company)[:3],
        'product_groupings': groupings.filter(owner=company)[:3],
        'purchased_products': purchased.filter(product__owner=company)[:3],
        'offline_purchases': offline_purchases.filter(owner=company)[:3],
        'requests': requests.filter(owner=company)[:3],
        'company': company
    }

    return render_to_response('postajob/%s/admin_overview.html'
                              % settings.PROJECT, data,
                              RequestContext(request))
Esempio n. 7
0
def view_request(request, pk, model=None):
    template = 'postajob/request/{model}.html'
    company = get_company(request)
    model = model or Request

    request_kwargs = {'pk': pk, 'owner': company}

    request_made = get_object_or_404(model, **request_kwargs)
    if model == Request:
        activity = "read request"
        request_object = request_made.request_object()
    else:
        activity = "read offline purchase"
        request_object = request_made

    content_type = ContentType.objects.get_for_model(type(request_object))

    data = {
        'company': company,
        'content_type': content_type,
        'object': request_object,
        'request_obj': request_made,
    }

    if not request.user.can(company, activity):
        return MissingActivity()

    return render_to_response(template.format(model=content_type.model), data,
                              RequestContext(request))
Esempio n. 8
0
    def get_context_data(self, **kwargs):
        context = super(CompanyProfileFormView,
                        self).get_context_data(**kwargs)
        company = get_company(self.request)
        context.setdefault('company', company)

        return context
Esempio n. 9
0
def candidate_information(request):
    """
    Sends user info, primary name, and searches to candidate_information.html.
    Gathers the employer's (request.user) companies and microsites and puts
    the microsites' domains in a list for further checking and logic,
    see helpers.py.

    """
    user_id = get_int_or_none(request.REQUEST.get('user'))
    company = get_company(request)

    if not user_id or not company:
        raise Http404

    # user gets pulled out from id
    try:
        candidate = User.objects.get(id=user_id)
    except User.DoesNotExist:
        raise Http404

    if not candidate.opt_in_employers:
        raise Http404

    urls = saved_searches(request.user, company, candidate)
    actions = analytics(request.user, company, candidate)
    actions = get_analytics_counts(actions)

    if not urls and not actions:
        raise Http404

    manager = PrimaryNameProfileUnitManager(order=['employmenthistory',
                                                   'education',
                                                   'militaryservice'])
    models = manager.displayed_units(candidate.profileunits_set.all())

    primary_name = getattr(manager, 'primary_name', 'Name not given')

    coming_from = {'path': 'view'}

    searches = candidate.savedsearch_set.all()
    searches = [search for search in searches
                if get_domain(search.feed).lower() in urls]

    modified_url = remove_param_from_url(request.build_absolute_uri(), 'user')
    query_string = "?%s" % urlparse(modified_url).query

    data_dict = {
        'user_info': models,
        'company_id': company.pk,
        'primary_name': primary_name,
        'the_user': candidate,
        'searches': searches,
        'coming_from': coming_from,
        'query_string': query_string,
        'actions': actions,
    }

    return render_to_response('mydashboard/candidate_information.html',
                              data_dict, RequestContext(request))
Esempio n. 10
0
    def access_callback(request):
        """
        Default callback used when appropriate app-level access isn't
        found.

        """
        company = get_company(request)
        raise Http404("%s doesn't have sufficient app-level access." % (
            company.name))
Esempio n. 11
0
def resend_invoice(request, pk):
    company = get_company(request)

    product = PurchasedProduct.objects.get(pk=pk, product__owner=company)
    product.invoice.send_invoice_email(send_to_admins=False,
                                       other_recipients=[request.user.email])
    data = {'purchased_product': pk}
    redirect_url = reverse('admin_view_invoice', kwargs=data) + '?m=success'
    return HttpResponseRedirect(redirect_url)
Esempio n. 12
0
    def access_callback(request):
        """
        Default callback used when appropriate app-level access isn't
        found.

        """
        company = get_company(request)
        raise MissingAppLevelAccess(
            "%s doesn't have sufficient app-level access." % (company.name))
Esempio n. 13
0
def resend_invoice(request, pk):
    company = get_company(request)

    product = PurchasedProduct.objects.get(pk=pk, product__owner=company)
    product.invoice.send_invoice_email(send_to_admins=False,
                                       other_recipients=[request.user.email])
    data = {'purchased_product': pk}
    redirect_url = reverse('admin_view_invoice', kwargs=data) + '?m=success'
    return HttpResponseRedirect(redirect_url)
Esempio n. 14
0
def admin_offlinepurchase(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    purchases = OfflinePurchase.objects.filter_by_sites(sites)
    data = {
        'offline_purchases': purchases.filter(owner=company),
        'company': company,
    }
    return render_to_response('postajob/offlinepurchase.html', data,
                              RequestContext(request))
Esempio n. 15
0
def admin_offlinepurchase(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    purchases = OfflinePurchase.objects.filter_by_sites(sites)
    data = {
        'offline_purchases': purchases.filter(owner=company),
        'company': company,
    }
    return render_to_response('postajob/offlinepurchase.html', data,
                              RequestContext(request))
Esempio n. 16
0
def activities(request):
    """
    Returns the activities a user can perform for the currently selected
    company.

    """
    company = get_company(request)
    if not request.user.is_anonymous() and request.user.pk:
        return {"activities": request.user.get_activities(company)}
    return {"activities": []}
Esempio n. 17
0
def activities(request):
    """
    Returns the activities a user can perform for the currently selected
    company.

    """
    company = get_company(request)
    if not request.user.is_anonymous() and request.user.pk:
        return {"activities": request.user.get_activities(company)}
    return {"activities": []}
Esempio n. 18
0
def admin_purchasedproduct(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    purchases = PurchasedProduct.objects.filter_by_sites(sites).filter(
        product__owner=company)
    data = {
        'company': company,
        'active_products': purchases.filter(expiration_date__gte=date.today()),
        'expired_products': purchases.filter(expiration_date__lt=date.today()),
    }

    return render_to_response('postajob/purchasedproduct.html', data,
                              RequestContext(request))
Esempio n. 19
0
def admin_request(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    requests = Request.objects.filter_by_sites(sites)

    data = {
        'company': company,
        'pending_requests': requests.filter(owner=company, action_taken=False),
        'processed_requests': requests.filter(owner=company, action_taken=True)
    }

    return render_to_response('postajob/request.html', data,
                              RequestContext(request))
Esempio n. 20
0
def admin_groupings(request):
    company = get_company(request)
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        grouping = ProductGrouping.objects.filter_by_sites(sites)
    else:
        grouping = ProductGrouping.objects.all()
    data = {
        'product_groupings': grouping.filter(owner=company),
        'company': company,
    }
    return render_to_response('postajob/productgrouping.html', data,
                              RequestContext(request))
Esempio n. 21
0
def prm_worthy(request):
    """
    Makes sure the User is worthy enough to use PRM.

    """
    company = get_company(request)
    if company is None:
        raise Http404("mypartners.helpers.prm_worthy: no company")

    partner_id = get_int_or_none(request.REQUEST.get('partner'))
    partner = get_object_or_404(company.partner_set, id=partner_id)

    return company, partner, request.user
Esempio n. 22
0
def admin_groupings(request):
    company = get_company(request)
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        grouping = ProductGrouping.objects.filter_by_sites(sites)
    else:
        grouping = ProductGrouping.objects.all()
    data = {
        'product_groupings': grouping.filter(owner=company),
        'company': company,
    }
    return render_to_response('postajob/productgrouping.html', data,
                              RequestContext(request))
Esempio n. 23
0
def admin_request(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    requests = Request.objects.filter_by_sites(sites)

    data = {
        'company': company,
        'pending_requests': requests.filter(owner=company, action_taken=False),
        'processed_requests': requests.filter(owner=company, action_taken=True)
    }

    return render_to_response('postajob/request.html', data,
                              RequestContext(request))
Esempio n. 24
0
def prm_worthy(request):
    """
    Makes sure the User is worthy enough to use PRM.

    """
    company = get_company(request)
    if company is None:
        raise Http404

    partner_id = get_int_or_none(request.REQUEST.get('partner'))
    partner = get_object_or_404(company.partner_set, id=partner_id)

    return company, partner, request.user
Esempio n. 25
0
def admin_purchasedproduct(request):
    company = get_company(request)
    sites = settings.SITE.postajob_site_list()
    purchases = PurchasedProduct.objects.filter_by_sites(sites).filter(
        product__owner=company)
    data = {
        'company': company,
        'active_products': purchases.filter(expiration_date__gte=date.today()),
        'expired_products': purchases.filter(expiration_date__lt=date.today()),
    }

    return render_to_response('postajob/purchasedproduct.html', data,
                              RequestContext(request))
Esempio n. 26
0
def jobs_overview(request):
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        jobs = Job.objects.filter_by_sites(sites)
    else:
        jobs = Job.objects.all()
    company = get_company(request)
    data = {
        'company' : company,
        'jobs': jobs.filter(owner=company, purchasedjob__isnull=True),
    }
    return render_to_response('postajob/%s/jobs_overview.html'
                              % settings.PROJECT, data,
                              RequestContext(request))
Esempio n. 27
0
def process_admin_request(request, pk, approve=True,
                          block=False):
    """
    Marks a Request as action taken on it and sets the corresponding object's
    approval status. Assumes the object has an is_approved field.

    Adds the requesting user (if one exists) to the company's block list
    if the block parameter is True.

    """
    company = get_company(request)
    request_made = get_object_or_404(Request, pk=pk, owner=company)
    content_type = request_made.content_type
    request_object = request_made.request_object()

    if request_object and request_object.user_has_access(request.user):
        if block and request_object.created_by:
            # Block the user that initiated this request
            # and deny all of that user's outstanding requests
            profile, _ = CompanyProfile.objects.get_or_create(
                company=company)
            profile.blocked_users.add(request_object.created_by)

            # Since Requests and the objects associated with them are related
            # using a fake foreign key, we have to do multiple queries. We
            # could potentially get away with only the first two, but the last
            # one is included just to be safe.
            request_objects = content_type.model_class().objects.filter(
                created_by=request_object.created_by,
                owner=request_object.owner,
                is_approved=False)
            requests = Request.objects.filter(
                object_id__in=request_objects.values_list('pk', flat=True),
                action_taken=False).values_list('object_id', flat=True)
            request_objects = request_objects.filter(
                pk__in=requests)

            reason = request.REQUEST.get('block-reason', '')
            requests.update(action_taken=True, deny_reason=reason)
            request_objects.update(is_approved=False)
        else:
            request_object.is_approved = approve
            request_object.save()
            if not approve:
                request_made.deny_reason = request.REQUEST.get('deny-reason',
                                                               '')
            request_made.action_taken = True
            request_made.save()

    return redirect('request')
Esempio n. 28
0
def admin_products(request):
    company = get_company(request)
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        products = Product.objects.filter_by_sites(sites)
    else:
        products = Product.objects.all()
    data = {
        'products': products.filter(owner=company),
        'company': company,
    }
    return render_to_response('postajob/%s/products.html'
                              % settings.PROJECT, data,
                              RequestContext(request))
Esempio n. 29
0
 def __init__(self, *args, **kwargs):
     request = kwargs.pop("request")
     super(EventFieldForm, self).__init__(*args, **kwargs)
     setattr(self, "request", request)
     initial = self.initial.get("field")
     choices = [("", "---------")]
     if initial:
         # It doesn't matter that we aren't actually retrieving the full
         # choice list at this point in time. This is just to preserve the
         # current value - the full list is retrieved via ajax on load.
         choices.append((initial, initial))
     self.fields["field"] = NoValidationChoiceField(choices=choices)
     if not request.user.is_superuser:
         company = get_company(request)
         queryset = EmailTemplate.objects.filter(Q(owner=company) | Q(owner__isnull=True))
         self.fields["email_template"].queryset = queryset
Esempio n. 30
0
    def set_object(self, *args, **kwargs):
        if resolve(self.request.path).url_name == self.add_name:
            if not self.product.can_post_more():
                # If more jobs can't be posted to the project, don't allow
                # the user to access the add view.
                raise Http404
            else:
                company = get_company(self.request)
                if company and hasattr(company, 'companyprofile'):
                    if self.request.user in company.companyprofile.blocked_users.all():
                        # If the current user has been blocked by the company
                        # that we are trying to post a job to, don't allow
                        # the user to access the add view.
                        raise Http404

        return super(PurchasedJobFormView, self).set_object(*args, **kwargs)
Esempio n. 31
0
def process_admin_request(request, pk, approve=True, block=False):
    """
    Marks a Request as action taken on it and sets the corresponding object's
    approval status. Assumes the object has an is_approved field.

    Adds the requesting user (if one exists) to the company's block list
    if the block parameter is True.

    """
    company = get_company(request)
    request_made = get_object_or_404(Request, pk=pk, owner=company)
    content_type = request_made.content_type
    request_object = request_made.request_object()

    if request_object and request_object.user_has_access(request.user):
        if block and request_object.created_by:
            # Block the user that initiated this request
            # and deny all of that user's outstanding requests
            profile, _ = CompanyProfile.objects.get_or_create(company=company)
            profile.blocked_users.add(request_object.created_by)

            # Since Requests and the objects associated with them are related
            # using a fake foreign key, we have to do multiple queries. We
            # could potentially get away with only the first two, but the last
            # one is included just to be safe.
            request_objects = content_type.model_class().objects.filter(
                created_by=request_object.created_by,
                owner=request_object.owner,
                is_approved=False)
            requests = Request.objects.filter(
                object_id__in=request_objects.values_list('pk', flat=True),
                action_taken=False).values_list('object_id', flat=True)
            request_objects = request_objects.filter(pk__in=requests)

            reason = request.REQUEST.get('block-reason', '')
            requests.update(action_taken=True, deny_reason=reason)
            request_objects.update(is_approved=False)
        else:
            request_object.is_approved = approve
            request_object.save()
            if not approve:
                request_made.deny_reason = request.REQUEST.get(
                    'deny-reason', '')
            request_made.action_taken = True
            request_made.save()

    return redirect('request')
Esempio n. 32
0
    def dispatch(self, *args, **kwargs):
        """
        Determine and set which product is attempting to be purchased.

        """
        # The add url also has the pk for the product they're attempting
        # to purchase.

        self.product = get_object_or_404(self.purchase_model,
                                         pk=kwargs.get('product'))

        # Set the display name based on the model
        self.display_name = self.display_name.format(product=self.product)

        # If the product is free but the current user has no companies or an
        # un-filled-out profile, use the product form that only gets company
        # information.
        if self.product.cost < 0.01:
            company = get_company(self.request)
            profile = get_object_or_none(CompanyProfile, company=company)

            if company and profile and profile.address_line_one:
                invoice = Invoice.objects.create(
                    transaction_type=Invoice.FREE,
                    first_name=self.request.user.first_name,
                    last_name=self.request.user.last_name,
                    address_line_one=profile.address_line_one,
                    address_line_two=profile.address_line_two,
                    city=profile.city,
                    state=profile.state,
                    country=profile.country,
                    zipcode=profile.zipcode,
                    owner=self.product.owner,
                )
                purchase_kwargs = {
                    'product': self.product,
                    'invoice': invoice,
                    'owner': company,
                    'paid': True,
                }
                PurchasedProduct.objects.create(**purchase_kwargs)
                return redirect(self.success_url)
            else:
                self.display_name = self.product
                self.form_class = PurchasedProductNoPurchaseForm
        return super(PurchasedProductFormView, self).dispatch(*args, **kwargs)
Esempio n. 33
0
def blocked_user_management(request):
    """
    Displays blocked users (if any) for the current company as well as
    an unblock link.
    """
    company = get_company(request)
    if not company:
        raise Http404
    profile = CompanyProfile.objects.get_or_create(company=company)[0]
    blocked_users = profile.blocked_users.all()
    data = {
        'company': company,
        'blocked_users': blocked_users
    }
    return render_to_response('postajob/%s/blocked_user_management.html'
                              % settings.PROJECT, data,
                              RequestContext(request))
Esempio n. 34
0
    def dispatch(self, *args, **kwargs):
        """
        Determine and set which product is attempting to be purchased.

        """
        # The add url also has the pk for the product they're attempting
        # to purchase.

        self.product = get_object_or_404(self.purchase_model,
                                         pk=kwargs.get('product'))

        # Set the display name based on the model
        self.display_name = self.display_name.format(product=self.product)

        # If the product is free but the current user has no companies or an
        # un-filled-out profile, use the product form that only gets company
        # information.
        if self.product.cost < 0.01:
            company = get_company(self.request)
            profile = get_object_or_none(CompanyProfile, company=company)

            if company and profile and profile.address_line_one:
                invoice = Invoice.objects.create(
                    transaction_type=Invoice.FREE,
                    first_name=self.request.user.first_name,
                    last_name=self.request.user.last_name,
                    address_line_one=profile.address_line_one,
                    address_line_two=profile.address_line_two,
                    city=profile.city,
                    state=profile.state,
                    country=profile.country,
                    zipcode=profile.zipcode,
                    owner=self.product.owner,
                )
                purchase_kwargs = {
                    'product': self.product,
                    'invoice': invoice,
                    'owner': company,
                    'paid': True,
                }
                PurchasedProduct.objects.create(**purchase_kwargs)
                return redirect(self.success_url)
            else:
                self.display_name = self.product
                self.form_class = PurchasedProductNoPurchaseForm
        return super(PurchasedProductFormView, self).dispatch(*args, **kwargs)
Esempio n. 35
0
def purchasedproducts_overview(request):
    company = get_company(request)
    if settings.SITE:
        sites = settings.SITE.postajob_site_list()
        products = PurchasedProduct.objects.filter_by_sites(sites)
        jobs = PurchasedJob.objects.filter_by_sites(sites)
    else:
        products = Product.objects.all()
        jobs = PurchasedJob.objects.all()
    products = products.filter(owner=company)
    data = {
        'company': company,
        'jobs': jobs.filter(owner=company),
        'active_products': products.filter(expiration_date__gte=date.today()),
        'expired_products': products.filter(expiration_date__lt=date.today()),
    }
    return render_to_response('postajob/%s/purchasedproducts_overview.html'
                              % settings.PROJECT,
                              data, RequestContext(request))
Esempio n. 36
0
        def wrap(request, *args, **kwargs):

            # If the user is not logged in, redirect them to the login page
            # with this url as the next url.
            if request.user.is_anonymous():
                params = {'next': request.get_full_path()}
                next_url = build_url(reverse('login'), params)
                return HttpResponseRedirect(next_url)

            # If the user is logged in, but they aren't a CompanyUser or they
            # are a CompanyUser, but their current Company doesn't have
            # perm_field access, return a 404.
            company = get_company(request)

            if not company or (perm_field and not getattr(company, perm_field,
                                                          False)):
                raise Http404

            return view_func(request, *args, **kwargs)
Esempio n. 37
0
def unblock_user(request, pk):
    """
    Unblocks a given user that has previously been blocked from posting jobs.

    Inputs:
    :pk: ID of user that has been blocked
    """
    company = get_company(request)
    if not company:
        raise Http404
    profile = company.companyprofile
    if profile:
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            pass
        else:
            profile.blocked_users.remove(user)
    return redirect(reverse('blocked_user_management'))
Esempio n. 38
0
        def wrap(request, *args, **kwargs):

            # If the user is not logged in, redirect them to the login page
            # with this url as the next url.
            if request.user.is_anonymous():
                params = {'next': request.get_full_path()}
                next_url = build_url(reverse('login'), params)
                return HttpResponseRedirect(next_url)

            # If the user is logged in, but they aren't an admin or they
            # are an admin , but their current Company doesn't have
            # perm_field access, return a 404.
            company = get_company(request)

            if not company or (perm_field
                               and not getattr(company, perm_field, False)):
                raise Http404("universal.decorators.company_has_access: "
                              "company doesn't exist or doesn't have "
                              "{perm} permissions".format(perm=perm_field))

            return view_func(request, *args, **kwargs)
Esempio n. 39
0
def get_purchasedjob_add_link(context):
    """
    Generates add links for creating PurchasedJobs. If the user is blocked, the
    link is replaced with a modal telling them so.
    """
    request = context['request']
    company = get_company(request)

    # Add 'blocked' context variable; determines if we are going to add a real
    # link or a modal when rendering the template.
    context['blocked'] = request.user in company.companyprofile.blocked_users.all()

    if 'purchased_product' not in context:
        # This is called from both the company owner side and the job poster
        # side. The context variable for the current purchased product is
        # different between the two.
        context['purchased_product'] = context['product']

    link = render_to_string('postajob/includes/purchasedjob_add_link.html',
                            context)
    return mark_safe(link)
Esempio n. 40
0
        def wrap(request, *args, **kwargs):

            # If the user is not logged in, redirect them to the login page
            # with this url as the next url.
            if request.user.is_anonymous():
                params = {'next': request.get_full_path()}
                next_url = build_url(reverse('login'), params)
                return HttpResponseRedirect(next_url)

            # If the user is logged in, but they aren't an admin or they
            # are an admin , but their current Company doesn't have
            # perm_field access, return a 404.
            company = get_company(request)

            if not company or (perm_field and not getattr(company, perm_field,
                                                          False)):
                raise Http404("universal.decorators.company_has_access: "
                              "company doesn't exist or doesn't have "
                              "{perm} permissions".format(perm=perm_field))

            return view_func(request, *args, **kwargs)
Esempio n. 41
0
    def get_context_data(self, **kwargs):
        kwargs['company'] = get_company(self.request)
        kwargs['prevent_delete'] = self.prevent_delete

        return super(PostajobModelFormMixin, self).get_context_data(**kwargs)
Esempio n. 42
0
def get_menus(context):
    """
    Returns menu items used in the topbar.

    Each top-level item is a 'menu' (eg. "Employers"), where as everything
    below those is a submenu (eg. "PRM").

    """
    # have to use hard coded urls since the named views don't exist on
    # microsites.
    url = lambda path: settings.ABSOLUTE_URL + path
    request = context.get("request")
    company = get_company(request)
    user = context.get("user")
    new_messages = context.get("new_messages")
    impersonating = context.get("impersonating")

    # menu item cant be generated for a user who isn't logged in
    if not user or not user.pk or user.is_anonymous():
        return []

    if new_messages:
        message_submenus = [{
            "id":
            info.message.pk,
            "href":
            url("message/inbox?message=%s" % info.message.pk),
            "label":
            "%s - %s" %
            (info.message.start_on.date(), info.message.subject[:10])
        } for info in context["new_messages"][:3]]
    else:
        message_submenus = [{
            "id": "no-messages",
            "href": url("message/inbox"),
            "label": "No new unread messages"
        }]
    message_menu = {
        "label":
        "Messages",
        "id":
        "menu-inbox",
        "icon":
        "icon-envelope icon-white",
        "mobile_icon_v2":
        "glyphicon glyphicon-envelope",
        "iconLabel":
        str(new_messages.count() if new_messages else 0),
        "mobile_submenuId":
        "mobile-messages",
        "submenus": [{
            "id": "menu-inbox-all",
            "href": url("message/inbox"),
            "label": "Inbox (See All)",
        }] + message_submenus
    }
    beta_menu = {}
    if user.is_superuser and 'apps.directemployers.org' in user.email:
        beta_menu.update({
            "label": "Beta",
            "id": "beta-menu",
            "mobile_icon_v2": "glyphicon glyphicon-flag",
            "submenus": [],
            "mobile_submenuId": "mobile-beta",
        })

        try:
            can_read_outreach_email_address = user.can(
                company, "read outreach email address")
        except MissingAppLevelAccess:
            can_read_outreach_email_address = False

        if can_read_outreach_email_address:
            beta_menu["submenus"].append({
                "id":
                "nonuseroutreach",
                "href":
                url("prm/view/nonuseroutreach"),
                "label":
                "Non-User Outreach",
            })

        try:
            can_view_analytics_info = user.can(company, "view analytics")
        except MissingAppLevelAccess:
            can_view_analytics_info = False

        if can_view_analytics_info:
            beta_menu["submenus"].append({
                "id": "analytics",
                "href": url("analytics/view/main"),
                "label": "Analytics",
            })

    employer_menu = {
        "label": "Employers",
        "id": "employers",
        "mobile_icon_v2": "glyphicon glyphicon-briefcase",
        "submenuId": "employer-apps",
        "mobile_submenuId": "mobile-employer-apps",
        "submenus": []
    } if user.roles.exists() else {}

    try:
        can_read_partner = user.can(company, "read partner")
    except MissingAppLevelAccess:
        can_read_partner = False

    if employer_menu and can_read_partner:
        employer_menu["submenus"] += [
            {
                "id": "partner-tab",
                "href": url("prm/view"),
                "label": "PRM"
            },
        ]

        version_urls = {
            'dynamic': url("reports/view/dynamicoverview"),
            'classic': url("reports/view/overview"),
        }
        reporting_version = request.COOKIES.get('reporting_version', 'classic')
        employer_menu["submenus"].append({
            "id":
            "reports-tab",
            "href":
            version_urls.get(reporting_version, "classic"),
            "label":
            "Reports",
        })

    try:
        can_read_role = user.can(company, "read role")
    except MissingAppLevelAccess:
        can_read_role = False

    if employer_menu and can_read_role:
        employer_menu["submenus"].append({
            "id": "manage-users-tab",
            "href": url("manage-users"),
            "label": "Manage Users",
        })

    profile_menu = {
        "label":
        user.email,
        "id":
        "profile_mobile_v2",
        "mobile_icon_v2":
        "glyphicon glyphicon-user",
        "label_mobile_v2":
        "Profile",
        "mobile_submenuId":
        "mobile-profile",
        "submenus": [{
            "id": "profile-tab",
            "href": url("profile/view"),
            "label": "My Profile"
        }, {
            "id": "searches-tab",
            "href": url("saved-search/view"),
            "label": "My Saved Searches"
        }, {
            "id": "account-tab",
            "href": url("account/edit"),
            "label": "Account Settings"
        }, {
            "id": "search-tab",
            "href": get_ms_url(context),
            "label": "Search Jobs"
        }, {
            "id": "logout-tab",
            "href": url("accounts/logout"),
            "label": "Log Out"
        }]
    }

    # If the topbar request is coming from a microsite, we've got the wrong
    # user. This can't simply be a request.user check.
    if impersonating or getattr(request.user, 'is_impersonate', False):
        profile_menu["submenus"].append({
            "id": "impersonate-tab",
            "href": reverse("impersonate-stop"),
            "label": "Stop Impersonating"
        })

    # only return menus we've populated
    return [
        menu for menu in beta_menu, message_menu, employer_menu, profile_menu
        if menu
    ]
Esempio n. 43
0
def get_company_from_cookie(context):
    request = context.get('request')
    if request:
        return get_company(request)
    return None
Esempio n. 44
0
 def __init__(self, *args, **kwargs):
     self.request = kwargs.pop('request', None)
     self.company = get_company(self.request)
     super(RequestForm, self).__init__(*args, **kwargs)
Esempio n. 45
0
def get_company_from_cookie(context):
    request = context.get('request')
    if request:
        return get_company(request)
    return None
Esempio n. 46
0
def get_menus(context):
    """
    Returns menu items used in the topbar.

    Each top-level item is a 'menu' (eg. "Employers"), where as everything
    below those is a submenu (eg. "PRM").

    """
    # have to use hard coded urls since the named views don't exist on
    # microsites.
    url = lambda path: settings.ABSOLUTE_URL + path
    company = get_company(context.get("request"))
    user = context.get("user")
    new_messages = context.get("new_messages")

    # menu item cant be generated for a user who isn't logged in
    if not user or not user.pk or user.is_anonymous():
        return []

    if new_messages:
        message_submenus = [
            {
                "id": info.message.pk,
                "href": url("message/inbox?message=%s" % info.message.pk),
                "label": "%s - %s" % (
                    info.message.start_on.date(), info.message.subject[:10]
                )
            } for info in context["new_messages"][:3]]
    else:
        message_submenus = [
            {
                "id": "no-messages",
                "href": url("message/inbox"),
                "label": "No new unread messages"
            }
        ]
    message_menu = {
        "label": "Messages",
        "id": "menu-inbox",
        "icon": "icon-envelope icon-white",
        "iconLabel": str(new_messages.count() if new_messages else 0),
        "submenus": [
            {
                "id": "menu-inbox-all",
                "href": url("message/inbox"),
                "label": "Inbox (See All)",
            }
        ] + message_submenus
    }

    employer_menu = {
        "label": "Employers",
        "id": "employers",
        "submenuId": "employer-apps",
        "submenus": [
        ]
    } if user.roles.exists() else {}

    if employer_menu and user.can(company, "read partner"):
        employer_menu["submenus"] += [
            {
                "id": "partner-tab",
                "href": url("prm/view"),
                "label": "PRM"
            },
            {
                "id": "reports-tab",
                "href": url("reports/view/overview"),
                "label": "Reports",
            }
        ]

    if employer_menu and user.can(company, "read role"):
        employer_menu["submenus"].append(
            {
                "id": "manage-users-tab",
                "href": url("manage-users"),
                "label": "Manage Users",
            }
        )

    profile_menu = {
        "label": user.email,
        "submenus": [
            {
                "id": "profile-tab",
                "href": url("profile/view"),
                "label": "My Profile"
            },
            {
                "id": "searches-tab",
                "href": url("saved-search/view"),
                "label": "My Saved Searches"
            },
            {
                "id": "account-tab",
                "href": url("account/edit"),
                "label": "Account Settings"
            },
            {
                "id": "search-tab",
                "href": get_ms_url(context),
                "label": "Search Jobs"
            },
            {
                "id": "logout-tab",
                "href": url("accounts/logout"),
                "label": "Log Out"
            }
        ]
    }

    # only return menus we've populated
    return [menu for menu in message_menu, employer_menu, profile_menu if menu]
Esempio n. 47
0
def dashboard(request, template="mydashboard/mydashboard.html",
              extra_context=None):
    """
    Returns a list of candidates who created a saved search for one of the
    microsites within the company microsite list or with the company name like
    jobs.jobs/company_name/careers for example between the given (optional)
    dates

    Inputs:
    :company:               company.id that is associated with request.user

    Returns:
    :render_to_response:    renders template with context dict

    """
    if hasattr(mail, 'outbox'):
        solr = settings.TEST_SOLR_INSTANCE
    else:
        solr = settings.SOLR

    company = get_company(request)
    if not company:
        raise Http404

    user_solr = Solr(solr['current'])
    facet_solr = Solr(solr['current'])

    # Add join only if we're using facets, not if we're simply searching.
    query_params = {'search', 'company'}
    if not query_params.issuperset({q_key for q_key in request.GET.keys()
                                    if q_key not in ['querystring_key',
                                                     'date_end', 'date_start',
                                                     'page']}):
        user_solr = user_solr.add_join(from_field='ProfileUnits_user_id',
                                       to_field='User_id')
    facet_solr = facet_solr.add_join(from_field='User_id',
                                     to_field='ProfileUnits_user_id')
    facet_solr = facet_solr.rows_to_fetch(0)

    authorized_microsites, buids = get_company_microsites(company)

    admins = CompanyUser.objects.filter(company=company.id)

    # Removes main user from admin list to display other admins
    admins = admins.exclude(user=request.user)
    requested_microsite = request.REQUEST.get('microsite', '')
    requested_date_button = request.REQUEST.get('date_button', False)    
    candidates_page = request.REQUEST.get('page', 1)    
          
    # the url value for 'All' in the select box is company name
    # which then gets replaced with all microsite urls for that company
    site_name = ''
    if requested_microsite != '':
        active_microsites = authorized_microsites.filter(
            domain__startswith=requested_microsite)
        user_solr, facet_solr = filter_by_domain(requested_microsite,
                                                 user_solr, facet_solr)
    else:
        active_microsites = authorized_microsites
        site_name = company.name
    if not site_name:
        try:
            site_name = active_microsites[0]
        except IndexError:
            site_name = ''
    active_microsites = set(active_microsites)

    rng, date_start, date_end, date_display = filter_by_date(request)
    user_solr = user_solr.add_filter_query(rng)
    facet_solr = facet_solr.add_query(rng)

    if request.GET.get('search', False):
        user_solr = user_solr.add_query("%s" % request.GET['search'])
        facet_solr = facet_solr.add_query("%s" % request.GET['search'])

    user_solr, facet_solr = filter_by_microsite(company, user_solr, facet_solr)

    (user_solr, facet_solr, filters) = apply_facets_and_filters(
        request, user_solr, facet_solr)

    solr_results = user_solr.rows_to_fetch(100).search()

    # List of dashboard widgets to display.
    dashboard_widgets = ["home_views", "search_views", "job_views",
                         "apply_clicks", "candidates", "search",
                         "applied_filters", "filters"]

    # Date button highlighting
    if 'today' in request.REQUEST:
        requested_date_button = 'today'
    elif 'seven_days' in request.REQUEST:
        requested_date_button = 'seven_days'
    elif 'thirty_days' in request.REQUEST:
        requested_date_button = 'thirty_days'

    url = request.build_absolute_uri()
    facets = parse_facets(facet_solr.search(), request)

    context = {
        'admin_you': request.user,
        'applied_filters': filters,
        'candidates_page': candidates_page,
        'company_admins': admins,
        'company_id': company.id,
        'company_microsites': authorized_microsites,
        'company_name': company.name,
        'dashboard_widgets': dashboard_widgets,
        'date_button': requested_date_button,
        'date_display': date_display,
        'date_end': date_end,
        'date_start': date_start,
        'date_submit_url': url,
        'facets': facets,
        'site_name': site_name,
        'view_name': 'Company Dashboard',
    }

    results = solr_results.docs

    facet_var_map = {
        'home': 'home',
        'listing': 'job_view',
        'results': 'search',
        'redirect': 'apply',
    }
    analytics_solr = Solr(solr['current']).add_facet_field(
        'page_category')
    if requested_microsite:
        analytics_solr = analytics_solr.add_query('domain:%s' %
                                                  requested_microsite)
    else:
        analytics_solr = analytics_solr.add_query('company_id:%d' % company.pk)

    rng = filter_by_date(request, field='view_date')[0]
    analytics_solr = analytics_solr.add_filter_query(rng)

    all_results = analytics_solr.rows_to_fetch(0).search()
    analytics_facets = all_results.facets.get('facet_fields', {}).get(
        'page_category', [])
    facet_dict = sequence_to_dict(analytics_facets)
    for key in facet_dict.keys():
        context_key = 'total_%s' % facet_var_map.get(key, '')
        context[context_key] = facet_dict[key]

    analytics_solr = analytics_solr.add_filter_query('User_id:[* TO *]')
    analytics_solr = analytics_solr.add_facet_field('domain')

    auth_results = analytics_solr.search()
    analytics_facet_list = auth_results.facets.get(
        'facet_fields', {}).get('domain', [])

    analytics_facets = sequence_to_dict(analytics_facet_list)
    analytics_facets = [domain for domain in analytics_facets.items()
                        if domain[0] in active_microsites]

    results += auth_results.docs

    candidates = dict_to_object(results)

    domains = [get_domain(c.SavedSearch_feed) for c in candidates
               if hasattr(c, 'SavedSearch_feed')]
    search_facets = [(domain, domains.count(domain)) for domain in set(domains)]

    domain_facets = {}
    for domain, group in groupby(analytics_facets + search_facets,
                                 key=lambda x: x[0]):
        domain_facets[domain] = sum(item[1] for item in group)

    candidate_list = sorted(candidates,
                            key=lambda y: y.SavedSearch_created_on
                            if hasattr(y, 'SavedSearch_created_on')
                            else y.view_date,
                            reverse=True)

    context['domain_facets'] = domain_facets
    context['candidates'] = candidate_list
    context['total_candidates'] = len([x for x in groupby(
        candidate_list, key=lambda y: y.User_id)])

    if extra_context is not None:
        context.update(extra_context)
    return render_to_response(template, context,
                              context_instance=RequestContext(request))