Example #1
0
    def save(self, sender):
        def save_message_date():
            message = UnregisteredMessage()
            message.save()

        lines = []
        first_name, last_name = get_name(self.cleaned_data['name'])
        lines.append("From: %s %s" % (first_name, last_name))

        if self.cleaned_data['email']:
            lines.append("Email: %s" % self.cleaned_data['email'])

        lines.append("")

        if self.cleaned_data['note']:
            lines.append("%s" % self.cleaned_data['note'])

        message = "\n".join(lines)
        ctx = {
            "SITE_NAME": settings.SITE_NAME,
            "sender": "%s %s" % (first_name, last_name),
            "message": message
        }

        subject = render_to_string(
            "account/emails/send_message_unregistered_subject.txt", ctx)

        send_hs_mail(subject,
                     "account/emails/send_message_unregistered_body.txt", ctx,
                     settings.DEFAULT_FROM_EMAIL, [self.recipient])
        save_message_date()
Example #2
0
 def mail_matched_searches(self):
     params = {
         'remote_healing':
         self.remote_healing,
         'trade_for_services':
         self.trade_for_services,
         'cost_per_session':
         self.cost_per_session,
         'specialities_ids':
         self.specialities.all().values_list('id', flat=True),
         'speciality_categories':
         self.speciality_categories.all().values_list('id', flat=True),
         'location':
         self.location,
     }
     queryset = HealingRequestSearch.search(params)
     subject = 'New Healing Request matching your saved search'
     for obj in queryset:
         search_link = full_url(
             reverse('show_healing_request_search', args=[obj.id]))
         request_link = full_url(
             reverse('show_healing_request', args=[self.id]))
         context = {
             'search_link': search_link,
             'title': self.title,
             'description': self.description,
             'request_link': request_link
         }
         send_hs_mail(subject,
                      'healing_requests/emails/new_matched_request.txt',
                      context, settings.DEFAULT_FROM_EMAIL,
                      [obj.user.email])
Example #3
0
    def handle(self, *args, **options):
        def get_providers_with_no_location():
            providers = healers.filter(remote_sessions=False)
            providers_with_no_location = []
            for provider in providers:
                if not provider.get_locations():
                    providers_with_no_location.append(provider)
            return providers_with_no_location

        healers = Healer.objects.filter(is_deleted=False, user__is_active=True)

        providers_blank = healers.filter(
            Q(user__avatar__isnull=True) | Q(about='')).distinct()

        providers_no_modality = healers.annotate(
            modality_count=Count('modality')).filter(modality_count=0)
        # filter wellness centers because of specialities of their providers
        providers_no_modality = (provider for provider in providers_no_modality
                                 if not is_wellness_center(provider)
                                 or not provider.has_specialities())

        providers = set(
            list(providers_blank) + list(providers_no_modality) +
            get_providers_with_no_location())

        username = options['username']
        for provider in providers:
            if username and provider.user.username != username:
                continue

            lastdate = provider.profile_completeness_reminder_lastdate
            interval = provider.profile_completeness_reminder_interval
            if username or not lastdate or lastdate + timedelta(
                    weeks=interval) <= date.today():
                site_base = unicode(Site.objects.get_current())
                ctx = {
                    'first_name':
                    provider.user.first_name,
                    'reminder_interval_link':
                    get_full_url('healer_edit'),
                    'change_reminder_interval_url':
                    get_full_url('healer_change_profile_reminder_interval'),
                    'change_reminder_interval_options':
                    Healer.PROFILE_REMINDER_INTERVAL_CHOICES,
                    'fill_warning_links':
                    get_fill_warning_links(provider),
                    'site_base':
                    site_base
                }
                subject = render_to_string(
                    "healers/emails/profile_reminder_subject.txt", ctx)
                send_hs_mail(subject,
                             'healers/emails/profile_reminder_message.txt',
                             ctx, settings.DEFAULT_FROM_EMAIL,
                             [provider.user.email])
                provider.profile_completeness_reminder_lastdate = date.today()
                provider.save()
Example #4
0
    def send_reminders(self, healer, client):
        if not client.user.email:
            return

        ctx = {
            'healer_name': unicode(healer.user.client),
            'healer_first_name':
            healer.user.first_name.encode('ascii', 'replace'),
            'review_url': get_full_url('review_form',
                                       args=[healer.user.username])
        }
        from_email = settings.DEFAULT_FROM_EMAIL
        subject = render_to_string('review/emails/reminder_subject.txt', ctx)
        send_hs_mail(subject, 'review/emails/reminder_message.txt', ctx,
                     from_email, [client.user.email])
Example #5
0
def mail_healer_after_intake_form_answered(client, healer):
	inbox_link = render_to_string("email_link.html", {'link': full_url(reverse('messages_inbox'))})
	schedule_link = render_to_string("email_link.html", {'link': full_url(reverse('schedule'))})

	subject = render_to_string("intake_forms/emails/send_healer_after_intake_form_subject.html", client)

	context = view_intake_form_answer_context(**{
		'healer': healer.user.username,
		'client': client.user.username,
	})

	context.update({
		'inbox_link': inbox_link,
		'schedule_link': schedule_link,
		'client': unicode(client)
	})

	from healers.utils import send_hs_mail
	send_hs_mail(subject, 'intake_forms/emails/send_healer_after_intake_form_body.txt',
		context, settings.DEFAULT_FROM_EMAIL, [healer.user.email])
Example #6
0
    def send_confirmation(self, email_address, **kwargs):
        salt = hashlib.sha1(str(random())).hexdigest()[:5]
        confirmation_key = hashlib.sha1(salt + email_address.email).hexdigest()
        current_site = Site.objects.get_current()
        # check for the url with the dotted view path
        try:
            path = reverse("emailconfirmation.views.confirm_email",
                           args=[confirmation_key])
        except NoReverseMatch:
            # or get path with named urlconf instead
            path = reverse("emailconfirmation_confirm_email",
                           args=[confirmation_key])
        activate_url = absolute_url(path)
        if 'next' in kwargs and kwargs['next']:
            activate_url += '?next=' + kwargs['next']
        context = {
            "user": email_address.user,
            "activate_url": activate_url,
            "email_template_header_url": activate_url,
            "current_site": current_site,
            "confirmation_key": confirmation_key,
            "recipient_email": email_address.email,
        }
        subject = render_to_string(
            "emailconfirmation/email_confirmation_subject.txt", context)
        # remove superfluous line breaks
        subject = "".join(subject.splitlines())
        #		message = render_to_string(
        #			"emailconfirmation/email_confirmation_message.txt", context)

        from_email = settings.DEFAULT_FROM_EMAIL
        recipient_list = [email_address.email]
        #		message_html = message.replace("\n", "</br>")
        send_hs_mail(subject,
                     "emailconfirmation/email_confirmation_message.txt",
                     context, from_email, recipient_list)

        return self.create(email_address=email_address,
                           sent=datetime.now(),
                           confirmation_key=confirmation_key)
Example #7
0
    def notify(self):
        ctx = {
            'review':
            self,
            'is_need_client_approval':
            ClientInvitation.objects.filter(from_user=self.reviewer.user,
                                            to_user=self.healer.user,
                                            status=2).count() > 0,
            'approve_url':
            get_full_url('friend_accept',
                         args=['clients', self.reviewer.user.id]),
            'decline_url':
            get_full_url('friend_decline',
                         args=['clients', self.reviewer.user.id])
        }

        from_email = settings.DEFAULT_FROM_EMAIL
        subject = render_to_string('review/emails/notify_subject.txt', ctx)

        from healers.utils import send_hs_mail
        send_hs_mail(subject, 'review/emails/notify_body.txt', ctx, from_email,
                     [self.healer.user.email])
Example #8
0
 def get_google_calendar(healer):
     try:
         google_calendar = GoogleCalendar(healer.user)
         healer.google_calendar_sync_retries = 0
     except oauth2client.client.Error:
         healer.google_calendar_sync_retries += 1
         google_calendar = None
         # exc_type = sys.exc_info()[0]
         # error_report(1, "Cal Sync Error %s - %s - %s" % (exc_type, str(e), healer.user))
         if healer.google_calendar_sync_retries >= settings.MAX_GCAL_SYNC_RETRIES:
             disable_google_sync(healer)
             send_hs_mail(
                 'Google Calendar Sync Disabled',
                 'sync_hs/email_calendar_disabled.txt', {
                     'MAX_GCAL_SYNC_RETRIES':
                     settings.MAX_GCAL_SYNC_RETRIES,
                     'google_calendar_sync_link':
                     get_full_url('google_calendar_instruction')
                 },
                 settings.DEFAULT_FROM_EMAIL, [healer.user.email],
                 bcc=[admin[1] for admin in settings.ADMINS])
             healer.google_calendar_sync_retries = 0
     healer.save()
     return google_calendar
Example #9
0
    def post(self, request, format=None):
        def get_signup_form_class():
            if signup_type == 'client':
                if no_name:
                    return ClientSignupNoNameForm
                return ClientSignupForm
            elif signup_type == 'healer':
                return HealerSignupForm
            elif signup_type == 'wellness_center':
                return WellnessCenterSignupForm

        def process_form():
            """Returns:
				user, signup_message, redirect_url."""
            user = form.save(next=request.session.pop('signup_next', ''),
                             is_superuser=is_superuser,
                             cookies=request.COOKIES)
            # Add to unapproved clients
            healer_username = request.session.pop('signup_healer', '')
            if healer_username:
                try:
                    healer_user = User.objects.get(
                        username__iexact=healer_username)
                    invite_or_create_client_friendship(
                        client_user=user,
                        healer_user=healer_user,
                        send_client_request_email=False)
                except User.DoesNotExist:
                    pass

            if is_superuser:
                message = 'User %s has been successfully created.' % user.get_full_name(
                )
                return user, message, None

            # Meant to resolve #964
            try:
                email = EmailAddress.objects.get(user=user)  # added DGL
            except EmailAddress.DoesNotExist:
                # user = User.objects.filter(first_name=form.cleaned_data["first_name"],
                # 	last_name=form.cleaned_data["last_name"]).order_by('-date_joined')[0]
                email = EmailAddress.objects.create(user=user,
                                                    email=user.email,
                                                    verified=False,
                                                    primary=True)
                EmailConfirmation.objects.send_confirmation(email)

            set_signup_source(user, self.request, is_phonegap)

            # get for phonegap backward compatibility:
            post_signup_processing(user,
                                   qd.get('is_ambassador', 0) == '1',
                                   request.session)

            if settings.ACCOUNT_EMAIL_VERIFICATION and not email.verified:
                if signup_type != 'client' and not is_phonegap:
                    form.login(request, user)
                return user, None, None
            else:
                form.login(request, user)
                return user, None, reverse('what_next')

        def get_url():
            if is_phonegap:
                if 'next_url' in qd:
                    return qd['next_url']
                else:
                    return 'signup_thanks_%s.html' % signup_type
            thanks_url = reverse('signup_thanks', args=[signup_type])
            plugin_value = qd.get(PLUGIN_KEY, False)
            if plugin_value:
                return '{}?{}={}'.format(thanks_url, PLUGIN_KEY, plugin_value)
            return thanks_url

        try:
            data = request.POST['data'].encode('utf-8')
            is_phonegap = json.loads(request.POST['is_phonegap'])
        except:
            return HttpResponseBadRequest()

        qd = QueryDict(data)
        signup_type = qd['type']
        no_name = qd.get('no_name', False)
        form_class = get_signup_form_class()

        is_superuser = qd.get('is_superuser', False)
        if is_superuser:
            if not request.user.is_superuser:
                raise Http404
        form = form_class(qd)

        if form.is_valid():
            user, thanks_message, redirect_url = process_form()
            if redirect_url is not None:
                return Response({'redirect_url': redirect_url})
            if form_class != ClientSignupForm:
                ctx_email = {
                    "first_name":
                    user.first_name,
                    "last_name":
                    user.last_name,
                    "email":
                    user.email,
                    "username":
                    user.username,
                    "provider_url":
                    ''.join(
                        [get_current_site(request).domain, '/', user.username])
                }
                send_hs_mail('New Provider', "admin/new_provider_message.txt",
                             ctx_email, settings.DEFAULT_FROM_EMAIL,
                             settings.EMAIL_ON_SIGNUP)

            if is_superuser:
                message = render_to_string('about/thanks.html', {
                    'thanks_message': thanks_message,
                    'thanks_title': 'Success'
                })
                return Response({'message': message})

            return Response({'url': get_url(), 'email': user.email})

        errors, error_elements, error_list_pg_bc = get_errors(form)

        return Response({
            'errors': errors,
            'error_elements': error_elements,
            'error_list': error_list_pg_bc
        })  # error_list_pg_bc for pg backward compatibility
Example #10
0
def send_message(request, data, is_registered, source=None):
	dajax = Dajax()

#	sender = request.user
	if is_registered:
		form = ComposeForm(QueryDict(data))
		if form.is_valid():
			sender = str(request.user.client)

			lines = []
			lines.append("From: %s" % sender)
			lines.append("Email: %s" % request.user.email)
			lines.append("")
			lines.append("Subject: %s" % form.cleaned_data['subject'])
			lines.append("")
			lines.append(form.cleaned_data['body'])

			message = "\n".join(lines)

			ctx = {
				"SITE_NAME": settings.SITE_NAME,
				"sender": sender,
				"message": message,
				"reply_url": absolute_url(reverse('messages_inbox'))
			}

			subject = render_to_string("account/emails/send_message_unregistered_subject.txt", ctx)

			send_hs_mail(subject, "account/emails/send_message_unregistered_body.txt", ctx, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data['recipient'][0].email])

	else:
		qd = QueryDict(data)

		try:
			recipient = Healer.objects.get(user__username__iexact=qd['recipient_username'])
		except Healer.DoesNotExist:
			return

		form = ComposeFormUnregistered(qd)
		form.recipient = recipient.user.email

	dajax.remove_css_class('#new_message_form input','error')
	dajax.remove_css_class('#new_message_form textarea','error')
	if form.is_valid():
		m = form.save(sender=request.user)
		if source:
			MessageExtra.objects.create(message=m[0], source=source)
#		request.user.message_set.create(
#			message=_(u"Message successfully sent."))
#		success_url = reverse('messages_inbox')
#		if request.GET.has_key('next'):
#			success_url = request.GET['next']

		dajax.script("new_message_success();")

	else:
		for error in form.errors:
			if error == "captcha":
				css_class = '#new_message_form #id_%s_1'
			else:
				css_class = '#new_message_form #id_%s'
			dajax.add_css_class(css_class % error,'error')

	#update captcha
	challenge, response = captcha_settings.get_challenge()()
	store = CaptchaStore.objects.create(challenge=challenge, response=response)
	dajax.assign('img.captcha', 'src', reverse('captcha-image',kwargs=dict(key=store.hashkey)))
	dajax.assign('#id_msg_security_verification_0', 'value', store.hashkey)
	dajax.assign('#id_msg_security_verification_1', 'value', '')

	return dajax.json()

#def new_message_form_processor(request):
#
#	if request.user.is_authenticated():
#		new_message_form = ComposeForm()
#	else:
#		new_message_form = None
#
#	return { "new_message_form" : new_message_form }
Example #11
0
	def post(self, request, format=None):
		try:
			data = request.POST['data'].encode('utf-8')
			source = request.POST.get('source', None)
		except:
			return HttpResponseBadRequest()

		if request.user.is_authenticated():
			form = ComposeForm(QueryDict(data))
			if form.is_valid():
				sender = str(request.user.client)

				lines = []
				lines.append("From: %s" % sender)
				lines.append("Email: %s" % request.user.email)
				lines.append("")
				lines.append("Subject: %s" % form.cleaned_data['subject'])
				lines.append("")
				lines.append(form.cleaned_data['body'])

				message = "\n".join(lines)

				ctx = {
					"SITE_NAME": settings.SITE_NAME,
					"sender": sender,
					"message": message,
					"reply_url": absolute_url(reverse('messages_inbox'))
				}

				subject = render_to_string("account/emails/send_message_unregistered_subject.txt", ctx)

				send_hs_mail(subject, "account/emails/send_message_unregistered_body.txt", ctx, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data['recipient'][0].email])

		else:
			qd = QueryDict(data)

			try:
				recipient = Healer.objects.get(user__username__iexact=qd['recipient_username'])
			except Healer.DoesNotExist:
				return

			form = ComposeFormUnregistered(qd)
			form.recipient = recipient.user.email

		if form.is_valid():
			m = form.save(sender=request.user)
			if source:
				MessageExtra.objects.create(message=m[0], source=source)
	#		request.user.message_set.create(
	#			message=_(u"Message successfully sent."))
	#		success_url = reverse('messages_inbox')
	#		if request.GET.has_key('next'):
	#			success_url = request.GET['next']

		#update captcha
		challenge, captcha_response = captcha_settings.get_challenge()()
		store = CaptchaStore.objects.create(challenge=challenge, response=captcha_response)
		errors, error_elements, _ = get_errors(form)

		return Response({'errors': errors,
						'error_elements': error_elements,
						'captcha': {
							'img': reverse('captcha-image', kwargs=dict(key=store.hashkey)),
							'code': store.hashkey}})
Example #12
0
 def email_data(self, user):
     send_hs_mail('New concierge request', "healers/emails/concierge.txt",
                  self.data, settings.DEFAULT_FROM_EMAIL, [user.email])
Example #13
0
    def post(self, request, format=None):
        try:
            data = request.POST['data'].encode('utf-8')
        except:
            return HttpResponseBadRequest()

        form = SendReferralForm(QueryDict(data))

        if not form.is_valid():
            errors = []
            for error in form.errors:
                css_class = '#referral_form #referral_%s'
                errors.append(css_class % error)
            return Response({'errors': errors})

        client_or_healer = form.cleaned_data['client_or_healer']
        from_user = get_object_or_404(
            User, username__iexact=form.cleaned_data['from_username'])
        to_user = form.cleaned_data['to_user']

        if client_or_healer == ReferralsSent.PROVIDER_TO_CLIENT:
            provider = from_user
            client = to_user
        else:
            provider = to_user
            client = from_user

        is_referral_sent = ReferralsSent.objects.filter(
            provider_user=provider,
            client_user=client,
            referring_user=request.user).count()

        if is_my_client(provider, client):
            message = "%s was already a client of %s." % (client.client,
                                                          provider.client)

        elif is_referral_sent:
            message = "You already referred %s to %s before." % (
                client.client, provider.client)

        else:
            mail_message = form.cleaned_data['message']

            ReferralsSent.objects.create(referring_user=request.user,
                                         provider_user=provider,
                                         client_user=client,
                                         message=mail_message)

            if client_or_healer == ReferralsSent.CLIENT_TO_PROVIDER:
                ctx = {
                    "SITE_NAME": settings.SITE_NAME,
                    "client": client,
                    "client_info": client.client.contact_info(),
                    "referer": request.user,
                    "mail_message": mail_message
                }
                subject = render_to_string(
                    "friends/refer_client_to_provider_subject.txt", ctx)
                send_hs_mail(subject,
                             "friends/refer_client_to_provider_message.txt",
                             ctx, settings.DEFAULT_FROM_EMAIL,
                             [provider.email])

                if not Referrals.objects.refers_to(provider, client):
                    Clients.objects.filter(from_user=request.user,
                                           to_user=provider).delete()
                    if not Referrals.objects.filter(from_user=request.user,
                                                    to_user=provider).exists():
                        friendship = Referrals.objects.create(
                            from_user=request.user, to_user=provider)
                        friendship.save()
            else:
                provider_profile = provider.client.healer
                friendship, is_profile_visible, ctx = get_healer_info_context(
                    provider_profile, request)
                ctx["info_only"] = True

                ctx.update({
                    "SITE_NAME": settings.SITE_NAME,
                    "STATIC_URL": settings.STATIC_URL,
                    "provider": provider_profile,
                    "referer": request.user,
                    "mail_message": mail_message
                })
                subject = render_to_string(
                    "friends/refer_provider_to_client_subject.txt", ctx)
                send_hs_mail(subject,
                             "friends/refer_provider_to_client_message.txt",
                             ctx,
                             settings.DEFAULT_FROM_EMAIL, [client.email],
                             html_template_name=
                             "friends/refer_provider_to_client_message.html")

            #update refers model

            message = "You refered %s to %s." % (client.client,
                                                 provider.client)

        return Response(message)