def test_process_referral_authenticated(self): referral = Referral.create(redirect_to="https://example.com/") self.assertFalse(referral.responses.exists()) referred_user = get_user_model().objects.create_user("janedoe", "*****@*****.**", "notsosecret") self.assertTrue(self.client.login(username=referred_user.username, password="******")) response = self.client.get(referral.url) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "https://example.com/") self.assertEqual(referral.responses.count(), 1) referral_response = referral.responses.first() self.assertEqual(referral_response.user, referred_user)
def handle_user_signed_up(sender, request, user, **kwargs): referral_response = Referral.record_response(request, "SIGN_UP") print(referral_response) profile = user.profile referral = Referral.create(user=user, redirect_to=reverse_lazy('home')) profile.referral = referral profile.save()
def payment_notification(sender, **kwargs): ipn = sender if ipn.payment_status == 'Completed': # payment was successful profile = Profile.objects.get(user_id=ipn.invoice) Referral.record_response(request, "PAID") profile.paid = True profile.save()
def handle_user_signed_up(sender, request, user, **kwargs): profile = user.profile referral = Referral.create(user=user, redirect_to=reverse_lazy('rest_register')) profile.referral = referral action = Referral.record_response(request, "USER_SIGNUP") if action is not None: referra = Referral.objects.get(id=action.referral.id) print(referra.user.id) profile.referredBy = User.objects.get(id=referra.user.id) profile.save() profile.save()
def createUser(request): if request.method == 'GET': user_form = SignUpForm() return render(request, 'sign_up.html', {'user_form': user_form}) elif request.method == 'POST': user_form = SignUpForm(request.POST) message = "User created successfully" if user_form.is_valid(): #validate user email email = user_form.cleaned_data['email'] mail_response = validate_email(email) disposable = mail_response['is_disposable_address'] #disposable if (disposable == True): errors = user_form.add_error( "email", "Email " + str(email) + " seems to be disposable, use another one.") data = {'user_form': user_form} return render(request, 'sign_up.html', data) user = user_form.save(commit=False) user.is_active = True user.username = user.username.lower().strip() user.save() referral_response = Referral.record_response(request, "SIGN_UP", target=user) send_confirmation_email(request, user) return render(request, 'account_activation_sent.html', {'email': email}) return render(request, 'sign_up.html', {'user_form': user_form}) raise ValueError('Not valid request at signup')
def signup(self, request, user): group = 'advertiser' g = Group.objects.get(name=group) user.groups.add(g) referral = Referral.create(user=user, redirect_to="index") user.referral = referral user.save()
def save_profile(sender, **kwargs): request = kwargs['request'] user = kwargs['user'] print(user) referral = Referral.create( user=user, redirect_to=reverse("Home:afterclickin"), label="SIGNED_UP", ) Referral.record_response(request, "SIGNED_UP") profile = Profile.objects.create(user=user, referral=referral) profile.save()
def after_signup(self, form): self.create_profile(form) super(SignupView, self).after_signup(form) action = Referral.record_response(self.request, "USER_SIGNUP") if action is not None: referral = Referral.objects.get(id=action.referral.id) profile = Profile.objects.get(user=self.created_user) profile.parent = Profile.objects.get(user=referral.user) profile.save()
def update_user_profile(sender, instance, created, **kwargs): if created: profile = Profile.objects.create(user=instance) referral = Referral.create( user=instance, redirect_to=reverse('users_create_user') ) profile.referral = referral instance.profile.save()
async def websocket_receive(self, event): print("received", event) front_end = event.get("text", None) if front_end is not None: data = json.loads(front_end) user = data.get('user') # request = data.get("request") # print(request, "this is request") await self.send({ "type": "websocket.send", "text": f"imekubali {user}" }) profile = Profile.objects.get(user__username=user, paid=False) print(profile, "checking if profile is not none") profile.paid = True profile.save() request = dot(self.scope) Referral.record_response(request, "PAID")
def validate_mpesa_code(request): profile = Profile.objects.filter(user=request.user, paid=False).first() # amount = order.get_total() data = {} mpesa_code = request.GET.get('mpesa_code', None) if profile: if mpesa_code: result1 = LNMOnline.objects.filter( MpesaReceiptNumber__iexact=mpesa_code, paid=False).exists() if result1 == True: result = LNMOnline.objects.get(MpesaReceiptNumber=mpesa_code, paid=False) result.paid = True result.save() Referral.record_response(request, "PAID") profile.paid = True profile.save() data["message"] = "Transaction Successful" return JsonResponse(data) else: data["message"] = "Mpesa Code Does not exist" return JsonResponse(data) else: data["message"] = "Enter Mpesa Code" return JsonResponse(data) else: data["message"] = "user does not exist" return JsonResponse(data)
def affiliate(request): profile = UserProfile.objects.get(username=request.user.username) # profile.parent = Profile.objects.get(user=referral.user) referral = Referral.create(user=profile, redirect_to=reverse("home")) profile.referral = referral profile.save() context = {"profile": profile} return render(request, "users/affiliate.html", context)
def home(request): context = { "title": "eLearning", } action = Referral.record_response(request, "login") respo = render(request, "home.html", context) if action is not None: referral = Referral.objects.get(id=action.referral.id) respo.set_cookie('parent', referral.user.username) return respo
def handle(self, verbosity, **options): """ Create a personal referral link for each existing user """ #Get all users, excluding inactive users users = User.objects.exclude(is_active=False) for user in users: referral = Referral.create( redirect_to=reverse('promotions:home'), user=user) profile = user.get_profile() profile.referral = referral profile.save()
def registration(request): if request.method == 'POST': register_form = RegistrationForm(request.POST) response_data = {} if register_form.is_valid(): register_form.save() cd = register_form.cleaned_data # before authentication and login! Referral.record_response(request, action_string="USER_SIGNUP") user = authenticate(username=cd['username'], password=cd['password1']) login(request, user) response_data['success'] = True response_data['message'] = _("Вы успешно зарегистрировались") # return HttpResponse(json.dumps(response_data), content_type="application/json") return HttpResponseRedirect(reverse('profile')) else: # print register_form.errors response_data['success'] = False response_data['message'] = register_form.errors return HttpResponse(json.dumps(response_data), content_type="application/json") return HttpResponseBadRequest()
def save_transaction(request): if request.method == 'POST': form = DonationForm(request, request.POST) response_data = {} if form.is_valid(): if form.cleaned_data["payment_method"] != Donation.PAYMENT_METHOD.ETH \ and not form.cleaned_data["tx_id"]: response_data['transaction_error'] = {} response_data['transaction_error']['tx_id'] = [ str(_("Для не ETH транзакций это поле обязательно")) ] return HttpResponse(json.dumps(response_data), content_type="application/json") else: donat_obj = form.save() # creating referral response ref_response_obj = Referral.record_response( request, action_string="PURCHASED") # linking referral response with donation if ref_response_obj: donat_obj.ref_response = ref_response_obj donat_obj.save() response_data['message'] = str(_('Transaction saved!')) response_data['donation_obj'] = { 'date': donat_obj.created_dt.strftime("%d.%m.%y"), 'method': donat_obj.payment_method } return HttpResponse(json.dumps(response_data), content_type="application/json") else: response_data['transaction_error'] = form.errors return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponseBadRequest()
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password = ( self.cleaned_data["username"], self.cleaned_data["email"], self.cleaned_data["password1"], ) new_user = UserenaSignup.objects.create_user( username, email, password, not userena_settings.USERENA_ACTIVATION_REQUIRED, userena_settings.USERENA_ACTIVATION_REQUIRED, ) group = "advertiser" g = Group.objects.get(name=group) new_user.groups.add(g) referral = Referral.create(user=new_user, redirect_to="index") new_user.referral = referral return new_user
def handle_user_signed_up(sender, user, form, **kwargs): profile = user.profile referral = Referral.create(user=user, redirect_to=reverse_lazy('account_signup')) profile.referral = referral profile.save()
def count_referral(request, is_new, **kwargs): if is_new: Referral.record_response(request, 'REGISTER')
def user_registered_handler(sender, user, request, **kwargs): """ Send alert to admins on new registered customer and send registration email """ from apps.customer.alerts import senders from apps.user import alerts from apps.user.models import GoogleAnalyticsData from pinax.referrals.models import Referral from apps.customer.tasks import mixpanel_post_registration, subscribe_user import urllib #prevent sending when user is superuser if not user.is_superuser: alerts.send_new_user_alert(user) #Create user's referral code and link to profile referral = Referral.create(redirect_to=reverse('promotions:home'), user=user) profile = kwargs.get('profile') if not profile: profile = user.get_profile() profile.referral = referral profile.added_chrome_extension = request.session.get( 'added_chrome_extension', False) if profile.added_chrome_extension: profile.date_chrome_extension_added = datetime.now() if not kwargs.get('post_signup_emails_sent'): if profile.email_confirmed: senders.send_registration_email(user) else: # we send the confirm email address email upon API registration # therefore, no need to resend it here if not profile.signed_up_through_api(): senders.send_email_confirmation_email(user) senders.send_thirty_minutes_post_signup_email(user) #give credit for newly signed up user if he followed a referral link #sender can be one of those two: # 1 - RegisterProfileView # 2 - python_social_auth django strategy #both have a request property so we're all covered # normally anafero middleware would handle this, but # because django-registration calls `login()`, the session_key # changes and `Referral.record_response()` won't work since the middleware hasn't # performed this cleanup if not request.user.is_authenticated(): request.user = user anafero_middleware = SessionJumpingMiddleware() anafero_middleware.process_request(request) response = responses.credit_signup(request) if response: #add site notification to let the referrer know that a user #has just registered following his referral link utils.add_user_signed_up_site_notification(response.referral.user, response.user) #save external referer external_referer = request.session.get('external_referer') if external_referer is not None: profile.external_referer = external_referer #need to identify the new user in mixpanel - we're doing this in the background #as we must call a blocking function mixpanel_anon_id = kwargs.get('mixpanel_anon_id') backend = kwargs.get('backend', 'Email') data = { 'mixpanel_anon_id': mixpanel_anon_id, 'user': user, 'profile': profile, 'backend': backend, 'referrer_mailbox': None, } #get registration type register_type = kwargs.get('register_type') #check for referral data referrer = response.referral.user if response else None if referrer: register_type = 'invite' data['referrer_mailbox'] = referrer.get_profile().uuid data['referrer_name'] = referrer.get_full_name() #check for analytics data if 'adwords_data' in request.session: term = request.session['adwords_data'].get('utm_term') content = request.session['adwords_data'].get('utm_content') gad_kwargs = { 'source': request.session['adwords_data'].get('utm_source'), 'medium': request.session['adwords_data'].get('utm_medium'), 'name': request.session['adwords_data'].get('utm_campaign'), 'term': urllib.unquote(term) if term else None, 'content': urllib.unquote(content) if content else None, 'profile': profile } try: GoogleAnalyticsData.objects.create(**gad_kwargs) except: logger.exception("Error creating GoogleAnalyticsData object") if gad_kwargs['medium'] and gad_kwargs['medium'].lower() == 'cpc': register_type = 'paid' data['register_type'] = register_type mixpanel_post_registration.apply_async(kwargs=data, queue='analytics') if not profile.email_confirmed: #move newly registered user to the unconfirmed group if email is not confirmed #registered users via API can have their email address confirmed at this stage list_id = settings.MAILCHIMP_LISTS[settings.MAILCHIMP_LIST_USERS] group_id = settings.MAILCHIMP_LIST_GROUPS[list_id][ settings.MAILCHIMP_GROUP_UNCONFIRMED] subscribe_user.apply_async(kwargs={ 'user': user, 'list_id': list_id, 'group_settings': { group_id: True }, 'is_conf_url_required': True }, queue='analytics') #save registration info if register_type: profile.registration_type = register_type profile.registration_method = backend profile.save()
def create_referral(user): """Generate referrel code for this user.""" return Referral.create(user=user, redirect_to="/")
def record_referrer_response(request, action): """ Here we give credit to the referrer """ return Referral.record_response(request, action)