Exemplo n.º 1
0
def get_user_profile(user):
    """ Returns user profile. Creates one if needed """
    if not (user and user.is_authenticated()):
        return None
    pr = cache.get("users_profile:auth_user=%s" % user.id, None)
    if pr:
        return pr
    pr = get_profile_by_email_or_phone(user.username)
    if not pr:
        pr = Profile.objects.filter(user=user).order_by("id")[:2]
        if len(pr) > 1:
            fb_log.info("Multiple profiles for user: %s" % user.username)
        if pr:
            pr = pr[0]
        if not pr:
            pr = Profile(user=user)
            pr.created_on = datetime.now()
            pr.save()
            if is_valid_email(user.username):
                try:
                    email = Email(email=user.username, user=pr, type="primary")
                    email.save()
                except:
                    pass
            if is_valid_mobile(user.username):
                try:
                    phone = Phone(phone - user.username, user=pr, type="primary")
                    phone.save()
                except:
                    pass
    cache.set("users_profile:auth_user=%s" % user.id, pr)
    return pr
Exemplo n.º 2
0
def get_user_profile(user):
    ''' Returns user profile. Creates one if needed '''
    if not (user and user.is_authenticated()):
        return None
    pr = cache.get('users_profile:auth_user=%s' % user.id, None)
    if pr:
        return pr
    pr = get_profile_by_email_or_phone(user.username)
    if not pr:
        pr = Profile.objects.filter(user=user).order_by('id')[:2]
        if len(pr) > 1:
            fb_log.info('Multiple profiles for user: %s' % user.username)
        if pr:
            pr = pr[0]
        if not pr:
            pr = Profile(user=user)
            pr.created_on = datetime.now()
            pr.save()
            if is_valid_email(user.username):
                try:
                    email = Email(email=user.username, user=pr, type='primary')
                    email.save()
                except:
                    pass
            if is_valid_mobile(user.username):
                try:
                    phone = Phone(phone - user.username,
                                  user=pr,
                                  type='primary')
                    phone.save()
                except:
                    pass
    cache.set('users_profile:auth_user=%s' % user.id, pr)
    return pr
Exemplo n.º 3
0
def create_user(username, email_id="", password=None, first_name="", last_name=""):
    """ This function called for new user sign up on p. interface. Thus username should be a valid phone number."""
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            usr = User(username=username, email="")
            if password is None or password == "":
                # use set_unusable_password to allow user to set his password in future
                usr.set_unusable_password()
            else:
                usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            profile = Profile(
                user=usr, created_on=datetime.now(), primary_phone="", primary_email="", secondary_email=""
            )
            if first_name and last_name:
                profile.full_name = "%s %s" % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type="primary")
            phone.is_verified = True
            phone.verified_on = datetime.now()
            phone.save()
        except Exception, e:
            log.exception("Error create_user username: %s  Exception: %s" % (username, repr(e)))
            return None, None
Exemplo n.º 4
0
def get_or_create_user(username,
                       email_id='',
                       password=None,
                       first_name='',
                       last_name=''):
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            phone = Phone.objects.get(phone=username)
            profile = phone.user
            usr = profile.user
        except Phone.DoesNotExist:
            try:
                usr = User.objects.get(username=username)
            except User.DoesNotExist:
                usr = User(username=username, email='')
                if password is None or password == '':
                    #use set_unusable_password to allow user to set his password in future
                    usr.set_unusable_password()
                else:
                    usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            try:
                profile = Profile.objects.get(user=usr)
            except Profile.DoesNotExist:
                profile = Profile(user=usr,
                                  created_on=datetime.now(),
                                  primary_phone='',
                                  primary_email='',
                                  secondary_email='')
                profile.full_name = '%s %s' % (first_name, last_name)
            if first_name and last_name:
                profile.full_name = '%s %s' % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type='primary')
            phone.save()
        except Exception, e:
            log.exception('Error get_or_create_user %s' % repr(e))
            return None, None
Exemplo n.º 5
0
def get_or_create_user(username, email_id="", password=None, first_name="", last_name=""):
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            phone = Phone.objects.get(phone=username)
            profile = phone.user
            usr = profile.user
        except Phone.DoesNotExist:
            try:
                usr = User.objects.get(username=username)
            except User.DoesNotExist:
                usr = User(username=username, email="")
                if password is None or password == "":
                    # use set_unusable_password to allow user to set his password in future
                    usr.set_unusable_password()
                else:
                    usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            try:
                profile = Profile.objects.get(user=usr)
            except Profile.DoesNotExist:
                profile = Profile(
                    user=usr, created_on=datetime.now(), primary_phone="", primary_email="", secondary_email=""
                )
                profile.full_name = "%s %s" % (first_name, last_name)
            if first_name and last_name:
                profile.full_name = "%s %s" % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type="primary")
            phone.save()
        except Exception, e:
            log.exception("Error get_or_create_user %s" % repr(e))
            return None, None
Exemplo n.º 6
0
def create_user(username,
                email_id='',
                password=None,
                first_name='',
                last_name=''):
    ''' This function called for new user sign up on p. interface. Thus username should be a valid phone number.'''
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            usr = User(username=username, email='')
            if password is None or password == '':
                #use set_unusable_password to allow user to set his password in future
                usr.set_unusable_password()
            else:
                usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            profile = Profile(user=usr,
                              created_on=datetime.now(),
                              primary_phone='',
                              primary_email='',
                              secondary_email='')
            if first_name and last_name:
                profile.full_name = '%s %s' % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type='primary')
            phone.is_verified = True
            phone.verified_on = datetime.now()
            phone.save()
        except Exception, e:
            log.exception('Error create_user username: %s  Exception: %s' %
                          (username, repr(e)))
            return None, None
Exemplo n.º 7
0
def register_for_deals(request):
    form = FBRegisterForm()
    if request.method == "POST":
        form = FBRegisterForm(request.POST)
        error = ""
        if form.is_valid():
            f = form.cleaned_data
            email_id = f["email"]
            mobile_no = f["mobile"]

            user_info = get_user_by_email_or_mobile(email_id, mobile_no)
            email_user, phone_user, email_alert_on, sms_alert_on = user_info

            if not email_user and not phone_user:
                # new user
                user = User.objects.create_user(email_id, email_id, None)
                user.first_name = f["name"]
                user.save()

                profile = Profile(user=user, full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile, type="primary", email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone

            if not email_user and phone_user:
                # user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user, type="primary", email=email_id)
                email.save()
                email_alert_on = email

            if not phone_user and email_user:
                # user with email already exist, update his phone number only
                phone = Phone(user=email_user, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if f["name"]:
                u_name = f["name"][0].upper() + f["name"][1:]
            else:
                u_name = None
            utils.subscribe_send_email(request, email_id, u_name)
            utils.subscribe_send_sms(mobile_no)
            try:
                newsletter = NewsLetter.objects.get(newsletter="DailyDeals", client=request.client.client)
                existing_subscription = DailySubscription.objects.filter(
                    newsletter=newsletter, sms_alert_on=sms_alert_on, email_alert_on=email_alert_on
                )
                if existing_subscription:
                    return HttpResponse(simplejson.dumps(dict(status="ok", msg="subscribed")))
                else:
                    subscribe = DailySubscription()
                    subscribe.newsletter = newsletter
                    subscribe.sms_alert_on = sms_alert_on
                    subscribe.email_alert_on = email_alert_on
                    subscribe.save()
                    return HttpResponse(simplejson.dumps(dict(status="ok", msg="subscribed")))
            except NewsLetter.DoesNotExist:
                return HttpResponse(simplejson.dumps(dict(status="ok", msg="newsletter does not exists")))

        else:
            errors = []
            # we are restricting to on error per field.
            for e in form["email"].errors[:1]:
                errors.append(e)
            for e in form["mobile"].errors[:1]:
                errors.append(e)
            return HttpResponse(simplejson.dumps(dict(status="failed", error=errors)))

    return render_to_response("fb/popup.html", {"form": form}, context_instance=RequestContext(request))
Exemplo n.º 8
0
def subscribe_email_link(request, alliance):
    form = FBRegisterForm()
    affiliate_name = alliance
    try:
        affiliate_subscription = SubscriptionLink.objects.get(path="/" + affiliate_name)
    except SubscriptionLink.DoesNotExist:
        raise Http404
    affiliate_logo = affiliate_subscription.affiliate.logo
    affiliate_text = affiliate_subscription.affiliate.text
    newsletter = affiliate_subscription.newsletter

    if request.method == "POST":
        form = FBRegisterForm(request.POST)
        error = ""
        already_subscribed = False
        if form.is_valid():
            f = form.cleaned_data
            email_id = f["email"]
            mobile_no = f["mobile"]
            name = f["name"]
            email_user, phone_user, email_alert_on, sms_alert_on = get_user_by_email_or_mobile(
                email_id, mobile_no
            )  # User.objects.get(username = mobile_no)
            if not email_user and not phone_user:  # new user
                user = User.objects.create_user(email_id, email_id, None)
                user.first_name = f["name"]
                user.save()

                profile = Profile(user=user, full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile, type="primary", email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if not email_user and phone_user:  # user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user, type="primary", email=email_id)
                email.save()
                email_alert_on = email
            if not phone_user and email_user:  # user with email already exist, update his phone number only
                phone = Phone(user=email_user, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if email_user and phone_user and email_user != phone_user:  # phone user and email user are different
                pass

            existing_subscription = DailySubscription.objects.filter(
                newsletter=newsletter,
                sms_alert_on=sms_alert_on,
                email_alert_on=email_alert_on,
                source="/" + affiliate_name,
            )
            if not existing_subscription:
                subscribe = DailySubscription()
                subscribe.newsletter = newsletter
                subscribe.sms_alert_on = sms_alert_on
                subscribe.email_alert_on = email_alert_on
                subscribe.source = "/" + affiliate_name
                subscribe.save()
            else:
                already_subscribed = True
                return render_to_response(
                    "fb/subscribed.html",
                    {"affiliate_name": affiliate_name, "already_subscribed": already_subscribed},
                    context_instance=RequestContext(request),
                )

            total_coupon_codes, text = assign_coupons(affiliate_subscription.affiliate, email_alert_on, sms_alert_on)
            if alliance == "icici":
                return render_icici_products(request, total_coupon_codes)
            if email_alert_on:
                send_coupons_by_email(total_coupon_codes, affiliate_subscription.affiliate, email_alert_on)

            if sms_alert_on:
                sms_text = text
                sms = SMS()
                sms.text = sms_text
                sms.to = sms_alert_on.phone
                sms.send()

            return render_to_response(
                "fb/discount.html",
                {
                    "affiliate": affiliate_subscription.affiliate,
                    "coupon_codes": total_coupon_codes,
                    "already_subscribed": already_subscribed,
                },
                context_instance=RequestContext(request),
            )
        else:
            return render_to_response(
                "fb/register_for_deals.html",
                {"form": form, "affiliate_logo": affiliate_logo, "affiliate_text": affiliate_text},
                context_instance=RequestContext(request),
            )

    else:
        return render_to_response(
            "fb/register_for_deals.html",
            {"form": form, "affiliate_logo": affiliate_logo, "affiliate_text": affiliate_text},
            context_instance=RequestContext(request),
        )
Exemplo n.º 9
0
def register_for_deals(request):
    form = FBRegisterForm()
    if request.method == 'POST':
        form = FBRegisterForm(request.POST)
        error = ''
        if form.is_valid():
            f = form.cleaned_data
            email_id = f['email']
            mobile_no = f['mobile']

            user_info = get_user_by_email_or_mobile(email_id, mobile_no)
            email_user, phone_user, email_alert_on, sms_alert_on = user_info

            if not email_user and not phone_user:
                #new user
                user = User.objects.create_user(email_id, email_id, None)
                user.first_name = f['name']
                user.save()

                profile = Profile(user=user, full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile, type='primary', email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile, type='primary', phone=mobile_no)
                phone.save()
                sms_alert_on = phone

            if not email_user and phone_user:
                # user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user,
                                  type='primary',
                                  email=email_id)
                email.save()
                email_alert_on = email

            if not phone_user and email_user:
                # user with email already exist, update his phone number only
                phone = Phone(user=email_user, type='primary', phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if f['name']:
                u_name = f['name'][0].upper() + f['name'][1:]
            else:
                u_name = None
            utils.subscribe_send_email(request, email_id, u_name)
            utils.subscribe_send_sms(mobile_no)
            try:
                newsletter = NewsLetter.objects.get(
                    newsletter='DailyDeals', client=request.client.client)
                existing_subscription = DailySubscription.objects.filter(
                    newsletter=newsletter,
                    sms_alert_on=sms_alert_on,
                    email_alert_on=email_alert_on)
                if existing_subscription:
                    return HttpResponse(
                        simplejson.dumps(dict(status='ok', msg='subscribed')))
                else:
                    subscribe = DailySubscription()
                    subscribe.newsletter = newsletter
                    subscribe.sms_alert_on = sms_alert_on
                    subscribe.email_alert_on = email_alert_on
                    subscribe.save()
                    return HttpResponse(
                        simplejson.dumps(dict(status='ok', msg='subscribed')))
            except NewsLetter.DoesNotExist:
                return HttpResponse(
                    simplejson.dumps(
                        dict(status='ok', msg='newsletter does not exists')))

        else:
            errors = []
            # we are restricting to on error per field.
            for e in form['email'].errors[:1]:
                errors.append(e)
            for e in form['mobile'].errors[:1]:
                errors.append(e)
            return HttpResponse(
                simplejson.dumps(dict(status='failed', error=errors)))

    return render_to_response('fb/popup.html', {'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 10
0
Arquivo: fb.py Projeto: daasara/riba
def subscribe_email_link(request, alliance_name=None):
    form = FBRegisterForm()
    url = request.get_full_path()
    if not alliance_name:
        raise Http404
    else:
        affiliate_name = alliance_name.strip()
    try:
        affiliate_subscription = SubscriptionLink.objects.get(path='/'+affiliate_name)
    except:
        raise Http404
    affiliate = affiliate_subscription.affiliate
    affiliate_logo = affiliate.logo
    affiliate_text = affiliate.text
    newsletter = affiliate_subscription.newsletter
    do_post = True
    show_avail_coupon = affiliate.is_coupon_avail
    if affiliate_name == "afaqs":
        do_post = False
    errors = []
    welcome_html = 'fb/register_for_deals.html'
    special_offers = ['gift']
    if affiliate_name in special_offers:
        welcome_html = 'fb/register_for_special_offers.html'
    if request.method == 'POST':
        form = FBRegisterForm(request.POST)
        error=''
        already_subscribed = False
        if form.is_valid():
            f=form.cleaned_data
            email_id = f['email'].strip()
            mobile_no = f['mobile'].strip()
            name = f['name'].strip()
            email_user,phone_user,email_alert_on,sms_alert_on = get_user_by_email_or_mobile(email_id,mobile_no)
            html_page = 'fb/discount-%s.html' % affiliate_name

            is_valid = True
            _coupon = Voucher.objects.filter(affiliate= affiliate, status="active").order_by('id')
            text = 'your' 
            total_coupon_codes ={}
            if affiliate.is_coupon_avail:
                if _coupon:
                    _coupon = _coupon[0]
                    total_coupon_codes[affiliate_name] = _coupon.code
                else:
                    errors.append("Sorry!! Coupons are not available")
                    is_valid = False
                if affiliate_name == 'esc':
                    total_coupon_codes = assign_coupons(affiliate)
            if is_valid:
                if not email_user and not phone_user: #new user
                    user,profile = utils.get_or_create_user(email_id, email_id, None, name)

                    email = UserEmail.objects.get(user=profile,type='primary',email=email_id)
                    email_alert_on = email
                    phone = Phone(user=profile,type='primary',phone=mobile_no)
                    phone.save()
                    sms_alert_on = phone
                elif email_user and phone_user:
                    if phone_user == email_user:
                        is_valid = True
                    else:
                        errors.append('Email id and Phone are not registered for the same user.')
                        is_valid = False
                elif not email_user and phone_user: #user with phone number already exist, update his email address only
                    errors.append('Mobile number is already subscribed.')
                    is_valid = False
                elif not phone_user and email_user: #user with email already exist, update his phone number only
                    errors.append('Email address is already subscribed.')
                    is_valid = False
                
            if not is_valid:
                return render_to_response(welcome_html,
                    {
                        'form':form,
                        'affiliate_logo':affiliate_logo,
                        'affiliate_text':affiliate_text,
                        'affiliate_name':affiliate_name,
                        'do_post':do_post,
                        'errors':errors,
                    },context_instance = RequestContext(request))
            url = request.get_full_path()
            existing_subscription_email = DailySubscription.objects.filter(newsletter=newsletter,email_alert_on=email_alert_on,source = affiliate_name)
            existing_subscription_phone = DailySubscription.objects.filter(newsletter=newsletter,sms_alert_on=sms_alert_on,source = affiliate_name)
            if affiliate_name in ["vcomm",'affinity','tyroo']:
                existing_subscription_email = DailySubscription.objects.filter(email_alert_on=email_alert_on)
                existing_subscription_phone = None
            if not existing_subscription_email and not existing_subscription_phone:
                subscribe = DailySubscription()
                subscribe.newsletter = newsletter
                subscribe.sms_alert_on = sms_alert_on
                subscribe.email_alert_on = email_alert_on
                subscribe.source = affiliate_name
                subscribe.save()

                if request.POST.get("selected_affiliates","") == "selected_affiliates":

                    t_body = get_template('notifications/users/affiliates_afaqs.email')
                    email_body = {}
                    email_body['request'] = request
                    email_body['name'] = name
                    c_body = Context(email_body)
                    t_subject = get_template('notifications/users/subscribe_sub.email')
                    email_from = {}
                    email_subject = {}
                    c_subject = Context(email_subject)
                    mail_obj = EmailAddress()
                    if is_future_ecom(request.client.client):
                        mail_obj.isHtml = True
                    mail_obj._from = request.client.client.promotions_email
                    mail_obj.body = t_body.render(c_body)
                    mail_obj.subject = t_subject.render(c_subject)
                    u_emails = ""
                    email = str(email_id)
                    u_emails = email.strip(',')
                    mail_obj.to = u_emails
                    mail_obj.send()

                    utils.subscribe_send_sms(mobile_no)
                    return HttpResponseRedirect("/")
                
                if not affiliate.is_coupon_avail:
                    if affiliate_name in special_offers:
                        send_coupons_by_email(request, total_coupon_codes, affiliate_name, email_alert_on, show_avail_coupon)
                        send_coupons_by_sms(request, total_coupon_codes, affiliate_name, sms_alert_on, show_avail_coupon)
                    else:
                        utils.subscribe_send_email(request,email_id, name)
                        utils.subscribe_send_sms(mobile_no)
                    return render_to_response('fb/thankyou-%s.html' % affiliate_name,{'email_id':email_id},context_instance = RequestContext(request))
                    
                if email_alert_on:
                    send_coupons_by_email(request, total_coupon_codes, affiliate_name, email_alert_on, show_avail_coupon)

                if sms_alert_on:
                    send_coupons_by_sms(request, total_coupon_codes, affiliate_name, sms_alert_on, show_avail_coupon)

                if affiliate_name != 'esc': 
                    _coupon.status = "inactive"
                    _coupon.save()
            else:
                errors.append("You have already subscribed for the deal.")
                already_subscribed = True
                is_valid = False

            if affiliate_name in ["vcomm",'affinity','tyroo']:
                return render_to_response('fb/subscribed.html',
                    {'affiliate_name':affiliate_name,'already_subscribed':already_subscribed},
                    context_instance = RequestContext(request))
    
            if is_valid: 
                return render_to_response(html_page,
                    {'affiliate_name':affiliate_name,'coupon_codes':total_coupon_codes, 'already_subscribed':already_subscribed},
                    context_instance = RequestContext(request))
    return render_to_response(welcome_html,
        {
            'form':form,
            'affiliate_logo':affiliate_logo,
            'affiliate_text':affiliate_text,
            'affiliate_name':affiliate_name,
            'do_post':do_post,
            'errors':errors,
            'show_avail_coupon':show_avail_coupon,
        },
        context_instance = RequestContext(request))
Exemplo n.º 11
0
Arquivo: fb.py Projeto: daasara/riba
def daily_deals_registration(request):
    form = FBRegisterForm()
    valid=False
    if request.method == 'POST':
        form = FBRegisterForm(request.POST)
        error=''
        if form.is_valid():
            valid = True
            f=form.cleaned_data
            email_id = f['email'].strip()
            mobile_no = f['mobile'].strip()

            user_info = get_user_by_email_or_mobile(email_id, mobile_no)
            email_user, phone_user, email_alert_on, sms_alert_on = user_info

            if not email_user and not phone_user:
                #new user
                user = User.objects.create_user(email_id,email_id,None)
                user.first_name = f['name'].strip()
                user.save()

                profile = Profile(user=user,full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile,type='primary',email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile,type='primary',phone=mobile_no)
                phone.save()
                sms_alert_on = phone

            if not email_user and phone_user:
                # user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user,type='primary',email=email_id)
                email.save()
                email_alert_on = email

            if not phone_user and email_user:
                # user with email already exist, update his phone number only
                phone = Phone(user=email_user,type='primary',phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if f['name']:
                u_name = f['name'][0].upper() + f['name'][1:]
            else:
                u_name = None
            utils.subscribe_send_email(request,email_id, u_name)
            utils.subscribe_send_sms(mobile_no)
            try:
                newsletter = NewsLetter.objects.get(newsletter='DailyDeals',client=request.client.client)
                existing_subscription = DailySubscription.objects.filter(newsletter=newsletter,sms_alert_on=sms_alert_on,email_alert_on=email_alert_on)
                if existing_subscription:
                    return render_to_response('fb/subscription_thankyou.html',
                            {'form':form,'valid':valid},
                            context_instance = RequestContext(request))
                else:
                    subscribe = DailySubscription()
                    subscribe.newsletter = newsletter
                    subscribe.sms_alert_on = sms_alert_on
                    subscribe.email_alert_on = email_alert_on
                    subscribe.save()
                    return render_to_response('fb/subscription_thankyou.html',
                            {'form':form,'valid':valid},
                            context_instance = RequestContext(request))
            except NewsLetter.DoesNotExist:
                return render_to_response('fb/subscription_thankyou.html',
                        {'form':form,'valid':valid},
                        context_instance = RequestContext(request))

        else:
            valid=False
            return render_to_response('fb/dailydeals_popup.html',
                    {'form':form,'valid':valid},
                    context_instance = RequestContext(request))

    return render_to_response('fb/dailydeals_popup.html',
            {'form':form,'valid':valid},
            context_instance = RequestContext(request))
Exemplo n.º 12
0
def migrate():
    # Migration plan
    # Read user, user address book from atg
    # Create one user in tinla per atg user

    #ezone_orders_users = FtbOrder.objects.select_related('order').all().values(
    #    'order__profile').distinct()
    #atg_users = DpsUser.objects.filter(dps_id__in = ezone_orders_users)
    atg_users = DpsUser.objects.all()

    count = atg_users.count()
    log.info('Found %s users in atg.' % count)
    index = 0
    exists = 0
    non_existing = 0
    newly_created = 0
    migrated = 0
    errors = 0
    attached = 0
    not_attached = 0
    atg_users = queryset_iterator(atg_users)
    for atg_user in atg_users:
        index += 1
        db.reset_queries()
        # Check if username is already taken in tinla
        # Tinla's usernames are phone numbers and email addresses
        email = None
        phone = None
        profile = None
        auth_user = None
        found = False
        username = atg_user.login
        try:
            email = Email.objects.select_related(
                'user', 'user__user').get(email=username)
            profile = email.user
            auth_user = profile.user
            found = True
        except Email.DoesNotExist:
            try:
                phone = Phone.objects.select_related(
                    'user', 'user__user').get(phone=username[:10])
                profile = phone.user
                auth_user = profile.user
                found = True
            except Phone.DoesNotExist:
                pass
        if found:
            exists += 1
            if profile.atg_login:
                migrated += 1
                if profile.atg_login != username:
                    log.info(
                        'Skipping user: %s. Check if it matches with: %s' %
                        (username, profile.atg_login))
            else:
                try:
                    profile.atg_login = username
                    profile.atg_password = atg_user.password
                    profile.save()
                    log.info(
                        'User exists. Just mapping atg_login and atg_password %s'
                        % username)
                    attached += 1
                except:
                    log.info('User exists. Duplicate atg_login %s' % username)
                    not_attached += 1
        else:
            non_existing += 1
            log.info('%s not found in tinla' % username)
            # No email and phone taken.
            if phone_re.match(username):
                phone = Phone(phone=username[:10])
            if email_re.match(username):
                email = Email(email=username)
            try:
                profile = new_profile(atg_user, phone, email)
                if profile:
                    newly_created += 1
                    log.info('Created new profile for %s. id is %s' %
                             (username, profile.id))
            except Exception, e:
                errors += 1
                log.exception('Error migrating %s. %s' % (username, repr(e)))

        if index % 10000 == 0:
            log.info('Processed %s/%s' % (index, count))
Exemplo n.º 13
0
def subscribe_email_link(request, alliance_name=None):
    form = FBRegisterForm()
    url = request.get_full_path()
    if not alliance_name:
        raise Http404
    else:
        affiliate_name = alliance_name.strip()
    try:
        affiliate_subscription = SubscriptionLink.objects.get(path="/" + affiliate_name)
    except:
        raise Http404
    affiliate = affiliate_subscription.affiliate
    affiliate_logo = affiliate.logo
    affiliate_text = affiliate.text
    newsletter = affiliate_subscription.newsletter
    do_post = True
    show_avail_coupon = affiliate.is_coupon_avail
    if affiliate_name == "afaqs":
        do_post = False
    errors = []
    welcome_html = "fb/register_for_deals.html"
    special_offers = ["gift"]
    if affiliate_name in special_offers:
        welcome_html = "fb/register_for_special_offers.html"
    if request.method == "POST":
        form = FBRegisterForm(request.POST)
        error = ""
        already_subscribed = False
        if form.is_valid():
            f = form.cleaned_data
            email_id = f["email"].strip()
            mobile_no = f["mobile"].strip()
            name = f["name"].strip()
            email_user, phone_user, email_alert_on, sms_alert_on = get_user_by_email_or_mobile(email_id, mobile_no)
            html_page = "fb/discount-%s.html" % affiliate_name

            is_valid = True
            _coupon = Voucher.objects.filter(affiliate=affiliate, status="active").order_by("id")
            text = "your"
            total_coupon_codes = {}
            if affiliate.is_coupon_avail:
                if _coupon:
                    _coupon = _coupon[0]
                    total_coupon_codes[affiliate_name] = _coupon.code
                else:
                    errors.append("Sorry!! Coupons are not available")
                    is_valid = False
                if affiliate_name == "esc":
                    total_coupon_codes = assign_coupons(affiliate)
            if is_valid:
                if not email_user and not phone_user:  # new user
                    user, profile = utils.get_or_create_user(email_id, email_id, None, name)

                    email = UserEmail.objects.get(user=profile, type="primary", email=email_id)
                    email_alert_on = email
                    phone = Phone(user=profile, type="primary", phone=mobile_no)
                    phone.save()
                    sms_alert_on = phone
                elif email_user and phone_user:
                    if phone_user == email_user:
                        is_valid = True
                    else:
                        errors.append("Email id and Phone are not registered for the same user.")
                        is_valid = False
                elif (
                    not email_user and phone_user
                ):  # user with phone number already exist, update his email address only
                    errors.append("Mobile number is already subscribed.")
                    is_valid = False
                elif not phone_user and email_user:  # user with email already exist, update his phone number only
                    errors.append("Email address is already subscribed.")
                    is_valid = False

            if not is_valid:
                return render_to_response(
                    welcome_html,
                    {
                        "form": form,
                        "affiliate_logo": affiliate_logo,
                        "affiliate_text": affiliate_text,
                        "affiliate_name": affiliate_name,
                        "do_post": do_post,
                        "errors": errors,
                    },
                    context_instance=RequestContext(request),
                )
            url = request.get_full_path()
            existing_subscription_email = DailySubscription.objects.filter(
                newsletter=newsletter, email_alert_on=email_alert_on, source=affiliate_name
            )
            existing_subscription_phone = DailySubscription.objects.filter(
                newsletter=newsletter, sms_alert_on=sms_alert_on, source=affiliate_name
            )
            if affiliate_name in ["vcomm", "affinity", "tyroo"]:
                existing_subscription_email = DailySubscription.objects.filter(email_alert_on=email_alert_on)
                existing_subscription_phone = None
            if not existing_subscription_email and not existing_subscription_phone:
                subscribe = DailySubscription()
                subscribe.newsletter = newsletter
                subscribe.sms_alert_on = sms_alert_on
                subscribe.email_alert_on = email_alert_on
                subscribe.source = affiliate_name
                subscribe.save()

                if request.POST.get("selected_affiliates", "") == "selected_affiliates":

                    t_body = get_template("notifications/users/affiliates_afaqs.email")
                    email_body = {}
                    email_body["request"] = request
                    email_body["name"] = name
                    c_body = Context(email_body)
                    t_subject = get_template("notifications/users/subscribe_sub.email")
                    email_from = {}
                    email_subject = {}
                    c_subject = Context(email_subject)
                    mail_obj = EmailAddress()
                    if is_future_ecom(request.client.client):
                        mail_obj.isHtml = True
                    mail_obj._from = request.client.client.promotions_email
                    mail_obj.body = t_body.render(c_body)
                    mail_obj.subject = t_subject.render(c_subject)
                    u_emails = ""
                    email = str(email_id)
                    u_emails = email.strip(",")
                    mail_obj.to = u_emails
                    mail_obj.send()

                    utils.subscribe_send_sms(mobile_no)
                    return HttpResponseRedirect("/")

                if not affiliate.is_coupon_avail:
                    if affiliate_name in special_offers:
                        send_coupons_by_email(
                            request, total_coupon_codes, affiliate_name, email_alert_on, show_avail_coupon
                        )
                        send_coupons_by_sms(
                            request, total_coupon_codes, affiliate_name, sms_alert_on, show_avail_coupon
                        )
                    else:
                        utils.subscribe_send_email(request, email_id, name)
                        utils.subscribe_send_sms(mobile_no)
                    return render_to_response(
                        "fb/thankyou-%s.html" % affiliate_name,
                        {"email_id": email_id},
                        context_instance=RequestContext(request),
                    )

                if email_alert_on:
                    send_coupons_by_email(
                        request, total_coupon_codes, affiliate_name, email_alert_on, show_avail_coupon
                    )

                if sms_alert_on:
                    send_coupons_by_sms(request, total_coupon_codes, affiliate_name, sms_alert_on, show_avail_coupon)

                if affiliate_name != "esc":
                    _coupon.status = "inactive"
                    _coupon.save()
            else:
                errors.append("You have already subscribed for the deal.")
                already_subscribed = True
                is_valid = False

            if affiliate_name in ["vcomm", "affinity", "tyroo"]:
                return render_to_response(
                    "fb/subscribed.html",
                    {"affiliate_name": affiliate_name, "already_subscribed": already_subscribed},
                    context_instance=RequestContext(request),
                )

            if is_valid:
                return render_to_response(
                    html_page,
                    {
                        "affiliate_name": affiliate_name,
                        "coupon_codes": total_coupon_codes,
                        "already_subscribed": already_subscribed,
                    },
                    context_instance=RequestContext(request),
                )
    return render_to_response(
        welcome_html,
        {
            "form": form,
            "affiliate_logo": affiliate_logo,
            "affiliate_text": affiliate_text,
            "affiliate_name": affiliate_name,
            "do_post": do_post,
            "errors": errors,
            "show_avail_coupon": show_avail_coupon,
        },
        context_instance=RequestContext(request),
    )
Exemplo n.º 14
0
def migrate_subscriptions():
    start = datetime(day=1, month=4, year=2011)
    subscripions_qs = FtbDealsLogin.objects.filter(registration_time__gte=start)
    newsletter = NewsLetter.objects.get(pk=2)
    for subscription in subscripions_qs:
        if SubscriptionSync.objects.filter(ext_id=subscription.id):
            #print 'Skipping %s: Already synced' % subscription.id
            continue
        email = subscription.email_address or ''
        mobile = subscription.mobile_number or ''
        name = subscription.register_name or ''
        if len(email) > 50 or len(name) > 100:
            #print 'Skipping %s: Long data' % subscription.id
            continue

        source = 'atg'
        if subscription.facebook_user == 1:
            source = 'facebook-atg'

        profile = None

        is_valid_email = False
        e = None
      	if utils.is_valid_email(email):
            is_valid_email = True
            try:
                e = Email.objects.get(email=email)
                profile = e.user
            except Email.DoesNotExist:
                pass

        is_valid_mobile = False
        m = None                 
        if utils.is_valid_mobile(mobile):
            is_valid_mobile = True
            try:
                m = Phone.objects.get(phone=mobile)
                profile = m.user
            except Phone.DoesNotExist:
                pass

        if not is_valid_mobile and is_valid_email:
            #print 'Skipping %s, %s, %s: Invalid data' % (email, mobile, name)
            continue

        if not profile:
            # Create a new profile in our system
            if is_valid_email:
                usr, profile = utils.get_or_create_user(email, email,
                                   password=None, first_name=name)
            if not is_valid_email:
                usr, profile = utils.get_or_create_user(mobile, '',
                                   password=None, first_name=name)

        if not profile:
            # Still not able to create profile
            #print 'Skipping %s, %s, %s: No profile' % (email, mobile, name)
            continue

	if not e:
            try:
                e = Email.objects.get(email=email)
            except Email.DoesNotExist:
                # Create a new email
                e = Email()
                e.user = profile
                e.email = email
                e.save()

        if not m:
            try:
                m = Phone.objects.get(phone=mobile)
            except Phone.DoesNotExist:
                m = Phone()
                m.user = profile
                m.phone = mobile
                m.save()

        # Create an entry into the subscription table 
        subscr = DailySubscription()
        subscr.email_alert_on = e
        subscr.sms_alert_on = m
        subscr.source = source
        subscr.timestamp = subscription.registration_time
        subscr.newsletter = newsletter
        subscr.save()

        link = SubscriptionSync()
        link.ext_id = subscription.id
        link.account = 'futurebazaar'
        link.save() 
Exemplo n.º 15
0
def migrate_subscriptions():
    start = datetime(day=1, month=4, year=2011)
    subscripions_qs = FtbDealsLogin.objects.filter(
        registration_time__gte=start)
    newsletter = NewsLetter.objects.get(pk=2)
    for subscription in subscripions_qs:
        if SubscriptionSync.objects.filter(ext_id=subscription.id):
            #print 'Skipping %s: Already synced' % subscription.id
            continue
        email = subscription.email_address or ''
        mobile = subscription.mobile_number or ''
        name = subscription.register_name or ''
        if len(email) > 50 or len(name) > 100:
            #print 'Skipping %s: Long data' % subscription.id
            continue

        source = 'atg'
        if subscription.facebook_user == 1:
            source = 'facebook-atg'

        profile = None

        is_valid_email = False
        e = None
        if utils.is_valid_email(email):
            is_valid_email = True
            try:
                e = Email.objects.get(email=email)
                profile = e.user
            except Email.DoesNotExist:
                pass

        is_valid_mobile = False
        m = None
        if utils.is_valid_mobile(mobile):
            is_valid_mobile = True
            try:
                m = Phone.objects.get(phone=mobile)
                profile = m.user
            except Phone.DoesNotExist:
                pass

        if not is_valid_mobile and is_valid_email:
            #print 'Skipping %s, %s, %s: Invalid data' % (email, mobile, name)
            continue

        if not profile:
            # Create a new profile in our system
            if is_valid_email:
                usr, profile = utils.get_or_create_user(email,
                                                        email,
                                                        password=None,
                                                        first_name=name)
            if not is_valid_email:
                usr, profile = utils.get_or_create_user(mobile,
                                                        '',
                                                        password=None,
                                                        first_name=name)

        if not profile:
            # Still not able to create profile
            #print 'Skipping %s, %s, %s: No profile' % (email, mobile, name)
            continue

        if not e:
            try:
                e = Email.objects.get(email=email)
            except Email.DoesNotExist:
                # Create a new email
                e = Email()
                e.user = profile
                e.email = email
                e.save()

        if not m:
            try:
                m = Phone.objects.get(phone=mobile)
            except Phone.DoesNotExist:
                m = Phone()
                m.user = profile
                m.phone = mobile
                m.save()

        # Create an entry into the subscription table
        subscr = DailySubscription()
        subscr.email_alert_on = e
        subscr.sms_alert_on = m
        subscr.source = source
        subscr.timestamp = subscription.registration_time
        subscr.newsletter = newsletter
        subscr.save()

        link = SubscriptionSync()
        link.ext_id = subscription.id
        link.account = 'futurebazaar'
        link.save()
Exemplo n.º 16
0
def daily_deals_registration(request):
    form = FBRegisterForm()
    valid = False
    if request.method == "POST":
        form = FBRegisterForm(request.POST)
        error = ""
        if form.is_valid():
            valid = True
            f = form.cleaned_data
            email_id = f["email"]
            mobile_no = f["mobile"]

            user_info = get_user_by_email_or_mobile(email_id, mobile_no)
            email_user, phone_user, email_alert_on, sms_alert_on = user_info

            if not email_user and not phone_user:
                # new user
                user = User.objects.create_user(email_id, email_id, None)
                user.first_name = f["name"]
                user.save()

                profile = Profile(user=user, full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile, type="primary", email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone

            if not email_user and phone_user:
                # user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user, type="primary", email=email_id)
                email.save()
                email_alert_on = email

            if not phone_user and email_user:
                # user with email already exist, update his phone number only
                phone = Phone(user=email_user, type="primary", phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if f["name"]:
                u_name = f["name"][0].upper() + f["name"][1:]
            else:
                u_name = None
            utils.subscribe_send_email(request, email_id, u_name)
            utils.subscribe_send_sms(mobile_no)
            try:
                newsletter = NewsLetter.objects.get(newsletter="DailyDeals", client=request.client.client)
                existing_subscription = DailySubscription.objects.filter(
                    newsletter=newsletter, sms_alert_on=sms_alert_on, email_alert_on=email_alert_on
                )
                if existing_subscription:
                    return render_to_response(
                        "fb/subscription_thankyou.html",
                        {"form": form, "valid": valid},
                        context_instance=RequestContext(request),
                    )
                else:
                    subscribe = DailySubscription()
                    subscribe.newsletter = newsletter
                    subscribe.sms_alert_on = sms_alert_on
                    subscribe.email_alert_on = email_alert_on
                    subscribe.save()
                    return render_to_response(
                        "fb/subscription_thankyou.html",
                        {"form": form, "valid": valid},
                        context_instance=RequestContext(request),
                    )
            except NewsLetter.DoesNotExist:
                return render_to_response(
                    "fb/subscription_thankyou.html",
                    {"form": form, "valid": valid},
                    context_instance=RequestContext(request),
                )

        else:
            valid = False
            return render_to_response(
                "fb/dailydeals_popup.html", {"form": form, "valid": valid}, context_instance=RequestContext(request)
            )

    return render_to_response(
        "fb/dailydeals_popup.html", {"form": form, "valid": valid}, context_instance=RequestContext(request)
    )
Exemplo n.º 17
0
def subscribe_email_link(request, alliance):
    form = FBRegisterForm()
    affiliate_name = alliance
    try:
        affiliate_subscription = SubscriptionLink.objects.get(path='/' +
                                                              affiliate_name)
    except SubscriptionLink.DoesNotExist:
        raise Http404
    affiliate_logo = affiliate_subscription.affiliate.logo
    affiliate_text = affiliate_subscription.affiliate.text
    newsletter = affiliate_subscription.newsletter

    if request.method == 'POST':
        form = FBRegisterForm(request.POST)
        error = ''
        already_subscribed = False
        if form.is_valid():
            f = form.cleaned_data
            email_id = f['email']
            mobile_no = f['mobile']
            name = f['name']
            email_user, phone_user, email_alert_on, sms_alert_on = get_user_by_email_or_mobile(
                email_id, mobile_no)  #User.objects.get(username = mobile_no)
            if not email_user and not phone_user:  #new user
                user = User.objects.create_user(email_id, email_id, None)
                user.first_name = f['name']
                user.save()

                profile = Profile(user=user, full_name=user.first_name)
                profile.save()

                email = UserEmail(user=profile, type='primary', email=email_id)
                email.save()
                email_alert_on = email
                phone = Phone(user=profile, type='primary', phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if not email_user and phone_user:  #user with phone number already exist, update his email address only
                email = UserEmail(user=phone_user,
                                  type='primary',
                                  email=email_id)
                email.save()
                email_alert_on = email
            if not phone_user and email_user:  #user with email already exist, update his phone number only
                phone = Phone(user=email_user, type='primary', phone=mobile_no)
                phone.save()
                sms_alert_on = phone
            if email_user and phone_user and email_user != phone_user:  #phone user and email user are different
                pass

            existing_subscription = DailySubscription.objects.filter(
                newsletter=newsletter,
                sms_alert_on=sms_alert_on,
                email_alert_on=email_alert_on,
                source='/' + affiliate_name)
            if not existing_subscription:
                subscribe = DailySubscription()
                subscribe.newsletter = newsletter
                subscribe.sms_alert_on = sms_alert_on
                subscribe.email_alert_on = email_alert_on
                subscribe.source = '/' + affiliate_name
                subscribe.save()
            else:
                already_subscribed = True
                return render_to_response(
                    'fb/subscribed.html', {
                        'affiliate_name': affiliate_name,
                        'already_subscribed': already_subscribed
                    },
                    context_instance=RequestContext(request))

            total_coupon_codes, text = assign_coupons(
                affiliate_subscription.affiliate, email_alert_on, sms_alert_on)
            if alliance == 'icici':
                return render_icici_products(request, total_coupon_codes)
            if email_alert_on:
                send_coupons_by_email(total_coupon_codes,
                                      affiliate_subscription.affiliate,
                                      email_alert_on)

            if sms_alert_on:
                sms_text = text
                sms = SMS()
                sms.text = sms_text
                sms.to = sms_alert_on.phone
                sms.send()

            return render_to_response('fb/discount.html', {
                'affiliate': affiliate_subscription.affiliate,
                'coupon_codes': total_coupon_codes,
                'already_subscribed': already_subscribed
            },
                                      context_instance=RequestContext(request))
        else:
            return render_to_response('fb/register_for_deals.html', {
                'form': form,
                'affiliate_logo': affiliate_logo,
                'affiliate_text': affiliate_text
            },
                                      context_instance=RequestContext(request))

    else:
        return render_to_response('fb/register_for_deals.html', {
            'form': form,
            'affiliate_logo': affiliate_logo,
            'affiliate_text': affiliate_text
        },
                                  context_instance=RequestContext(request))