Example #1
0
def home(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponseRedirect`` if the user is already authenticated, else ``HttpResponse``

    If the ``user`` is already authenticated, redirect them to the url that is most appropriate for their account type.
    Otherwise, render the home page with template variables:

    * *account_form* - an instance of :class:`debra.forms.ShelfAccountForm`
    """
    if request.user.is_authenticated():
        brand = request.visitor["brand"]
        if brand:
            account_helpers.intercom_track_event(
                request, "brand-viewed-blogger-landing", {})
        # if not (brand and not brand.is_subscribed):
        #     return HttpResponseRedirect(request.user.userprofile.after_login_url)

    response = render(request,
                      'pages/landing/home.html', {
                          'page': 'bloggers',
                          'landing_page': True,
                          'account_form': ShelfAccountForm()
                      },
                      context_instance=RequestContext(request))

    return response
Example #2
0
def genereate_new_report_notification(collection_id):
    from debra.models import PostAnalyticsCollection
    from debra import account_helpers
    from debra import helpers

    collection = PostAnalyticsCollection.objects.get(id=collection_id)

    now = datetime.datetime.strftime(datetime.datetime.now(), '%c')

    body = '''Started to generate a new report at {}:
                collection_id = {},
                collection_name = {},
                user = {}
            '''.format(now, collection.id, collection.name, collection.user
                       or 'No user')
    subject = 'New report for collection_id={}, {}'.format(collection.id, now)

    helpers.send_admin_email_via_mailsnake(subject, body)

    account_helpers.intercom_track_event(
        None,
        "generate-report-requested", {
            'collection_name': collection.name,
            'collection_id': collection.id,
        },
        user=collection.user)
Example #3
0
def blogger_pins(request, influencer_id):
    brand = request.visitor["brand"]
    base_brand = request.visitor["base_brand"]
    assoc_inf = account_helpers.get_associated_influencer(request.user)
    plan_name = brand.stripe_plan
    try:
        influencers_qs = Influencer.objects.prefetch_related('platform_set')
        influencer = influencers_qs.get(id=influencer_id)
    except:
        raise Http404()
    if brand:
        mongo_utils.track_query("brand-clicked-blogger-pins",
                                {'blog_url': influencer.blog_url},
                                {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(request,
                                             "brand-clicked-blogger-pins",
                                             {'blog_url': influencer.blog_url})
    elif assoc_inf:
        account_helpers.intercom_track_event(request, "blogger-view-pins",
                                             {'blog_url': influencer.blog_url})
    if request.is_ajax():
        data = feeds_helpers.pinterest_feed_json(request,
                                                 for_influencer=influencer,
                                                 default_posts="about_pins")
        data = json.dumps(data, cls=DjangoJSONEncoder)
        return HttpResponse(data, content_type="application/json")
    else:
        influencer = serializers.annotate_influencer(influencer,
                                                     request=request)

        context = {
            'influencer': influencer,
            'page': 'pins',
            'selected_tab': 'search_bloggers',
            'search_page': True,
            'type': 'all',
            'selected_tab': 'search',
            'sub_page': 'main_search',
            'shelf_user': request.visitor["user"],
            'debug': settings.DEBUG,
            'tag_id': request.GET.get('tag_id'),
            'saved_search': request.GET.get('saved_search'),
        }

        context.update(
            search_helpers.prepare_filter_params(context, plan_name=plan_name))

        return render(request, 'pages/bloggers/blogger_pins.html', context)
Example #4
0
def privacy(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` rendering the privacy page
    """

    brand = request.visitor["brand"]
    if brand:
        account_helpers.intercom_track_event(request, "brand-viewed-privacy",
                                             {})

    return render(request, 'pages/landing/privacy.html', {
        'landing_page': True,
        'nav_bar_extra_class': "plain_page_nav_bar",
    })
Example #5
0
def terms(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` rendering the terms page
    """

    return redirect('http://www.theshelf.com/terms-and-conditions/')

    brand = request.visitor["brand"]
    if brand:
        account_helpers.intercom_track_event(request, "brand-viewed-terms", {})

    return render(request, 'pages/landing/terms.html', {
        'landing_page': True,
        'nav_bar_extra_class': "plain_page_nav_bar",
    })
Example #6
0
    def create(self, request):
        # from debra.brand_helpers import bookmarking_task
        from debra import account_helpers, mongo_utils

        mongo_utils.track_visit(request)

        brand = request.visitor['base_brand']
        data = json.loads(request.body)

        # check if group with such name exists
        note, recent_tag, brand_tag_ids, _ = self._get_tag_ids(brand.id)
        tag_names = redis_cache.get_many(
            ['ig_{}'.format(tag_id) for tag_id in brand_tag_ids]).values()

        if data.get('name') in tag_names:
            return Response(
                {
                    'status': 'error',
                    'content': 'Collection with such name already exists',
                },
                status=status.HTTP_400_BAD_REQUEST)

        tag = InfluencersGroup.objects.create(
            name=data.get('name'),
            owner_brand=brand,
            creator_brand=brand,
            creator_userprofile=request.visitor['user'],
        )
        settings.REDIS_CLIENT.sadd('btags_{}'.format(brand.id), tag.id)
        # settings.REDIS_CLIENT.hset('brectags', brand.id, tag.id)

        # track
        mongo_utils.track_query("brand-create-collection", {
            'collection_name': tag.name,
        }, {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(request,
                                             "brand-create-collection", {
                                                 'collection_name': tag.name,
                                             })

        return Response({
            'id': tag.id,
            'name': tag.name,
            'selected': True,
            'type': 'tag',
        })
Example #7
0
def features(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` rendering the features page
    """

    brand = request.visitor["brand"]
    if brand:
        account_helpers.intercom_track_event(request, "brand-viewed-features",
                                             {})

    return render(request,
                  'pages/landing/features.html', {
                      'landing_page': True,
                      'page': 'features'
                  },
                  context_instance=RequestContext(request))
Example #8
0
def brand_email_mismatch(request):
    """
    brand landing page when email domain mismatch brand domain
    """

    import hashlib
    userprofile = request.user.userprofile
    hex_string = hashlib.md5(str(userprofile.id)).hexdigest()
    account_helpers.intercom_track_event(
        request, "brand-email-mismatch", {
            'email': request.user.email,
            'brand_url': request.user.userprofile.temp_brand_domain
        })
    logout(request)
    return render(request, 'pages/landing/brand_email_domain_mismatch.html', {
        'userprofile': userprofile,
        'hex_string': hex_string
    })
Example #9
0
def trigger_brand_membership_verify(request):
    """
    view called when user requests blog badge verification
    """
    userprofile = request.user.userprofile
    if not userprofile.temp_brand_domain:
        logout(request)
        return HttpResponse("verified")
    brand = get_object_or_404(
        Brands, domain_name__iexact=userprofile.temp_brand_domain)
    account_helpers.intercom_track_event(
        request, 'brand-membership-verification-requested',
        {'brand_url': brand.domain_name})
    account_helpers.verify_brand_membership.apply_async([userprofile.id],
                                                        queue="celery")
    # account_helpers.verify_brand_membership(userprofile.id)

    return HttpResponse()
Example #10
0
def del_brand_from_agency(request):
    brand = request.visitor["base_brand"]
    if not brand or not brand.is_subscribed or not brand.stripe_plan in STRIPE_AGENCY_PLANS:
        return HttpResponseForbidden()

    try:
        data = json.loads(request.body)
    except ValueError:
        data = {}

    brand_name = data.get('name')
    print "removing ", brand_name

    to_brands = models.Brands.objects.filter(name=brand_name)
    for to_brand in to_brands:
        remove_privilages = (models.UserProfileBrandPrivilages.PRIVILAGE_OWNER,
                             models.UserProfileBrandPrivilages.PRIVILAGE_CONTRIBUTOR,
                             models.UserProfileBrandPrivilages.PRIVILAGE_CONTRIBUTOR_UNCONFIRMED,
                             )
        profiles = [x.user_profile.id for x in brand.related_user_profiles.filter(
            permissions__in=remove_privilages).only('user_profile__id')]
        print profiles
        print to_brand.related_user_profiles.filter(user_profile__id__in=profiles, permissions=models.UserProfileBrandPrivilages.PRIVILAGE_AGENCY)
        to_brand.related_user_profiles.filter(
            user_profile__in=profiles, permissions=models.UserProfileBrandPrivilages.PRIVILAGE_AGENCY).delete()
        if "agency_brand" in request.session and request.session["agency_brand"] == to_brand.id:
            all_managed = request.visitor["managed_brands"]
            for managed in all_managed:
                if managed.id != to_brand.id:
                    request.session["agency_brand"] = managed.brand.id
                    break
        account_helpers.intercom_track_event(request, "brand-remove-subbrand", {
            'brand': brand.domain_name,
            'subbrand': to_brand.domain_name,
        })

    try:
        update_agency_stripe(brand)
    except:
        return HttpResponseBadRequest("Something went wrong. Probably, you're trying to use Stripe production mode through test mode user.")

    return HttpResponse()
Example #11
0
def trigger_badge_verify(request):
    """
    view called when user requests blog badge verification
    """
    if not request.user.userprofile or request.user.userprofile.blog_verified:
        return redirect('/')
    blog_url = request.user.userprofile.blog_page
    #blogger_name = request.user.userprofile.name if request.user.userprofile.name else request.user.email
    account_helpers.intercom_track_event(
        request, 'blogger-badge-verification-requested',
        {'blog_url': blog_url})
    account_helpers.verify_blog_ownership.apply_async(
        [request.user.userprofile.id], queue="celery", countdown=5 * 60)
    # account_helpers.verify_blog_ownership(request.user.userprofile.id)

    if request.is_ajax():
        return HttpResponse()
    else:
        return render(request, 'registration/badge_verify_request_sent.html',
                      {})
Example #12
0
def blogger_posts_sponsored(request, influencer_id):
    mongo_utils.track_visit(request)
    brand = request.visitor["brand"]
    base_brand = request.visitor["base_brand"]
    assoc_inf = account_helpers.get_associated_influencer(request.user)
    try:
        influencers_qs = Influencer.objects.prefetch_related('platform_set')
        influencer = influencers_qs.get(id=influencer_id)
    except:
        raise Http404()
    if not brand and assoc_inf != influencer:
        return HttpResponseForbidden()
    if brand:
        mongo_utils.track_query("brand-clicked-blogger-sponsored-posts",
                                {'blog_url': influencer.blog_url},
                                {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(
            request, "brand-clicked-blogger-sponsored-posts",
            {'blog_url': influencer.blog_url})
    elif assoc_inf:
        account_helpers.intercom_track_event(request,
                                             "blogger-view-sponsored-posts",
                                             {'blog_url': influencer.blog_url})
    if request.is_ajax():
        data = feeds_helpers.collab_feed_json(request,
                                              for_influencer=influencer,
                                              default_posts="about")
        data = json.dumps(data, cls=DjangoJSONEncoder)
        return HttpResponse(data, content_type="application/json")
    else:
        influencer = serializers.annotate_influencer(influencer,
                                                     request=request)
        return render(
            request, 'pages/bloggers/blogger_posts_sponsored.html', {
                'influencer': influencer,
                'page': 'posts_sponsored',
                'selected_tab': 'search_bloggers',
                'search_page': True,
            })
Example #13
0
def blogger_items(request, influencer_id):
    brand = request.visitor["brand"]
    base_brand = request.visitor["base_brand"]
    assoc_inf = account_helpers.get_associated_influencer(request.user)
    try:
        influencer = Influencer.objects
        influencer = influencer.prefetch_related('platform_set')
        influencer = influencer.get(id=influencer_id)
    except:
        raise Http404()
    if brand:
        mongo_utils.track_query("brand-clicked-blogger-products",
                                {'blog_url': influencer.blog_url},
                                {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(request,
                                             "brand-clicked-blogger-products",
                                             {'blog_url': influencer.blog_url})
    elif assoc_inf:
        account_helpers.intercom_track_event(request, "blogger-view-products",
                                             {'blog_url': influencer.blog_url})
    if request.is_ajax() or request.GET.get('debug'):
        data = feeds_helpers.product_feed_json(request,
                                               for_influencer=influencer)
        data = json.dumps(data, cls=DjangoJSONEncoder)
        if request.GET.get('debug'):
            return HttpResponse("<body></body>")
        return HttpResponse(data, content_type="application/json")
    else:
        influencer = serializers.annotate_influencer(influencer,
                                                     request=request)
        return render(
            request, 'pages/bloggers/blogger_items.html', {
                'influencer': influencer,
                'page': 'items',
                'selected_tab': 'search_bloggers',
                'search_page': True,
            })
Example #14
0
def blogger_blog_not_ok(request):
    """
    blogger landing page when blog is not verified
    """
    user = request.visitor["user"]
    auth_user = request.visitor["auth_user"]
    influencer = request.visitor["influencer"]
    if influencer and influencer.group_mapping.filter(
            jobs__isnull=True).exists():
        user.blog_verified = True
        user.save()
    if not user:
        return redirect('/')
    blog_url = user.blog_page
    account_helpers.intercom_track_event(request, "blogger-get-badge", {
        'email': auth_user.email,
        'blog_url': blog_url,
    })
    return render(
        request, 'pages/landing/tmp_blogger_blog_verify.html', {
            'blog_url': blog_url,
            'blog_url_stripped': blog_url_strip(blog_url) or blog_url
        })
Example #15
0
def brand_home(request, **kwargs):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` rendering the brand home page

    Render the brand home page with template variables:

    * *account_form* - an instance of :class:`debra.forms.ShelfAccountForm`
    """

    if request.user.is_authenticated():
        brand = request.visitor["brand"]
        if brand:
            account_helpers.intercom_track_event(request,
                                                 "brand-viewed-brand-landing",
                                                 {})
        return HttpResponseRedirect(request.user.userprofile.after_login_url)

    if not settings.DEBUG and kwargs.get('blog_redirection', True):
        return HttpResponseRedirect("http://theshelf.com")

    return render(request,
                  'pages/landing/brand_home.html', {
                      'landing_page':
                      True,
                      'account_form':
                      ShelfAccountForm(),
                      'login_popup_auto_open':
                      kwargs.get('login_popup_auto_open', False),
                      'brand_signup_popup_auto_open':
                      kwargs.get('brand_signup_popup_auto_open', False),
                      'blogger_signup_popup_auto_open':
                      kwargs.get('blogger_signup_popup_auto_open', False),
                      'influenity_signup_popup_auto_open':
                      kwargs.get('influenity_signup_popup_auto_open', False),
                  },
                  context_instance=RequestContext(request))
Example #16
0
def blogger_generic_posts(request, section, influencer_id, **kwargs):
    mongo_utils.track_visit(request)
    brand = request.visitor["brand"]
    base_brand = request.visitor["base_brand"]

    # parameters
    show_filters = False and brand.stripe_plan

    # get influencer from db
    try:
        influencers_qs = Influencer.objects.prefetch_related('platform_set')
        influencer = influencers_qs.get(id=influencer_id)
    except:
        raise Http404()

    # track events
    if brand:
        mongo_utils.track_query("brand-clicked-blogger-posts",
                                {'blog_url': influencer.blog_url},
                                {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(request,
                                             "brand-clicked-blogger-posts",
                                             {'blog_url': influencer.blog_url})
    elif account_helpers.get_associated_influencer(request.user):
        account_helpers.intercom_track_event(request, "blogger-view-posts",
                                             {'blog_url': influencer.blog_url})

    influencer = serializers.annotate_influencer(influencer, request=request)

    context = {
        'influencer':
        influencer,
        'page':
        normalize_posts_section_name(section),
        'selected_tab':
        'search_bloggers',
        'search_page':
        True,
        'show_filters':
        show_filters,
        'for_influencer':
        influencer.id,
        # 'posts_section': section,
        'initial_search_mode':
        normalize_posts_section_name(section),
        'init_brand':
        kwargs.get('brand_domain'),
        'type':
        'all',
        'selected_tab':
        'search',
        'sub_page':
        'main_search',
        'shelf_user':
        request.visitor["user"],
        'debug':
        settings.DEBUG,
        'tag_id':
        request.GET.get('tag_id'),
        'saved_search':
        request.GET.get('saved_search'),
        'sections':
        get_sections(
            include_all_section=kwargs.get('brand_domain') is not None),
        'blogger_page':
        True,
    }

    if show_filters:
        context.update(
            search_helpers.prepare_filter_params(context,
                                                 plan_name=brand.stripe_plan))

    return render(request, 'pages/bloggers/blogger_generic_posts.html',
                  context)
Example #17
0
def add_brand_to_agency(request):

    def set_privilages(to_brand):
        if request.visitor["user"].brand_privilages.filter(brand=to_brand).exists():
            # dont add twice and dont add self
            return True

        expand_privilages = (models.UserProfileBrandPrivilages.PRIVILAGE_OWNER,
                             models.UserProfileBrandPrivilages.PRIVILAGE_CONTRIBUTOR,
                             models.UserProfileBrandPrivilages.PRIVILAGE_CONTRIBUTOR_UNCONFIRMED,
                             )

        for related in brand.related_user_profiles.filter(permissions__in=expand_privilages):
            bp = models.UserProfileBrandPrivilages()
            bp.brand = to_brand
            bp.user_profile = related.user_profile
            bp.permissions = models.UserProfileBrandPrivilages.PRIVILAGE_AGENCY
            bp.save()
        return False

    brand = request.visitor["base_brand"]
    if not brand or not brand.is_subscribed or not brand.stripe_plan in STRIPE_AGENCY_PLANS:
        return HttpResponseForbidden()

    try:
        data = json.loads(request.body)
    except ValueError:
        data = {}

    brand_name = data.get('name')
    brand_url = data.get('url')

    brand_url = utils.domain_from_url(brand_url)
    if not helpers.is_valid_hostname(brand_url):
        return HttpResponseBadRequest("Enter URL with valid hostname.")
    print "Adding ", brand_name, brand_url

    to_brand = models.Brands.objects.filter(domain_name=brand_url)
    print to_brand
    if len(to_brand) > 0:
        print "Found single brand"
        to_brand = to_brand[0]
        if set_privilages(to_brand):
            return HttpResponseBadRequest("You can't add same brand twice and use your brand as agency sub-brand..")
        account_helpers.intercom_track_event(request, "brand-add-subbrand", {
            'brand': brand.domain_name,
            'subbrand': to_brand.domain_name,
        })
        request.session["agency_brand"] = to_brand.id
    elif not to_brand:
        print "Requested new brand"
        to_brand = models.Brands.objects.create(
            domain_name=brand_url, name=brand_name)
        to_brand.save()
        brand_helpers.create_profile_for_brand(to_brand)
        set_privilages(to_brand)
        account_helpers.intercom_track_event(request, "brand-add-subbrand", {
            'brand': brand.domain_name,
            'subbrand': to_brand.domain_name,
        })
        request.session["agency_brand"] = to_brand.id
    else:
        #@todo handle multiple brands
        pass

    try:
        update_agency_stripe(brand)
    except:
        return HttpResponseBadRequest("Something went wrong. Probably, you're trying to use Stripe production mode through test mode user.")

    return HttpResponse()
Example #18
0
def pricing(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` rendering the pricing page

    Render the pricing page with template variables:

    * *stripe_key* - the public key for the ``stripe`` payment service. If ``DEBUG`` is True, we use the ``STRIPE_TEST_PUBLISHABLE_KEY`` key, otherwise
    we use the ``STRIPE_LIVE_PUBLISHABLE_KEY`` key
    """

    current_plan = None

    base_brand = request.visitor["base_brand"]
    brand = request.visitor["brand"]
    if brand:
        account_helpers.intercom_track_event(request, "brand-viewed-pricing",
                                             {})
        slack_msg = "\n**************\nBrand = " + brand.domain_name + " User: "******"\n" + " Viewed Pricing Page"
        account_helpers.send_msg_to_slack.apply_async(
            ['brand-viewed-pricing', slack_msg], queue='celery')

    if settings.DEBUG:
        if brand and brand.is_subscribed:
            current_plan = brand.stripe_plan
    else:
        if brand and brand.is_subscribed and not brand.flag_trial_on:
            return HttpResponseRedirect(
                request.user.userprofile.after_login_url)

    admin_plan = base_brand.flag_availiable_plan

    plans = []
    if base_brand.is_agency and base_brand.flag_show_other_plans:
        plans = constants.get_agency_extra_plans()
        if admin_plan not in plans:
            plans = [admin_plan] + plans
    else:
        plans = [admin_plan]

    plans = filter(None, map(constants.PLAN_INFO.get, plans))

    if base_brand.flag_one_time_fee_on:
        for plan in plans:
            plan['hidden_button'] = True
            plan[
                'extra_text'] = "This will be charged starting next month. At this point, you'll only be charged for the One Time fee."
        other_plans = plans
        plans = [{
            'name':
            'One Time Services Contract' if base_brand.flag_services_plan else
            'One Time Setup / Service Fee',
            'amount':
            float(base_brand.flag_one_time_fee),
            'interval':
            None,
            'type':
            None,
            'interval_count':
            None,
            'one_time':
            True,
            'services_plan':
            base_brand.flag_services_plan,
            'other_plans':
            other_plans
        }]

    return render(
        request,
        'pages/landing/pricing.html', {
            'landing_page': True,
            'stripe_key': STRIPE_TEST_PUBLISHABLE_KEY
            if settings.DEBUG else STRIPE_LIVE_PUBLISHABLE_KEY,
            'current_plan': current_plan,
            'plans': plans,
        },
        context_instance=RequestContext(request))
Example #19
0
def blogger_edit(request, influencer_id):
    mongo_utils.track_visit(request)
    try:
        influencers_qs = Influencer.objects.prefetch_related('platform_set')
        influencer = influencers_qs.get(id=influencer_id)
    except:
        raise Http404()
    if not request.user.userprofile:
        print "User doesnt have userprofile"
        raise Http404()
    profile = request.user.userprofile

    assoc_inf = account_helpers.get_associated_influencer(request.user)
    if assoc_inf != influencer and not request.user.is_superuser:
        print "privilages mismatched"
        return HttpResponseForbidden()

    if assoc_inf:
        account_helpers.intercom_track_event(request,
                                             "blogger-edit-description",
                                             {'blog_url': influencer.blog_url})

    if request.is_ajax():
        edits = []

        try:
            data = json.loads(request.body)
        except ValueError:
            print "bad json"
            return HttpResponseBadRequest()

        if data.get("collaborations_modified"):
            edits.append({
                "field": "collaborations",
            })
        if data.get("ifb_modified"):
            edits.append({
                "field": "info for brand",
            })

        old_style_tags = profile.style_tags
        profile.style_tags = ",".join(
            [x.strip() for x in data.get("tags") if x])
        if old_style_tags != profile.style_tags:
            edits.append({
                "field": "style_tags",
                "from": old_style_tags,
                "to": profile.style_tags
            })

        if influencer.name != data.get("name"):
            edits.append({
                "field": "name",
                "from": influencer.name,
                "to": data.get("name")
            })
        influencer.name = data.get("name")
        if influencer.blogname != data.get("blogname"):
            edits.append({
                "field": "blogname",
                "from": influencer.blogname,
                "to": data.get("blogname")
            })
        influencer.blogname = data.get("blogname")
        if influencer.email != data.get("email"):
            edits.append({
                "field": "email",
                "from": influencer.email,
                "to": data.get("email")
            })
        influencer.email = data.get("email")
        location_edited = False
        if influencer.demographics_location_normalized != data.get("location"):
            location_edited = True
            edits.append({
                "field": "demographics_location_normalized",
                "from": influencer.demographics_location_normalized,
                "to": data.get("location")
            })
        influencer.demographics_location_normalized = data.get("location")
        if influencer.demographics_location != data.get("location"):
            edits.append({
                "field": "demographics_location",
                "from": influencer.demographics_location,
                "to": data.get("location")
            })
        influencer.demographics_location = data.get("location")
        if influencer.description != data.get("bio"):
            edits.append({
                "field": "description",
                "from": influencer.description,
                "to": data.get("bio")
            })
        influencer.description = data.get("bio")
        if influencer.collaboration_types != data.get("collaboration_types"):
            edits.append({
                "field": "collaboration_types",
                "from": influencer.collaboration_types,
                "to": data.get("collaboration_types")
            })
        influencer.collaboration_types = data.get("collaboration_types")
        if influencer.how_you_work != data.get("how_you_work"):
            edits.append({
                "field": "how_you_work",
                "from": influencer.how_you_work,
                "to": data.get("how_you_work")
            })
        influencer.how_you_work = data.get("how_you_work")

        influencer.collaborations.all().delete()
        rev_dict_ictype = dict([
            (x[1], x[0]) for x in InfluencerCollaborations.COLLABORATION_TYPES
        ])
        for collab in data.get("collaborations", []):
            post_url = collab.get("post_url", '')
            if not post_url.startswith("http://") and not post_url.startswith(
                    "https://"):
                post_url = "http://" + post_url
            brand_url = collab.get("brand_url", '')
            if not brand_url.startswith(
                    "http://") and not brand_url.startswith("https://"):
                brand_url = "http://" + brand_url
            timestamp = collab.get('timestamp')
            try:
                timestamp = datetime.strptime(
                    timestamp.split('T')[0], "%Y-%m-%d")
                timestamp = timestamp.strftime('%x')
            except (AttributeError, ValueError):
                pass
            try:
                influencer.collaborations.create(
                    brand_name=collab.get("brand_name"),
                    brand_url=brand_url,
                    post_url=post_url,
                    details=collab.get("details"),
                    timestamp=timestamp,
                    collaboration_type=rev_dict_ictype.get(
                        collab.get('collab_type')))
            except IntegrityError:
                continue

        influencer.infos_for_brands.all().delete()

        ifb_enabled = data.get("info_for_brands", {}).get("enabled", {})
        ifb_range_max = data.get("info_for_brands", {}).get("range_max", {})
        ifb_range_min = data.get("info_for_brands", {}).get("range_min", {})
        ifb_info = data.get("info_for_brands", {}).get("info", {})

        for info_type, is_enabled in ifb_enabled.iteritems():
            if is_enabled:
                range_min = ifb_range_min.get(info_type)
                range_max = ifb_range_max.get(info_type)
                try:
                    range_min = float(range_min)
                except:
                    range_min = None
                try:
                    range_max = float(range_max)
                except:
                    range_max = None
                info = ifb_info.get(info_type)
                influencer.infos_for_brands.create(range_min=range_min,
                                                   range_max=range_max,
                                                   details=info,
                                                   info_type=info_type)

        try:
            validated_on = json.loads(influencer.validated_on)
        except (ValueError, TypeError):
            validated_on = []
        validated_on.append(ADMIN_TABLE_INFLUENCER_SELF_MODIFIED)
        validated_on = list(set(validated_on))
        influencer.validated_on = json.dumps(validated_on)

        influencer.save()
        profile.save()

        if location_edited:
            geocoding.normalize_location.apply_async((influencer.id, ))

        if edits:
            mongo_utils.influencer_log_edits(influencer.id, edits)

        request.visitor.flush()
        return HttpResponse()
    else:

        info_for_brands = {
            "info": {},
            "range_max": {},
            "enabled": {},
            "range_min": {}
        }

        collaborations = []

        for info in influencer.infos_for_brands.all():
            info_for_brands["enabled"][info.info_type] = True
            info_for_brands["range_min"][info.info_type] = info.range_min
            info_for_brands["range_max"][info.info_type] = info.range_max
            info_for_brands["info"][info.info_type] = info.details

        for collab in influencer.collaborations.all():
            collab_data = {
                "brand_name":
                collab.brand_name,
                "brand_url":
                collab.brand_url,
                "post_url":
                collab.post_url,
                "details":
                collab.details,
                "timestamp":
                collab.timestamp,
                "collab_type":
                dict(InfluencerCollaborations.COLLABORATION_TYPES).get(
                    collab.collaboration_type),
            }
            collaborations.append(collab_data)

        profile_data = {
            "collaborations": collaborations,
            "info_for_brands": info_for_brands,
            "tags": profile.style_tags.split(","),
            "name": influencer.name,
            "blogname": influencer.blogname,
            "email": influencer.email,
            "location": influencer.demographics_location_normalized,
            "bio": influencer.description,
            "collaboration_types": influencer.collaboration_types,
            "how_you_work": influencer.how_you_work
        }

        return render(
            request, 'pages/bloggers/blogger_edit.html', {
                'influencer': influencer,
                'page': 'edit',
                'selected_tab': 'search_bloggers',
                'profile_data': json.dumps(profile_data,
                                           cls=DjangoJSONEncoder),
                'social': search_helpers.get_social_data(influencer, profile),
                'collab_types': InfluencerCollaborations.COLLABORATION_TYPES,
                'sections': get_sections(),
                'blogger_page': True,
            })
Example #20
0
def post_activation(request, user):
    print "OK, here: in post_activation_redirect for %r " % user
    user_prof = user.userprofile
    buy_after = False
    if request:
        if "buy_after" in request.session and request.session["buy_after"]:
            buy_after = True


    if user_prof.temp_brand_domain:
        account_helpers.intercom_track_event(request, "brand-email-verified", {
            'email': user.email,
            'brand_url': user_prof.temp_brand_domain,
            'date_joined': datetime.datetime.now().strftime("%c")
        }, user=user)

        print "ok, we are brand related"
        ####This handles user's who claim to be working for a given brand
        brand = Brands.objects.filter(domain_name__iexact=user_prof.temp_brand_domain)
        if not brand:
            log.error("Connecting user %s to non existing brand %s !" % (user, user_prof.temp_brand_domain))
        else:
            brand = brand[0]

        ## if user's email belongs to the domain name of the brand, then only we allow this association
        if brand and helpers.check_if_email_matches_domain(user.email, brand.domain_name):
            brand_helpers.sanity_checks(brand)
            user_prof.temp_brand_domain = None
            user_prof.save()

            brand_helpers.connect_user_to_brand(brand, user_prof)
            account_helpers.intercom_track_event(None, "brand-ownership-verified", {
                'email': user.email,
                'brand_url': brand.domain_name,
                'manual': False,
                'success': True,
            }, user)

            # change it to celery before push to production
            if not settings.DEBUG:
                account_helpers.notify_admins_about_brand_email_match.apply_async([user_prof, brand], queue="celery")
                #account_helpers.notify_admins_about_brand_email_match(user_prof, brand)
            if request:
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                if buy_after:
                    return reverse("debra.account_views.auto_buy"), (), {}
                return reverse("debra.account_views.email_verified_brand"), (), {}
        else:
            reason = "%s doesn't exist" % user_prof.temp_brand_domain if not brand else "domain mismatch between %s and %s" % (user.email, brand.domain_name)

            # now notify admins so that they can reach out to the brand user
            account_helpers.notify_admins_about_brand_email_mismatch.apply_async([user_prof], queue="celery")

            pass
            ## basically login as the user with no brand associated with you

    if user_prof.blog_name and user_prof.blog_page:
        account_helpers.intercom_track_event(request, "blogger-email-verified", {
            'email': user.email,
            'blog_url': user_prof.blog_page,
            'date_joined': datetime.datetime.now().strftime("%c")
        }, user=user)
        # intercom_user = user_prof.get
        user_prof.update_intercom()
        print "[BLOGGER: EMAIL VERIFIED] %r %r" % (user_prof, user_prof.blog_page)


    if request:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        if buy_after:
            return reverse("debra.account_views.auto_buy"), (), {}
        print "ok, redirecting to %s " % user.userprofile.after_login_url
        return user.userprofile.after_login_url, (), {}
Example #21
0
def blogger_about(request, influencer_id):
    mongo_utils.track_visit(request)

    mongo_utils.influencer_profile_viewed(influencer_id)

    try:
        influencers_qs = Influencer.objects.prefetch_related('platform_set')
        influencer = influencers_qs.get(id=influencer_id)
    except:
        raise Http404()
    profile = influencer.shelf_user and influencer.shelf_user.userprofile or None

    if influencer.blacklisted:
        from debra.account_views import access_locked_page

        return access_locked_page(request,
                                  "Access is locked by administration.")

    assoc_inf = account_helpers.get_associated_influencer(request.user)
    if assoc_inf == influencer:
        profile_owner = True
        add_email = True
    else:
        profile_owner = False

    brand = request.visitor["brand"]
    base_brand = request.visitor["base_brand"]

    influencer_data = search_helpers.get_influencer_json(
        influencer,
        include_photos=True,
        long_post_content=True,
        request=request)
    try:
        influencer_data['profile']['items_list'] = influencer_data['profile'][
            'items']
    except KeyError:
        pass
    influender_profile_id = influencer_data.get("profile", {}).get("id", None)
    add_email = False
    if base_brand and base_brand.is_subscribed:
        if base_brand.stripe_plan in STRIPE_EMAIL_PLANS:
            add_email = True
        if base_brand.stripe_plan in STRIPE_COLLECTION_PLANS:
            influencer = Influencer.objects.get(id=influencer_id)
            influencer_data["can_favorite"] = True
            influencer_data["is_favoriting"] = brand.influencer_groups.filter(
                influencers_mapping__influencer__id=influencer_id).exists()
    else:
        influencer_data["can_favorite"] = False

    if add_email:
        influencer_data["email"] = False
        emails = influencer.email
        if emails:
            splited = emails.split()
            if splited:
                influencer_data["email"] = splited[0]

    if brand:
        mongo_utils.track_query("brand-clicked-blogger-about",
                                {'blog_url': influencer.blog_url},
                                {"user_id": request.visitor["auth_user"].id})

        account_helpers.intercom_track_event(request,
                                             "brand-clicked-blogger-about",
                                             {'blog_url': influencer.blog_url})
    elif assoc_inf:
        account_helpers.intercom_track_event(request, "blogger-view-about",
                                             {'blog_url': influencer.blog_url})

    influencer = serializers.annotate_influencer(influencer, request=request)

    return render(
        request, 'pages/bloggers/blogger_about.html', {
            'influencer':
            influencer,
            'page':
            'about',
            'posts':
            json.dumps(influencer_data.get("posts"), cls=DjangoJSONEncoder),
            'influencer_data':
            influencer_data,
            'style_tags':
            profile and profile.style_tags and profile.style_tags.split(","),
            'relfashion_stats':
            json.dumps(influencer_data.get("relfashion_stats"),
                       cls=DjangoJSONEncoder),
            'category_stats':
            json.dumps(influencer_data.get("category_stats"),
                       cls=DjangoJSONEncoder),
            'popularity_stats':
            json.dumps(influencer_data.get("popularity_stats"),
                       cls=DjangoJSONEncoder),
            'popularity_sums':
            json.dumps(influencer_data.get("popularity_sums"),
                       cls=DjangoJSONEncoder),
            'STRIPE_PLAN_STARTUP':
            STRIPE_PLAN_STARTUP,
            'STRIPE_PLAN_BASIC':
            STRIPE_PLAN_BASIC,
            'STRIPE_EMAIL_PLANS':
            STRIPE_EMAIL_PLANS,
            'COLLABORATION_TYPES':
            InfluencerCollaborations.COLLABORATION_TYPES,
            'profile_owner':
            profile_owner,
            'selected_tab':
            'search_bloggers',
            'search_page':
            True,
            'sections':
            get_sections(),
            'blogger_page':
            True,
        })