Beispiel #1
0
def INTERCOM_CUSTOM_DATA(up):
    from debra import account_helpers
    brand = account_helpers.get_associated_brand(up)
    has_brand = brand is not None
    influencer = account_helpers.get_associated_influencer(up)
    has_influencer = influencer is not None
    regprof = None
    try:
        regprof = up.user.registrationprofile_set.all()[0]
    except:
        pass

    company_data = None
    if has_brand:
        company_data = brand.get_intercom_company_data()

    data = {
        "is_blogger":
        bool(up.blog_page),
        "is_brand":
        has_brand or bool(up.temp_brand_domain),
        "blogger_is_active":
        up.user.is_active if up.blog_page else None,
        "brand_stripe_customer_created_at":
        brand.flag_stripe_customer_created if brand else None,
        "has_blog_verified":
        up.blog_verified,
        "has_brand_verified":
        has_brand,
        "has_influencer":
        has_influencer,
        "blog_url":
        up.blog_page,
        "blog_name":
        up.blog_name,
        "ready_to_invite":
        influencer is not None and influencer.ready_to_invite or False,
        "activation_key":
        regprof.activation_key if regprof else None,
        "expiration_days":
        settings.ACCOUNT_ACTIVATION_DAYS,
        "brand_url":
        brand.domain_name if brand else up.temp_brand_domain,
        "brand_name":
        company_data.get('name') if company_data else None,
        "plan":
        company_data.get('plan') if company_data else None,
        "monthly_spend":
        company_data.get('monthly_spend') if company_data else None,
    }
    return data
Beispiel #2
0
def shelf_login(request):
    """
    :param request: ``HttpRequest`` instance
    :return: ``HttpResponse`` instance

    If the login attempt was successful, return an ``HttpResponse`` with ``status=200`` and ``content`` equals a ``json`` object containing keys:

    * *url* - the url to go to after a successful login, this defaults to the url provided as a ``next`` parameter
    in the ``GET`` request, but if that isn't provided, it uses the url set in the :class:`debra.models.UserProfile` instance
    given by ``valid_user.userprofile.after_login_url``

    if the login attempt was not successful, return an ``HttpResponse`` with ``status=500`` and ``content`` equals a ``json`` object containing keys:

    * *errors* - an array of errors given by ``form.errors``

    """
    request.invalidate_visitor = True
    form = ShelfLoginForm(data=request.POST)
    if form.is_valid():
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']
        next_url = request.GET.get('next', None)

        valid_user = authenticate(username=email, password=password)
        if valid_user.username.startswith(
                "theshelf") and valid_user.username.endswith(".toggle"):
            return HttpResponseForbidden()
        login(request, valid_user)
        brand = account_helpers.get_associated_brand(valid_user)
        if brand and brand.is_agency:
            managed = account_helpers.get_managed_brand(valid_user)
            if managed:
                request.session["agency_brand"] = managed[0].brand.id
        return HttpResponse(status=200,
                            content=json.dumps({
                                'url':
                                next_url if next_url else
                                valid_user.userprofile.after_login_url
                            }))
    else:
        return HttpResponse(status=403,
                            content=json.dumps({'errors': form.errors}))
Beispiel #3
0
def track_visit_task(re_usr_id):
    """
    takes request.visitor instance and saves visit fact
    """
    from debra import models
    from debra import account_helpers

    collection = get_visitor_tracking_col()
    if not collection:
        log.error("No collection to track visit")
        return
    user_id = "anonymous"
    user_email = "anonymous"
    user = None
    brand = None
    if re_usr_id:
        user = models.User.objects.get(id=re_usr_id)
        user_id = re_usr_id
        user_email = user.email
        brand = account_helpers.get_associated_brand(user)

    key_data = {
        'user_id': user_id,
    }
    output_data = {
        '$set': {
            'email': user_email,
            'meta': user and INTERCOM_CUSTOM_DATA(user.userprofile) or None,
            'brand_meta': brand and brand.get_intercom_company_data() or None,
            'last_visit': time.time(),
        },
        '$inc': {
            'visits': 1
        }
    }
    collection.update(key_data, output_data, upsert=True)
Beispiel #4
0
def brand_payment(request):
    """
    process a payment for a brand
    takes requests body as json with following fields
    - stripeToken
    - promotionCode
    - plan  - plan name, all plans are listed under :mod:`debra.constants`

    - amount - obsolete
    """
    import datetime
    import time
    request.invalidate_visitor = True
    user = request.user
    user_prof = user.userprofile
    brand = account_helpers.get_associated_brand(user_prof)

    do_association = False
    #if the user doesnt have a brand, nothing to do but return
    if not brand:
        print "No brand privilages"
        try:
            brand = Brands.objects.get(
                domain_name__iexact=user_prof.temp_brand_domain)
        except Brands.DoesNotExist:
            mail_admins(
                "No brand for user: %i during autoassociation in payment view"
                % (user_prof.id, ))
            return HttpResponseBadRequest(content=json.dumps({
                'error':
                'We had some trouble with associating brand to your account, no charge was made.'
            }))
        except MultipleObjectsReturned:
            mail_admins(
                "Multiple brands for user: %i during autoassociation in payment view"
                % (user_prof.id, ))
            return HttpResponseBadRequest(content=json.dumps({
                'error':
                'We had some trouble with associating brand to your account, no charge was made.'
            }))

        if brand.stripe_id:
            owner = brand.related_user_profiles.get(
                permissions=UserProfileBrandPrivilages.PRIVILAGE_OWNER
            ).user_profile
            msg = "Brand you claimed you are member is already registered and your email doesnt seems to be from its domain. Please contact %s to get access to account."
            return HttpResponseBadRequest(
                content=json.dumps({'error': msg % owner.name}))

        do_association = True

    try:
        data = json.loads(request.body)

    except ValueError:
        #old code fallback
        data = {}

    token = data.get('stripeToken')
    promo = data.get('promotionCode')
    plan = data.get('plan')
    one_time = bool(int(data.get('one_time')))
    print "signup to", plan
    log.error('Signup to {}'.format(plan))
    payment_amount = int(data.get('amount', Brands.SUBSCRIPTION_COST))

    if not token:
        #old code fallback
        token = request.POST['stripeToken']
        payment_amount = int(
            request.POST.get('amount', Brands.SUBSCRIPTION_COST))
        plan = "Startup"
    try:
        customer_id = brand.stripe_id

        # if the brand doesn't have a stripe id, create one now (this should happen when their subscription starts)
        if not customer_id:
            print "Creating new stripe customer"
            log.error('Creating new stripe customer')
            try:
                customer_id = stripe.Customer.create(
                    card=token,
                    description='{brand} customer created'.format(
                        brand=brand.name)).id
            except Exception:
                log.exception('Payment error')
                return HttpResponseBadRequest(
                    content=json.dumps({'error': 'Payment processing error'}))
            # print "Success"
            log.error('Success')
            brand.stripe_id = customer_id
            brand.save()

        customer = stripe.Customer.retrieve(customer_id)

        is_new_subscription = any([
            one_time,
            not customer.subscriptions.data,
            customer.subscriptions.data
            and customer.subscriptions.data[0].plan != plan,
        ])

        if one_time:
            try:
                stripe.Charge.create(
                    amount=payment_amount * 100,
                    currency="usd",
                    customer=customer_id,
                    description="{brand} with email {email}".format(
                        brand=brand.name, email=user.email))
            except stripe.error.CardError:
                return HttpResponseBadRequest(
                    content=json.dumps({'error': 'Payment processing error'}))
        elif customer.subscriptions.data:
            #remove existing subscriptions if any (plan change)
            # print "Replace subscriptions"
            log.error('Replace subscriptions, len={}, data:{}'.format(
                len(customer.subscriptions.data), customer.subscriptions.data))
            sub = customer.subscriptions.data[0]
            log.error('Last sub: {}'.format(sub))
            sub.plan = plan
            if promo:
                sub.coupon = promo
            sub.save()
            if not promo:
                try:
                    sub.delete_discount()
                    customer.save()
                except Exception:
                    pass
            log.error('Sub updated: {}'.format(sub))
        else:
            # print "New subscription"
            log.error('New subsciption, promo: '.format(promo))
            try:
                if promo:
                    customer.subscriptions.create(plan=plan, coupon=promo)
                else:
                    customer.subscriptions.create(plan=plan)
            except Exception:
                brand.stripe_id = None
                brand.is_subscribed = False
                brand.save()
                log.exception('Payment error')
                return HttpResponseBadRequest(
                    content=json.dumps({'error': 'Payment processing error'}))

        # save payment amount
        brand.flag_last_payment_amount = payment_amount
        brand.flag_stripe_customer_created = time.mktime(
            datetime.datetime.now().timetuple())

        # make sure brand is not blacklisted
        brand.blacklisted = False

        # make sure brand is not suspended due to payment
        if is_new_subscription and brand.flag_suspended and brand.flag_suspend_reason == 'stripe_plan_deleted':
            brand.flag_suspended = False
            brand.flag_suspend_reason = None

        brand.save()

        user_prof.update_intercom()

        log.error('Success')
        mp.track(
            user_prof.user.email,
            'Subscribed',
            {
                'brand_url': brand.domain_name,
                'amount': payment_amount,  # payment_amount is in cents
                'promocode': promo,
            })
        # stripe.Charge.create(
        #   amount=payment_amount, # amount in cents
        #   currency="usd",
        #   customer=customer_id,
        #   description="{brand} with email {email}".format(brand=brand.name, email=user.email)
        # )

        if do_association:
            print "Late association with brand"
            brand_helpers.sanity_checks(brand)
            user_prof.temp_brand_domain = None
            user_prof.save()
            brand_helpers.connect_user_to_brand(brand, user_prof)

        print "Refreshing stripe data"
        log.error('Refreshing stripe data')
        brand.refresh_stripe_data()

        brand = Brands.objects.get(id=brand.id)
        if brand.is_subscribed:
            print "All good"
        else:
            print "Brand is still not subscribed?"
        if one_time:
            if request.is_ajax():
                return HttpResponse(
                    status=200,
                    content=json.dumps(
                        {'next': reverse("debra.search_views.main_search")}))
            else:
                return redirect(reverse("debra.search_views.main_search"))
        else:
            if request.is_ajax():
                return HttpResponse(
                    status=200,
                    content=json.dumps({
                        'next':
                        reverse("debra.account_views.plan_changed_brand",
                                args=(map_plan_names(plan.lower()), ))
                    }))
            else:
                return redirect(
                    reverse("debra.account_views.plan_changed_brand",
                            args=(map_plan_names(plan.lower()), )))
    except stripe.CardError:
        brand.stripe_id = None
        brand.is_subscribed = False
        brand.save()
        # The card has been declined
        return HttpResponseBadRequest(
            content=json.dumps({'error': 'credit card has been declined'}))
    except stripe.InvalidRequestError:
        return HttpResponseBadRequest(
            content=json.dumps({'error': 'promotion code is invalid'}))
Beispiel #5
0
 def get_base_brand(self):
     user = self["user"]
     if user:
         return account_helpers.get_associated_brand(user)
     else:
         return None