def check_user_status(request, template_file="administration/userstatus/status.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get(email__iexact=form.cleaned_data.get('email')) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if profile.skeleton_user: context[ 'status'] = "This user hasn't signed up to rate tracker yet, but has signed up for a reminder/instructions email, the newsletter, rate alerts or the concierge service" elif not profile.filled_in_name: context['status'] = "This user never finished filling in their name on the initial signup" elif not user.is_active: context['status'] = "This user is inactive" else: context['status'] = "User has signed up, probably has forgotten their password..." except User.DoesNotExist: context['status'] = "user doesn't exist" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def update_salesforce_user_task(queryset): SFResponseCodes =["SUCCESS", "ERR_USERID_EXISTS", "ERR_USERID_NOT_FOUND", "ERR_PORTFOLIOID_NOT_FOUND", "ERR_PORTFOLIOID_EXISTS"] django_client = init_client() for user in queryset: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] bitmask = get_subscription_bitmask(profile) if CampaignsSignup.objects.filter(email=user.email).exists(): bitmask += 16 bitmask += 8 returncode = django_client.service.updateUser2('%s' % profile.user.id, profile.user.username, profile.user.email, user.first_name, user.last_name, profile.dob, profile.telephone, profile.salutation, profile.postcode, bitmask, profile.user.is_active, ) if returncode > 0: raise ResponseError(returncode)
def ExportUsers(modeladmin, request, queryset): today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') failed_users = [] fn = os.path.join(USER_EXPORT_PATH % date_format) f1 = open(fn, 'wb') fwr = csv.writer(f1, delimiter=',', quoting=csv.QUOTE_MINIMAL) fwr.writerow(['Email', 'Firstname', 'Surname', 'Telephone', 'Postcode', 'Newsletters', 'RateAlerts']) for file in queryset: csv_file = readers.UnicodeReader(open(file.csv_file.path, 'rb'), encoding='utf-8') for row in csv_file: try: user = User.objects.get(email__iexact=row[0]) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] fwr.writerow([user.email, user.first_name, user.last_name, profile.telephone, profile.postcode, profile.newsletter, profile.ratealerts]) except Exception, ex: try: if not row[0] == "Email": failed_users.append(row[0]) failed_users.append(" because %s \n" % ex) except: failed_users.append(ex) file.has_been_run = True file.save() file.csv_file.close()
def update_salesforce_user_task(queryset): SFResponseCodes = [ "SUCCESS", "ERR_USERID_EXISTS", "ERR_USERID_NOT_FOUND", "ERR_PORTFOLIOID_NOT_FOUND", "ERR_PORTFOLIOID_EXISTS" ] django_client = init_client() for user in queryset: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] bitmask = get_subscription_bitmask(profile) if CampaignsSignup.objects.filter(email=user.email).exists(): bitmask += 16 bitmask += 8 returncode = django_client.service.updateUser2( '%s' % profile.user.id, profile.user.username, profile.user.email, user.first_name, user.last_name, profile.dob, profile.telephone, profile.salutation, profile.postcode, bitmask, profile.user.is_active, ) if returncode > 0: raise ResponseError(returncode)
def resend_user_activation( request, template_file="administration/resend_activation/index.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get( email__iexact=form.cleaned_data.get('email')) if not user.is_active: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if not profile.skeleton_user: send_email_confirmation(request, user) context[ 'message'] = "Activation email has been resent to %s" % user.email else: context[ 'message'] = "This user hasn't signed up for ratetracker" else: context[ 'message'] = "This user has already activated, they should probably use the password reset bit on the login page!" except User.DoesNotExist: context['message'] = "User doesn't exist!" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def save(self): user = super().save(commit=True) # Save a profile object for the user profile = Profile(user=user) profile.save() return user
def resend_user_activation(request, template_file="administration/resend_activation/index.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get(email__iexact=form.cleaned_data.get('email')) if not user.is_active: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if not profile.skeleton_user: send_email_confirmation(request, user) context['message'] = "Activation email has been resent to %s" % user.email else: context['message'] = "This user hasn't signed up for ratetracker" else: context[ 'message'] = "This user has already activated, they should probably use the password reset bit on the login page!" except User.DoesNotExist: context['message'] = "User doesn't exist!" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def handle_noargs(self, **options): dte = self._get_query_date(datetime.datetime.now()) human_readable_format = dte.strftime('%Y/%m/%d') date_format = dte.strftime('%Y%m%d') fn = os.path.join(NON_ACTIVE_USERS_CSV_PATH % date_format) f = open(fn, 'wb') fwr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL) fwr.writerow(['Username', 'Email', 'First Name', 'Last Name', 'Tel. no.', 'Source', 'Date Joined']) # Get users who have not activated yet users = User.objects.filter(date_joined__lte=self._get_start_date(dte), date_joined__gte=self._get_end_date(dte), is_active=False, is_superuser=False).order_by('date_joined').exclude(email__in=SAVCHAMP_EMAIL_FILTERS) counter = 0 for user in users: try: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() if not profile.skeleton_user: email = user.email first_name = user.first_name last_name = user.last_name user_name = user.username date_joined = user.date_joined tel = profile.telephone source = profile.source fwr.writerow([user_name,email, first_name, last_name, tel, source, date_joined]) counter += 1 except Exception: pass f.close() if counter > 0: email = EmailMessage('Inactive users report w/e %s, %s users found ' % (human_readable_format,counter), 'Please find attached a list of inactive users who joined last week', settings.DEFAULT_FROM_EMAIL, ALERTS_CSV_EMAIL,) email.attach_file(fn) email.send() else: email = EmailMessage('Inactive users report w/e %s, 0 users founds ' % human_readable_format, 'There are no inactive users who joined last week', settings.DEFAULT_FROM_EMAIL, ALERTS_CSV_EMAIL,) email.send()
def handle_noargs(self, **options): dte = self._get_query_date(datetime.datetime.now()) human_readable_format = dte.strftime('%Y/%m/%d') date_format = dte.strftime('%Y%m%d') fn = os.path.join(NON_ACTIVE_USERS_CSV_PATH % date_format) f = open(fn, 'wb') fwr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL) fwr.writerow(['Username', 'Email', 'First Name', 'Last Name', 'Tel. no.', ' Source', 'Date Joined']) # Get users who have not activated yet users = User.objects.filter(is_active=False, is_superuser=False).order_by('date_joined').exclude(email__in=SAVCHAMP_EMAIL_FILTERS) counter = 0 for user in users: try: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() if not profile.skeleton_user: email = user.email first_name = user.first_name last_name = user.last_name user_name = user.username date_joined = user.date_joined tel = profile.telephone source = profile.source fwr.writerow([user_name, email, first_name, last_name, tel, source, date_joined]) counter += 1 except Exception: pass f.close() if counter > 0: email = EmailMessage('Inactive users report w/e %s, %s users found ' % (human_readable_format, counter ), 'Please find attached a list of all the inactive users', settings.DEFAULT_FROM_EMAIL, ALERTS_CSV_EMAIL, ) email.attach_file(fn) email.send() else: email = EmailMessage('Inactive users report w/e %s, 0 users founds ' % human_readable_format, 'There are no inactive users', settings.DEFAULT_FROM_EMAIL, ALERTS_CSV_EMAIL, ) email.send()
def handle_noargs(self, **options): #get all users and then export them to a csv for syncing with salesforce (for newUser4) failed_users=[] userList = User.objects.all() fn = os.path.join(USER_EXPORT_PATH % 'all') f = open(fn, 'wb') fwr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL) for user in userList: try: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() #GET ALT TEL AND BEST TIME TO CALL try: signup = CampaignsSignup.objects.get(email=profile.user.email) alt_tel = signup.alt_telephone best_time = signup.best_call_time except: alt_tel = '' best_time = '' subscriptions = self._get_subscription_bitmask(profile) fwr.writerow([user.id, user.username, user.email, user.first_name, user.last_name, profile.dob, profile.telephone, profile.salutation, profile.postcode, subscriptions, profile.source, alt_tel, best_time, user.is_active, user.date_joined]) except Exception as ex: try: failed_users.append("%s failed because %s \n" % (user.email, ex)) except: failed_users.append("%s \n" % ex) f.close() email = EmailMessage('User Salesforce List', ('The following users failed: \n %s' % "".join(failed_users)), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'],) email.attach_file(fn) email.send()
def handle_noargs(self, **options): #get all users and then export them to a csv for syncing with salesforce (for newUser4) failed_users = [] userList = User.objects.all() fn = os.path.join(USER_EXPORT_PATH % 'all') f = open(fn, 'wb') fwr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL) for user in userList: try: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() #GET ALT TEL AND BEST TIME TO CALL try: signup = CampaignsSignup.objects.get( email=profile.user.email) alt_tel = signup.alt_telephone best_time = signup.best_call_time except: alt_tel = '' best_time = '' subscriptions = self._get_subscription_bitmask(profile) fwr.writerow([ user.id, user.username, user.email, user.first_name, user.last_name, profile.dob, profile.telephone, profile.salutation, profile.postcode, subscriptions, profile.source, alt_tel, best_time, user.is_active, user.date_joined ]) except Exception as ex: try: failed_users.append("%s failed because %s \n" % (user.email, ex)) except: failed_users.append("%s \n" % ex) f.close() email = EmailMessage( 'User Salesforce List', ('The following users failed: \n %s' % "".join(failed_users)), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], ) email.attach_file(fn) email.send()
def RemoveUsersRateAlertFlag(modeladmin, request, queryset): today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') failed_users = [] for file in queryset: csv_file = readers.UnicodeReader(open(file.csv_file.path, 'rb'), encoding='utf-8') for row in csv_file: try: user = User.objects.get(email__iexact=row[0]) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.ratealerts = False profile.is_synched = False profile.save() except Exception, ex: try: if not row[0] == "Email": failed_users.append(row[0]) failed_users.append(" because %s \n" % ex) except: failed_users.append(ex) file.has_been_run = True file.save() file.csv_file.close()
def ratealert(request, template_file = 'common/signups/checkemail.html'): context = RequestContext(request) if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email', None) try: signup = RateAlertsSignup.objects.get(email__iexact=email) #someone has tried resigning up - now we need to check if they have activated anywhere else on the site if signup.is_activated is False: if User.objects.filter(email__iexact=email).exists(): user = User.objects.get(email__iexact=email) if user.is_active: signup.is_activated = True signup.save() try: profile = user.profile except Profile.DoesNotExist: profile = Profile(email__iexact=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.ratealerts = True profile.is_synched = False profile.save() return redirect('thankyou_newsletter') else: send_ratealert_activation(request, signup) return redirect('signup_newsletter') elif NewsletterSignup.objects.filter(email__iexact=email).exists(): newssignup = NewsletterSignup.objects.get(email__iexact=email) if newssignup.is_activated: signup.is_activated = True signup.save() return redirect('thankyou_newsletter') else: send_ratealert_activation(request, signup) return redirect('signup_newsletter') else: send_ratealert_activation(request, signup) return redirect('signup_newsletter') else: return redirect('thankyou_newsletter') except RateAlertsSignup.DoesNotExist: ra = RateAlertsSignup() ra.email = email ra.is_synched = False ra.activation_key = str(uuid.uuid4()).replace('-','') while RateAlertsSignup.objects.filter(activation_key=ra.activation_key).exists(): ra.activation_key = str(uuid.uuid4()).replace('-','') ra.is_activated = False ra.save() send_ratealert_activation(request, ra) return redirect('signup_newsletter') return render_to_response(template_file, context_instance=context)
def activate_ratealert(request, key=None, template_file = 'common/signups/ratealertactivation.html'): context = RequestContext(request) signup = RateAlertsSignup.objects.get(activation_key=key) if not signup.is_activated: signup.is_activated = True signup.is_synched = False signup.save() if NewsletterSignup.objects.filter(email__iexact=signup.email).exists(): newssignup = NewsletterSignup.objects.get(email__iexact=signup.email) newssignup.is_activated = True newssignup.save() if User.objects.filter(email__iexact=signup.email).exists(): user = User.objects.get(email__iexact=signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() return render_to_response(template_file, context_instance=context)
def activate_newsletter(request, key, template_file = 'common/signups/newsletteractivation.html'): context = RequestContext(request) signup = NewsletterSignup.objects.get(activation_key=key) if not signup.is_activated: signup.is_activated = True signup.is_synched = False signup.save() if RateAlertsSignup.objects.filter(email__iexact=signup.email).exists(): rasignup = RateAlertsSignup.objects.get(email__iexact=signup.email) rasignup.is_activated = True rasignup.save() if User.objects.filter(active=True, email__iexact=signup.email).exists(): user = User.objects.get(is_active=True, email__iexact=signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() data = {'signup_id' : signup.id} context['raform'] = RateAlertsUpsellForm(initial=data) return render_to_response(template_file, context_instance=context)
def ExportUserProducts(modeladmin, request, queryset): today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') failed_users = [] fn = os.path.join(USER_EXPORT_PATH % date_format) f1 = open(fn, 'wb') fwr = csv.writer(f1, delimiter=',', quoting=csv.QUOTE_MINIMAL) fwr.writerow(['Email', 'Firstname', 'Surname', 'Provider', 'Product', 'Account Type', 'Balance', 'Deleted']) for file in queryset: csv_file = readers.UnicodeReader(open(file.csv_file.path, 'rb'), encoding='utf-8') for row in csv_file: try: user = User.objects.get(email__iexact=row[0]) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] varproducts = ProductPortfolio.objects.filter(user=user) fixedproducts = RatetrackerReminder.objects.filter(user=user) for varproduct in varproducts: fwr.writerow([user.email, user.first_name, user.last_name, varproduct.provider, varproduct.account_type, varproduct.product, varproduct.balance, varproduct.is_deleted]) for reminder in fixedproducts: fwr.writerow([user.email, user.first_name, user.last_name, reminder.provider, reminder.account_type, '', reminder.balance, reminder.is_deleted]) except Exception, ex: try: if not row[0] == "Email": failed_users.append(row[0]) failed_users.append(" because %s \n" % ex) except: failed_users.append(ex) file.has_been_run = True file.save() file.csv_file.close()
def handle_noargs(self, **options): newsletterList = NewsletterSignup.objects.all() ratealertsList = RateAlertsSignup.objects.all() failed_users = [] for newsletter in newsletterList: try: user = User.objects.get(email__iexact=newsletter.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() profile.newsletter = True profile.save() except User.DoesNotExist: pass except Exception as ex: failed_users.append(newsletter.email) failed_users.append(" because %s \n" % ex) for ratealert in ratealertsList: try: user = User.objects.get(email__iexact=ratealert.email) profile = user.profile profile.ratealert = True profile.save() except User.DoesNotExist: pass except Exception as ex: failed_users.append(ratealert.email) failed_users.append(" because %s \n" % ex) send_mail('Profile Status', "The following signups failed: %s " % "".join(failed_users), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False)
def Stage2Profile(email, first_name, surname, telephone): user = User.objects.get(email__iexact=email) user.first_name = first_name user.last_name = surname user.save() try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.telephone = telephone profile.is_synched = False profile.filled_in_name = True profile.save()
def change_user_email(request, template_file="administration/change_email/index.html"): context = RequestContext(request) if request.method == "POST": form = ChangeEmailForm(request.POST) if form.is_valid(): try: user = User.objects.get(email__iexact=form.cleaned_data.get('old_email')) except User.DoesNotExist: messages.error(request, 'User does not exist with this email.') return redirect('admininstrationindex') except User.MultipleObjectsReturned: messages.error(request, 'Multiple users were found for this email address.') return redirect('admininstrationindex') user.email = form.cleaned_data.get('new_email') user.save() try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() else: context['form'] = form else: context['form'] = ChangeEmailForm() return render_to_response(template_file, context_instance=context)
def check_user_status(request, template_file="administration/userstatus/status.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get( email__iexact=form.cleaned_data.get('email')) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if profile.skeleton_user: context[ 'status'] = "This user hasn't signed up to rate tracker yet, but has signed up for a reminder/instructions email, the newsletter, rate alerts or the concierge service" elif not profile.filled_in_name: context[ 'status'] = "This user never finished filling in their name on the initial signup" elif not user.is_active: context['status'] = "This user is inactive" else: context[ 'status'] = "User has signed up, probably has forgotten their password..." except User.DoesNotExist: context['status'] = "user doesn't exist" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def handle_noargs(self, **options): newsletterList = NewsletterSignup.objects.all() ratealertsList = RateAlertsSignup.objects.all() failed_users = [] for newsletter in newsletterList: try: user = User.objects.get(email__iexact=newsletter.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() profile.newsletter = True profile.save() except User.DoesNotExist: pass except Exception as ex: failed_users.append(newsletter.email) failed_users.append(" because %s \n" % ex) for ratealert in ratealertsList: try: user = User.objects.get(email__iexact=ratealert.email) profile = user.profile profile.ratealert = True profile.save() except User.DoesNotExist: pass except Exception as ex: failed_users.append(ratealert.email) failed_users.append(" because %s \n" % ex) send_mail('Profile Status', "The following signups failed: %s " % "".join(failed_users), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False)
def change_user_password( request, template_file="administration/change_password/index.html"): context = RequestContext(request) if request.method == "POST": form = ChangePasswordForm(request.POST) if form.is_valid(): try: user = User.objects.get( email__iexact=form.cleaned_data.get('email')) except User.DoesNotExist: messages.error(request, 'User does not exist with this email.') return redirect('admininstrationindex') except User.MultipleObjectsReturned: messages.error( request, 'Multiple users were found for this email address.') return redirect('admininstrationindex') new_password = form.cleaned_data.get('new_password') active = form.cleaned_data.get('active') user.set_password(new_password) if active: user.is_active = True try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() user.save() context[ 'message'] = "The password for %s has been changed" % user.email else: context['form'] = form else: context['form'] = ChangePasswordForm() return render_to_response(template_file, context_instance=context)
def change_user_email(request, template_file="administration/change_email/index.html"): context = RequestContext(request) if request.method == "POST": form = ChangeEmailForm(request.POST) if form.is_valid(): try: user = User.objects.get( email__iexact=form.cleaned_data.get('old_email')) except User.DoesNotExist: messages.error(request, 'User does not exist with this email.') return redirect('admininstrationindex') except User.MultipleObjectsReturned: messages.error( request, 'Multiple users were found for this email address.') return redirect('admininstrationindex') user.email = form.cleaned_data.get('new_email') user.save() try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() else: context['form'] = form else: context['form'] = ChangeEmailForm() return render_to_response(template_file, context_instance=context)
def finish_activation(request, template_file='common/signups/thankyou.html'): context = RequestContext(request) if request.method == "POST": form = RateAlertsUpsellForm(request.POST) if form.is_valid(): signup_id = form.cleaned_data.get('signup_id', None) signup = NewsletterSignup.objects.get(id=signup_id) email = signup.email if RateAlertsSignup.objects.filter(email__iexact=email).exists(): rasignup = RateAlertsSignup.objects.get(email__iexact=email) rasignup.is_activated = True rasignup.is_synched = False rasignup.save() else: rasignup = RateAlertsSignup() rasignup.email = email rasignup.is_activated = True rasignup.is_synched = False rasignup.save() if User.objects.filter(email__iexact=signup.email).exists(): user = User.objects.get(email__iexact=signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() return redirect('thankyou_newsletter') return render_to_response(template_file, context_instance=context)
def change_user_password(request, template_file="administration/change_password/index.html"): context = RequestContext(request) if request.method == "POST": form = ChangePasswordForm(request.POST) if form.is_valid(): try: user = User.objects.get(email__iexact=form.cleaned_data.get('email')) except User.DoesNotExist: messages.error(request, 'User does not exist with this email.') return redirect('admininstrationindex') except User.MultipleObjectsReturned: messages.error(request, 'Multiple users were found for this email address.') return redirect('admininstrationindex') new_password = form.cleaned_data.get('new_password') active = form.cleaned_data.get('active') user.set_password(new_password) if active: user.is_active = True try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] profile.is_synched = False profile.save() user.save() context['message'] = "The password for %s has been changed" % user.email else: context['form'] = form else: context['form'] = ChangePasswordForm() return render_to_response(template_file, context_instance=context)
def alert_adjustment_sync(self, django_client): synched_emails = [] synched = 0 sync_message = [] today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') fn = os.path.join(SALESFORCE_SYNC_ALERTS_PATH % date_format) f1 = open(fn, 'ab') SFResponseCodes =["SUCCESS", "ERR_USERID_EXISTS", "ERR_USERID_NOT_FOUND", "ERR_PORTFOLIOID_NOT_FOUND", "ERR_PORTFOLIOID_EXISTS"] # First, sync users associated with the newsletter news_signups = NewsletterSignup.objects.exclude(is_synched=True) for news_signup in news_signups: new_user = False try: user = User.objects.get(email__iexact=news_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(news_signup) profile = Profile() profile.user = user profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) sync_message.append("Newsletter, ") if profile.ratealerts: sync_message.append("Rate Alerts, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_sync(django_client, profile, user, new_user, bitmask) if returncode > 0: raise ResponseError(returncode) synched += 1 profile.is_synched = True profile.save() if CampaignsSignup.objects.filter(email=user.email).exists(): sync_message.append("Concierge, ") campaign_object = CampaignsSignup.objects.get(email=user.email) campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) news_signup.is_synched = True news_signup.save() if synched >= 400: break except ResponseError as e: send_mail('Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) # Secondly, sync users associated with rate alerts that aren't on the newsletter rate_signups = RateAlertsSignup.objects.exclude(is_synched=True) if synched < 400: for rate_signup in rate_signups: new_user = False try: user = User.objects.get(email__iexact=rate_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(rate_signup) profile = Profile() profile.user = user profile.newsletter = False profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) sync_message.append("Rate Alerts, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_sync(django_client, profile, user, new_user, bitmask) if returncode > 0: raise ResponseError(returncode) synched += 1 rate_signup.is_synched = True rate_signup.save() profile.is_synched = True profile.save() if CampaignsSignup.objects.filter(email=user.email).exists(): sync_message.append("Concierge, ") campaign_object = CampaignsSignup.objects.get(email=user.email) campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail('Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) # Lastly, sync the campaign signups that aren't on rate signups or news signups campaign_signups = CampaignsSignup.objects.exclude(is_synched=True) if synched < 400: for campaign_signup in campaign_signups: new_user = False first_name = '' last_name = '' try: user = User.objects.get(email__iexact=campaign_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() first_name = user.first_name last_name = user.last_name set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(campaign_signup) #user.is_active = True #requested by Jack Linstead for the rate tracker concierge emails. user.save() # Try and split out the name into something usable to pass across to Salesforce names = campaign_signup.name.split() profile = Profile() profile.user = user profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) try: if len(names) == 1: last_name = names[0] else: # Guesswork required, assume that only the last component is the last name last_name = names.pop() first_name = ' '.join(names) except: first_name = "Not Provided" last_name = "Not Provided" user.first_name = first_name user.last_name = last_name user.save() sync_message.append("Concierge, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_concierge_sync(django_client, profile, user, new_user, bitmask, campaign_signup, first_name, last_name) if returncode > 0: raise ResponseError(returncode) synched += 1 campaign_signup.is_synched = True campaign_signup.save() profile.is_synched = True profile.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail('Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) f1.close()
def sync_reminder_signup(self, SFResponseCodes, django_client, reminder_signup, sync_message, synched): new_user = False try: user = User.objects.get(email__iexact=reminder_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(reminder_signup) profile = Profile() profile.user = user profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) sync_message.append("Reminder, ") bitmask = get_bitmask(user) if bitmask > 0: returncode = 5 try: returncode = self._process_salesforce_sync(django_client, profile, user, new_user, bitmask) if returncode > 0: raise ResponseError(returncode) profile.is_synched = True profile.save() reminder_signup.is_synched = True reminder_signup.save() if synched >= 400: return except ResponseError as e: send_mail('Sync Error', "The following error occurred while syncing reminders or instructions for %s: %s" % ( profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False)
def create_concierge_client( request, template_file="administration/concierge_creation/index.html"): context = RequestContext(request) if request.method == "POST": form = ConciergeForm(request.POST) if form.is_valid(): form_email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') number = form.cleaned_data.get('number') try: user = User.objects.get(email__iexact=form_email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] user.first_name = first_name user.last_name = last_name user.is_active = True user.save() profile.telephone = number profile.is_synched = False profile.skeleton_user = False profile.filled_in_name = True profile.save() try: campaign_signup = CampaignsSignup.objects.get( email__iexact=form_email) except CampaignsSignup.DoesNotExist: campaign_signup = CampaignsSignup(email=form_email) campaign_signup.name = " ".join([first_name, last_name]) campaign_signup.telephone = number campaign_signup.is_client = True campaign_signup.is_synched = False campaign_signup.save() except User.DoesNotExist: try: campaign_signup = CampaignsSignup.objects.get( email__iexact=form_email) except CampaignsSignup.DoesNotExist: campaign_signup = CampaignsSignup() campaign_signup.email = form_email campaign_signup.name = " ".join([first_name, last_name]) campaign_signup.telephone = number campaign_signup.is_client = True campaign_signup.is_synched = False campaign_signup.save() user = User() user.is_active = True user.first_name = first_name user.last_name = last_name user.email = form_email user.username = MakeUsername() # This should be removed once messaging the client is brought in house user.skeleton_user = True # Set to stop concierge clients getting emails about rate tracker. user.save() profile = Profile() profile.user = user profile.telephone = number profile.skeleton_user = False profile.filled_in_name = True profile.is_synched = False profile.save() context[ 'message'] = "%s has now been changed to a concierge client, this will be reflected in Salesforce over the next 2-3mins" % user.email record_referral_signup(request, user, True, 'concierge_client', third_party=True) else: context['form'] = form else: context['form'] = ConciergeForm() return render_to_response(template_file, context_instance=context)
def sync_ratetracker_portfolio(self, product_portfolio_id): try: django_client = init_client() portfolio = ProductPortfolio.objects.get(pk=product_portfolio_id) user = portfolio.user # Get users rate tracker reminders # Ensure user has a profile, then update the bitmask by starting that task try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.is_synched = False profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] prt = django_client.factory.create('ProductPortfolio') prt.Balance = portfolio.balance prt.OpeningDate = portfolio.opening_date prt.Id = "pp%s" % portfolio.id prt.RateTrack = True latest_product_tier = portfolio.master_product.return_product_from_balance(portfolio.balance) prt.SCCode = latest_product_tier.sc_code prt.UserId = portfolio.user_id if portfolio.is_deleted: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted' ) statsd_client += 1 return_code = django_client.service.deleteRateTracker(portfolio.user_id, prt) if return_code == 2: raise ResponseError('Could not delete a product record on Salesforce, awaiting User creation') if return_code == 3: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted' ) statsd_client += 1 return_code = django_client.service.newRateTracker(portfolio.user_id, prt) if return_code == 0: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted' ) statsd_client += 1 return_code = django_client.service.deleteRateTracker(portfolio.user_id, prt) else: raise ResponseError('Could not create a new product record for deletion on Salesforce') else: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted' ) statsd_client += 1 return_code = django_client.service.newRateTracker(portfolio.user_id, prt) if return_code == 2: raise ResponseError('Could not create a new product record on Salesforce, awaiting User creation') if return_code == 4: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted' ) statsd_client += 1 return_code = django_client.service.updateRateTracker(portfolio.user_id, prt) if return_code == 0: portfolio.is_synched = True portfolio.save() else: # Profile Doesn't Exist Yet or has been deleted. portfolio.is_synched = False # # Process bitmask value for Salesforce except (WebFault, SalesforceAuthenticationFailed) as exc: pass
def alert_adjustment_sync(self, django_client): synched_emails = [] synched = 0 sync_message = [] today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') fn = os.path.join(SALESFORCE_SYNC_ALERTS_PATH % date_format) f1 = open(fn, 'ab') SFResponseCodes = [ "SUCCESS", "ERR_USERID_EXISTS", "ERR_USERID_NOT_FOUND", "ERR_PORTFOLIOID_NOT_FOUND", "ERR_PORTFOLIOID_EXISTS" ] # First, sync users associated with the newsletter news_signups = NewsletterSignup.objects.exclude(is_synched=True) for news_signup in news_signups: new_user = False try: user = User.objects.get(email__iexact=news_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(news_signup) profile = Profile() profile.user = user profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) sync_message.append("Newsletter, ") if profile.ratealerts: sync_message.append("Rate Alerts, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_sync( django_client, profile, user, new_user, bitmask) if returncode > 0: raise ResponseError(returncode) synched += 1 profile.is_synched = True profile.save() if CampaignsSignup.objects.filter( email=user.email).exists(): sync_message.append("Concierge, ") campaign_object = CampaignsSignup.objects.get( email=user.email) campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) news_signup.is_synched = True news_signup.save() if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) # Secondly, sync users associated with rate alerts that aren't on the newsletter rate_signups = RateAlertsSignup.objects.exclude(is_synched=True) if synched < 400: for rate_signup in rate_signups: new_user = False try: user = User.objects.get(email__iexact=rate_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(rate_signup) profile = Profile() profile.user = user profile.newsletter = False profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) sync_message.append("Rate Alerts, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_sync( django_client, profile, user, new_user, bitmask) if returncode > 0: raise ResponseError(returncode) synched += 1 rate_signup.is_synched = True rate_signup.save() profile.is_synched = True profile.save() if CampaignsSignup.objects.filter( email=user.email).exists(): sync_message.append("Concierge, ") campaign_object = CampaignsSignup.objects.get( email=user.email) campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) # Lastly, sync the campaign signups that aren't on rate signups or news signups campaign_signups = CampaignsSignup.objects.exclude(is_synched=True) if synched < 400: for campaign_signup in campaign_signups: new_user = False first_name = '' last_name = '' try: user = User.objects.get( email__iexact=campaign_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() first_name = user.first_name last_name = user.last_name set_initial_flags(user, profile) except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(campaign_signup) #user.is_active = True #requested by Jack Linstead for the rate tracker concierge emails. user.save() # Try and split out the name into something usable to pass across to Salesforce names = campaign_signup.name.split() profile = Profile() profile.user = user profile.skeleton_user = True profile.filled_in_name = False profile.save() set_initial_flags(user, profile) try: if len(names) == 1: last_name = names[0] else: # Guesswork required, assume that only the last component is the last name last_name = names.pop() first_name = ' '.join(names) except: first_name = "Not Provided" last_name = "Not Provided" user.first_name = first_name user.last_name = last_name user.save() sync_message.append("Concierge, ") bitmask = get_bitmask(user) if bitmask > 0: try: returncode = self._process_salesforce_concierge_sync( django_client, profile, user, new_user, bitmask, campaign_signup, first_name, last_name) if returncode > 0: raise ResponseError(returncode) synched += 1 campaign_signup.is_synched = True campaign_signup.save() profile.is_synched = True profile.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'], fail_silently=False) f1.close()
def get_bitmask(user): bitmask = 0 try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if not profile.skeleton_user and profile.filled_in_name: #ratetracker user bitmask += 8 if profile.newsletter: bitmask += 1 #WILL HAVE TO CHECK FOR ACTIVE if profile.ratealerts: bitmask += 2 if CampaignsSignup.objects.filter(email__iexact=user.email).exists(): #concierge ENQUIRY bitmask += 16 try: concierge = CampaignsSignup.objects.get(email__iexact=user.email) except CampaignsSignup.MultipleObjectsReturned: concierge = CampaignsSignup.objects.filter(email__iexact=user.email) concierge[1].delete() concierge = concierge[0] if concierge.is_client: bitmask += 32 if ReminderSignup.objects.filter(email__iexact=user.email).exists(): try: reminder = ReminderSignup.objects.get(email__iexact=user.email) except ReminderSignup.MultipleObjectsReturned: reminder = ReminderSignup.objects.filter(email__iexact=user.email) reminder[1].delete() reminder = reminder[0] if reminder.healthcheck: bitmask += 128 if reminder.bestbuys: bitmask += 64 reminder.is_synched = True reminder.save() if WeeklyRateAlert.objects.filter(email__iexact=user.email).exists(): try: weekly_rate_alert = WeeklyRateAlert.objects.get(email__iexact=user.email) except WeeklyRateAlert.MultipleObjectsReturned: weekly_rate_alert = WeeklyRateAlert.objects.filter(email__iexact=user.email) weekly_rate_alert[1].delete() weekly_rate_alert = weekly_rate_alert[0] if weekly_rate_alert.frequency == 1: bitmask += 256 elif weekly_rate_alert.frequency == 2: bitmask += 512 elif weekly_rate_alert.frequency == 3: bitmask += 1024 if IFASignup.objects.filter(email__iexact=user.email).exists(): bitmask += 2048 if BJSignup.objects.filter(email__iexact=user.email).exists(): bitmask += 4096 if Petition.objects.filter(email__iexact=user.email).exists(): bitmask += 8192 if SevenPitfallsSignup.objects.filter(email__iexact=user.email).exists(): bitmask += 16384 return bitmask
def create_stage_one_profile(request, email, source, send_activation=True, login_user=True, use_site_framework=True): user_created = False record_stats = False try: user = User.objects.get(email__iexact=email) except User.MultipleObjectsReturned: user = User.objects.filter(email__iexact=email).earliest('date_joined') # Found more than one account with this email, use the first one. except User.DoesNotExist: password = User.objects.make_random_password(50) # make a 50 char password for temporary use site = get_current_site(request) username = MakeUsername() user = RegistrationProfile.objects.create_inactive_user(site=site, send_email=send_activation, request=request, username=username, password=password, email=email) user_created = True try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles.earliest() if profile.skeleton_user: if request is not None: profile.ip_address = get_client_ip(request) else: profile.ip_address = '127.0.0.1' profile.save() elif send_activation and not user.is_active and not user_created: return redirect('resend_activation') elif login_user and user.is_active is True: return redirect('auth_login') Stage1Profile(user, request, source) if not email.endswith('@local'): record_referral_signup(request, user, user_created, 'signup') statsd_client = StatsDClient().get_counter_client( client_name='user.profile.created' ) statsd_client += 1 statsd_client = StatsDClient().get_counter_client( client_name='user.profile.created.{source}'.format( source=source ) ) statsd_client += 1 statsd_client = StatsDClient().get_counter_client( client_name='user.profile.created.{source}.{path}'.format( source=source, path=request.path ) ) statsd_client += 1 record_stats = True return user, user_created, record_stats
def create_concierge_client(request, template_file="administration/concierge_creation/index.html"): context = RequestContext(request) if request.method == "POST": form = ConciergeForm(request.POST) if form.is_valid(): form_email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') number = form.cleaned_data.get('number') try: user = User.objects.get(email__iexact=form_email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] user.first_name = first_name user.last_name = last_name user.is_active = True user.save() profile.telephone = number profile.is_synched = False profile.skeleton_user = False profile.filled_in_name = True profile.save() try: campaign_signup = CampaignsSignup.objects.get(email__iexact=form_email) except CampaignsSignup.DoesNotExist: campaign_signup = CampaignsSignup(email=form_email) campaign_signup.name = " ".join([first_name, last_name]) campaign_signup.telephone = number campaign_signup.is_client = True campaign_signup.is_synched = False campaign_signup.save() except User.DoesNotExist: try: campaign_signup = CampaignsSignup.objects.get(email__iexact=form_email) except CampaignsSignup.DoesNotExist: campaign_signup = CampaignsSignup() campaign_signup.email = form_email campaign_signup.name = " ".join([first_name, last_name]) campaign_signup.telephone = number campaign_signup.is_client = True campaign_signup.is_synched = False campaign_signup.save() user = User() user.is_active = True user.first_name = first_name user.last_name = last_name user.email = form_email user.username = MakeUsername() # This should be removed once messaging the client is brought in house user.skeleton_user = True # Set to stop concierge clients getting emails about rate tracker. user.save() profile = Profile() profile.user = user profile.telephone = number profile.skeleton_user = False profile.filled_in_name = True profile.is_synched = False profile.save() context[ 'message'] = "%s has now been changed to a concierge client, this will be reflected in Salesforce over the next 2-3mins" % user.email record_referral_signup(request, user, True, 'concierge_client', third_party=True) else: context['form'] = form else: context['form'] = ConciergeForm() return render_to_response(template_file, context_instance=context)
def sync_ratetracker_portfolio(self, product_portfolio_id): try: django_client = init_client() portfolio = ProductPortfolio.objects.get(pk=product_portfolio_id) user = portfolio.user # Get users rate tracker reminders # Ensure user has a profile, then update the bitmask by starting that task try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.is_synched = False profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] prt = django_client.factory.create('ProductPortfolio') prt.Balance = portfolio.balance prt.OpeningDate = portfolio.opening_date prt.Id = "pp%s" % portfolio.id prt.RateTrack = True latest_product_tier = portfolio.master_product.return_product_from_balance( portfolio.balance) prt.SCCode = latest_product_tier.sc_code prt.UserId = portfolio.user_id if portfolio.is_deleted: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted') statsd_client += 1 return_code = django_client.service.deleteRateTracker( portfolio.user_id, prt) if return_code == 2: raise ResponseError( 'Could not delete a product record on Salesforce, awaiting User creation' ) if return_code == 3: statsd_client = StatsDClient().get_counter_client( client_name= 'salesforce.sync_ratetracker_portfolio.attempted') statsd_client += 1 return_code = django_client.service.newRateTracker( portfolio.user_id, prt) if return_code == 0: statsd_client = StatsDClient().get_counter_client( client_name= 'salesforce.sync_ratetracker_portfolio.attempted') statsd_client += 1 return_code = django_client.service.deleteRateTracker( portfolio.user_id, prt) else: raise ResponseError( 'Could not create a new product record for deletion on Salesforce' ) else: statsd_client = StatsDClient().get_counter_client( client_name='salesforce.sync_ratetracker_portfolio.attempted') statsd_client += 1 return_code = django_client.service.newRateTracker( portfolio.user_id, prt) if return_code == 2: raise ResponseError( 'Could not create a new product record on Salesforce, awaiting User creation' ) if return_code == 4: statsd_client = StatsDClient().get_counter_client( client_name= 'salesforce.sync_ratetracker_portfolio.attempted') statsd_client += 1 return_code = django_client.service.updateRateTracker( portfolio.user_id, prt) if return_code == 0: portfolio.is_synched = True portfolio.save() else: # Profile Doesn't Exist Yet or has been deleted. portfolio.is_synched = False # # Process bitmask value for Salesforce except (WebFault, SalesforceAuthenticationFailed) as exc: pass
def alert_adjustment_sync(self, django_client, news_signups, rate_signups, campaign_signups): synched_emails = [] synched = 0 sync_message = [] today = datetime.datetime.now() date_format = today.strftime('%Y%m%d') fn = os.path.join(SALESFORCE_SYNC_ALERTS_PATH % date_format) f1 = open(fn, 'ab') SFResponseCodes = [ "SUCCESS", "ERR_USERID_EXISTS", "ERR_USERID_NOT_FOUND", "ERR_PORTFOLIOID_NOT_FOUND", "ERR_PORTFOLIOID_EXISTS" ] # First, sync users associated with the newsletter for news_signup in news_signups: new_user = False try: user = User.objects.get(email__iexact=news_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() if profile.ratealerts: sync_message.append("Rate Alerts, ") except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(news_signup) profile = Profile() profile.user = user profile.skeleton_user = True profile.save() if self._in_other_list(user.email, rate_signups): profile.ratealerts = True sync_message.append("Rate Alerts, ") except Exception as ex: print "The following %s caused %s" % (news_signup, ex) profile.newsletter = True sync_message.append("Newsletter, ") bitmask = self._get_subscription_bitmask(profile) if self._in_other_list(user.email, campaign_signups): bitmask += 16 sync_message.append("Concierge, ") if ProductPortfolio.objects.filter(user=user).count() > 0: sync_message.append("Rate Tracker, ") bitmask += 8 elif RatetrackerReminder.objects.filter(user=user).count() > 0: sync_message.append("Rate Tracker, ") bitmask += 8 elif not new_user: bitmask += 8 try: returncode = 0 if returncode > 0: raise ResponseError(returncode) synched += 1 profile.is_synched = True profile.save() news_signup.is_synched = True news_signup.save() if profile.ratealerts: try: ratealert_object = RateAlertsSignup.objects.get( email=user.email) except RateAlertsSignup.DoesNotExist: ratealert_object = RateAlertsSignup() ratealert_object.is_synched = True ratealert_object.save() if self._in_other_list(user.email, campaign_signups): campaign_object = CampaignsSignup.objects.get( email=user.email) campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, settings.CSV_EXPORT_RECIPIENTS, fail_silently=False) except Exception as ex: print "The following %s caused %s" % (news_signup, ex) # Secondly, sync users associated with rate alerts that aren't on the newsletter if synched < 400: for rate_signup in rate_signups: if rate_signup.email not in synched_emails: new_user = False try: user = User.objects.get( email__iexact=rate_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(rate_signup) profile = Profile() profile.user = user profile.newsletter = False profile.skeleton_user = True profile.save() except Exception as ex: print "The following %s caused %s" % (rate_signup, ex) profile.ratealerts = True sync_message.append("Rate Alerts, ") bitmask = self._get_subscription_bitmask(profile) if self._in_other_list(user.email, campaign_signups): bitmask += 16 sync_message.append("Concierge, ") if ProductPortfolio.objects.filter(user=user).count() > 0: bitmask += 8 sync_message.append("Rate Tracker, ") elif RatetrackerReminder.objects.filter( user=user).count() > 0: bitmask += 8 sync_message.append("Rate Tracker, ") elif not new_user: bitmask += 8 try: returncode = 0 if returncode > 0: raise ResponseError(returncode) synched += 1 rate_signup.is_synched = True rate_signup.save() profile.is_synched = True profile.save() if self._in_other_list(user.email, campaign_signups): campaign_object = CampaignsSignup.objects.get( email=user.email) if not profile.newsletter and campaign_object.newsletter: profile.newsletter = True profile.is_synched = True profile.save() campaign_object.is_synched = True campaign_object.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, settings.CSV_EXPORT_RECIPIENTS, fail_silently=False) except Exception as ex: print "The following %s caused %s" % (rate_signup, ex) # Lastly, sync the campaign signups that aren't on rate signups or news signups if synched < 400: for campaign_signup in campaign_signups: if campaign_signup.email not in synched_emails: new_user = False first_name = '' last_name = '' try: user = User.objects.get( email__iexact=campaign_signup.email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() if campaign_signup.newsletter: profile.newsletter = True sync_message.append("Newsletter, ") except User.DoesNotExist: new_user = True user = self._create_new_user_skeleton(campaign_signup) #user.is_active = True #requested by Jack Linstead for the rate tracker concierge emails. user.save() # Try and split out the name into something usable to pass across to Salesforce names = campaign_signup.name.split() profile = Profile() profile.user = user profile.skeleton_user = True profile.save() try: if len(names) == 1: last_name = names[0] else: # Guesswork required, assume that only the last component is the last name last_name = names.pop() first_name = ' '.join(names) except: first_name = "Not Provided" last_name = "Not Provided" if campaign_signup.newsletter: profile.newsletter = True sync_message.append("Newsletter, ") profile.ratealerts = False user.first_name = first_name user.last_name = last_name user.save() sync_message.append("Concierge, ") bitmask = self._get_subscription_bitmask(profile) bitmask += 16 if ProductPortfolio.objects.filter(user=user).count() > 0: bitmask += 8 sync_message.append("Rate Tracker, ") elif RatetrackerReminder.objects.filter( user=user).count() > 0: bitmask += 8 sync_message.append("Rate Tracker, ") elif not new_user: bitmask += 8 try: returncode = 0 if returncode > 0: raise ResponseError(returncode) synched += 1 campaign_signup.is_synched = True campaign_signup.save() profile.is_synched = True profile.save() if profile.newsletter: try: newsletter = NewsletterSignup.objects.get( email=campaign_signup.email) except NewsletterSignup.DoesNotExist: newsletter = NewsletterSignup() newsletter.email = user.email newsletter.is_synched = True newsletter.save() f1.write("Synced %s for %s \n" % ("".join(sync_message), user.email)) sync_message = [] synched_emails.append(user.email) if synched >= 400: break except ResponseError as e: send_mail( 'Sync Error', "The following error occurred while syncing alerts for %s: %s" % (profile.user.email, SFResponseCodes[returncode]), settings.DEFAULT_FROM_EMAIL, settings.CSV_EXPORT_RECIPIENTS, fail_silently=False) except Exception as ex: print "The following %s caused %s" % (campaign_signup, ex) f1.close()
def BasketInitialProfile(email, first_name=None, surname=None, telephone = None, newsletter=False, ratealert=False): user = User.objects.get(email__iexact=email) try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if first_name and surname: user.first_name = first_name user.last_name = surname user.save() profile.filled_in_name = True profile.telephone = telephone profile.newsletter = newsletter profile.ratealerts = ratealert profile.is_synched = False profile.source = "Basket" profile.save()