コード例 #1
0
def client(request, username, template_name="clients/clients_profile.html"):
    client = get_object_or_404(Client, user__username__iexact=username)

    healer = is_healer(client)
    if healer:
        return redirect(healer.healer_profile_url())

    contact_info = None
    if is_healer(request.user):
        try:
            contact_info = ContactInfo.objects.get(healer__user=request.user,
                                                   client=client)
        except ContactInfo.DoesNotExist:
            pass

    is_profile_visible = Clients.objects.are_friends(request.user, client.user)

    request.friend_type = "clients"
    request.other_user = client.user
    return render_to_response(
        template_name,
        {
            "is_profile_visible": is_profile_visible,
            "phone_numbers": client.phone_numbers.all(),
            "is_me": client.user == request.user,
            "contact_info": contact_info,
            #		"other_user": other_user,
        },
        context_instance=RequestContext(request, {}, [friend_bar_processor]))
コード例 #2
0
    def test_client_as_ambassador(self):
        self.signup('client', True)

        c = Client.objects.filter(user__email=self.email)
        self.assertEqual(c.count(), 1)
        self.assertEqual(c[0].ambassador_program, True)
        self.assertFalse(is_healer(c[0]))
コード例 #3
0
def impersonate(request, username):
    """Login as selected user."""
    request_user = request.user
    original_user = request.session.get('original_user', False)
    if original_user:
        if not get_object_or_404(User, username=original_user).is_superuser:
            raise Http404
    elif not request_user.is_superuser:
        raise Http404

    new_user = get_object_or_404(User, username=username)
    login_user(request, new_user)

    if not original_user:
        request.session['original_user'] = request_user.username

    elif original_user == new_user.username:
        request.session['original_user'] = None

    else:
        request.session['original_user'] = original_user

    #if original_user:
    #    if original_user != new_user.profile:
    #        request.session['original_user'] = original_user
    #elif request_user != new_user:
    #    request.session['original_user'] = request_user.profile

    if is_healer(new_user):
        return redirect('what_next')
    else:
        return redirect('home')
コード例 #4
0
def import_google_contacts(request):
    if not is_healer(request.user):
        raise Http404

    try:
        google_contacts = GoogleContacts(request.user)
    except oauth2client.client.Error:
        request.session['oauth_callback_redirect'] = 'import_google_contacts'
        return redirect('oauth2_google_login')

    healer = request.user.client.healer

    # check running import from any api
    import_status = ContactsImportStatus.objects.filter(user=healer.user,
                                                        status=STATUS_RUNNING)
    if import_status.count() > 0:
        return redirect('import_contacts_status')

    # remove all previous statuses and run
    ContactsImportStatus.objects.filter(user=healer.user).delete()
    import_status = ContactsImportStatus.objects.create(user=healer.user,
                                                        api=GOOGLE_API,
                                                        status=STATUS_RUNNING)
    import_google_contact_process(healer, google_contacts, import_status)

    response = redirect('import_contacts_status')
    if request.GET.get('fb', 0):
        response['Location'] += '?fb=1'
    return response
コード例 #5
0
    def test_join_invitation_success(self):
        from_user = User.objects.get(id=1)
        email = '*****@*****.**'
        contact, created = Contact.objects.get_or_create(email=email,
                                                         user=from_user)
        SiteJoinInvitation.objects.create(from_user=from_user,
                                          contact=contact,
                                          message="",
                                          status="2",
                                          confirmation_key="123",
                                          is_to_healer=True)

        fb_data = {
            'first_name': 'test1',
            'last_name': 'test2',
            'email': email,
            'id': '1'
        }
        user = facebook_callback.handle_no_user(self.request,
                                                self.oauth_access, fb_data,
                                                'healer')

        self.assertEqual(user.email, fb_data['email'])
        self.assertFalse(user.has_usable_password())
        self.assertTrue(user.is_active)
        self.assertTrue(is_healer(user.client))
コード例 #6
0
 def test_client_as_ambassador(self):
     self.data['is_ambassador'] = '1'
     response = self.signup()
     self.assertEqual(response['email'], self.email)
     c = Client.objects.filter(user__email=self.email)
     self.assertEqual(c.count(), 1)
     self.assertEqual(c[0].ambassador_program, True)
     self.assertFalse(is_healer(c[0]))
コード例 #7
0
def disable_stripe_connect(request):
    UserAssociation.objects.filter(user=request.user,
                                   service='stripe').delete()
    healer = is_healer(request.user)
    healer.gift_certificates_enabled = False
    healer.booking_healersource_fee = Healer.BOOKING_HEALERSOURCE_FEE_PERCENTAGE
    healer.save()
    return healers.views.payments_settings(
        request, message='Stripe Connect has been disabled.')
コード例 #8
0
def client_detail(request, client_username):
    try:
        client = Client.objects.get(user__username__iexact=client_username)
    except Client.DoesNotExist:
        return HttpResponse("<h3>Oops!</h3>Sorry, couldn't find that Client")

    client_info = client.contact_info(separator='<br />', email_link=True)
    if request.user != client.user and not is_my_client(
            request.user, client.user):
        client_info = None

    contact_info = client.get_contact_info(request.user.client)
    contact_info_text = None
    if contact_info:
        contact_info_text = contact_info.text(separator='<br />',
                                              email_link=True)

    healer_link = None
    healer = is_healer(client)
    logged_in_healer = Healer.objects.get(user=request.user)
    if healer:
        healer_link = healer.healer_profile_url()

    c = {
        'has_intake_form':
        logged_in_healer.has_intake_form(),
        'client':
        client,
        'user':
        request.user,
        'client_info':
        client_info,
        'contact_info':
        contact_info,
        'contact_info_text':
        contact_info_text,
        'healer_link':
        healer_link,
        'answered_intake_form':
        client.answered_intake_form(is_healer(request.user)),
    }
    return render_to_response('clients/client_detail.html',
                              c,
                              context_instance=RequestContext(request))
コード例 #9
0
def profile_edit(request, template_name="clients/clients_profile_edit.html"):
    client = get_object_or_404(Client, user__id=request.user.id)
    try:
        get_user_customer(request.user)  # initiate customer
    except:
        pass
    if is_healer(client):
        return redirect('healer_edit')

    phones = ClientPhoneNumber.objects.filter(client=client)

    if request.method == 'POST':
        form = ClientForm(request.POST)
        if form.is_valid():
            if phones:
                phones[0].number = form.cleaned_data['phone']
                phones[0].save()
            else:
                ClientPhoneNumber.objects.create(
                    client=client, number=form.cleaned_data['phone'])

            client.user.first_name = form.cleaned_data['first_name']
            client.user.last_name = form.cleaned_data['last_name']
            client.user.save()

            client.about = form.cleaned_data['about']
            client.send_reminders = form.cleaned_data['send_reminders']
            client.ghp_notification_frequency = form.cleaned_data[
                'ghp_notification_frequency']

            #			client.beta_tester = form.cleaned_data['beta_tester']
            client.save()
            return redirect('clients_profile')
    else:
        form = ClientForm(
            initial={
                'first_name': client.user.first_name,
                'last_name': client.user.last_name,
                'about': client.about,
                'phone': (phones[0].number if (len(phones) > 0) else ''),
                'send_reminders': client.send_reminders,
                'ghp_notification_frequency': client.ghp_notification_frequency
                #			'beta_tester' : client.beta_tester
            })

    return render_to_response(template_name, {
        'client': client,
        'form': form,
        'locations': client.get_locations_objects(),
        'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY,
    },
                              context_instance=RequestContext(request))
コード例 #10
0
def get_healer_info_context(healer, request):
	client = None
	client_id = ""
	request.friend_type = None
	is_profile_visible = True
	is_client = False
	try:
		client = clients.models.Client.objects.get(user__id=request.user.id)
		request.friend_type = 'referrals' if is_healer(client) else "healers"
		client_id = client.id
		is_client = is_my_client(healer.user, request.user)
	except ObjectDoesNotExist:
		pass

	is_profile_visible = healer.is_visible_to(request.user, is_client)

	if not is_profile_visible and not request.user.is_superuser:
		if request.user != healer.user:
			return is_client, False, {}

	locations = healer.get_locations(user=request.user, is_client=is_client,
		skip_center_locations=True)

	#	referring_users = [o['friend'] for o in Referrals.objects.referrals_to(healer.user)]
	#	healers = Healer.objects.filter(user__in=referring_users)
	#	referrals_to_me = [h.user for h in healers if h.is_visible_to(request.user)]
	referrals_to_me_count = Referrals.objects.referrals_to(healer.user, count=True)

	phones = clients.models.ClientPhoneNumber.objects.filter(client=healer)

	if request.user == healer.user:
		modalities = Modality.objects_approved.get_with_unapproved(healer=healer)
	else:
		modalities = Modality.objects_approved
	modalities = list(modalities.filter(healer=healer, visible=True))
	modalities.reverse()

	request.other_user = healer.user

	return is_client, True, {
		"healer": healer,
		"client": client,
		"client_id": client_id,
		"is_my_client": is_client,
		"locations": locations,
		"referrals_to_me_count": referrals_to_me_count,
		"phone": (phones[0].number if (len(phones) > 0) else ''),
		"modalities": modalities,
		"is_schedule_visible": healer.is_schedule_visible(request.user, is_client),
		"review_exist": healer.reviews.filter(reviewer__user=request.user).count() if request.user.is_authenticated() else False,
		"is_review_permission": healer.is_review_permission(request.user, is_client),
		}
コード例 #11
0
    def test_healer2healer_as_client(self):
        self.test_healer.client_screening = Healer.SCREEN_NONE
        self.test_healer.save()

        self.invitation.is_to_healer = True
        self.invitation.save()

        response = self.signup(confirm=True)
        self.assertTrue('redirect_url' in response)

        new_client = Client.objects.get(user__email=self.email)
        self.assertFalse(is_healer(new_client))
        self.check_friendship_clients_refferals_numbers(new_client, 1, 1, 0)
コード例 #12
0
    def __init__(self, user, data=None):
        self.healer = None
        now = settings.GET_NOW()
        if is_healer(user):
            self.healer = user.client.healer
            now = self.healer.get_local_time()

        users = Clients.objects.friends_for_user(user)
        clients = [(u["friend"].client.id, str(u["friend"].client))
                   for u in users]
        self.base_fields['client'].choices = clients
        self.base_fields['client'].widget.choices = clients

        healer_locations = ClientLocation.objects.filter(client__user=user)
        locations = [(hl.location.id, str(hl.location))
                     for hl in healer_locations]

        if len(locations) == 0:
            locations.insert(0, ("-1", Location.get_name(None)))

        self.base_fields['location'].choices = locations
        self.base_fields['location'].widget.choices = locations

        time_choices = []
        dt = now.replace(hour=0, minute=0)
        dt_end = dt + timedelta(days=1)
        while dt < dt_end:
            time_choices.append(
                (dt.strftime("%H:%M"), dt.strftime("%I:%M %p").lower()))
            dt += timedelta(minutes=15)

#		self.base_fields['start'].choices = time_choices
#		self.base_fields['end'].choices = time_choices

        self.base_fields['start'].widget.choices = time_choices

        self.base_fields[
            'treatment_length'].queryset = TreatmentTypeLength.objects.filter(
                treatment_type__healer__user=user)

        #		self.base_fields['start'].widget.initial = ["12:00"]
        #		self.base_fields['end'].widget.initial = [12]

        super(forms.Form, self).__init__(initial={
            'start': '12:00',
            'end': '13:00',
            'date': dt.date() + timedelta(days=1)
        },
                                         data=data)
コード例 #13
0
    def test_healer2client_as_client(self):
        self.test_healer.client_screening = Healer.SCREEN_NONE
        self.test_healer.save()

        self.signup()

        new_client = Client.objects.get(user__email=self.email)
        self.assertFalse(is_healer(new_client))

        clients = Clients.objects.filter(from_user=self.test_healer.user,
                                         to_user=new_client.user).count()
        self.assertEqual(clients, 1)

        client = Client.objects.get(user__email=self.email)
        self.assertEqual(client.approval_rating, 100)
コード例 #14
0
    def test_no_join_invitation_success(self):
        fb_data = {
            'first_name': 'test1',
            'last_name': 'test2',
            'email': '*****@*****.**',
            'id': '1'
        }
        user = facebook_callback.handle_no_user(self.request,
                                                self.oauth_access, fb_data,
                                                'healer')

        self.assertEqual(user.email, fb_data['email'])
        self.assertFalse(user.has_usable_password())
        self.assertTrue(user.is_active)

        self.assertTrue(is_healer(user.client))
コード例 #15
0
def remove_card(request):
    def check_all_payments_disabled():
        for plan_type in settings.PLAN_TYPES:
            current_subscription = get_current_subscription(customer)
            if getattr(current_subscription, '%s_status' % plan_type):
                return 'You have to disable payments for "%s" to remove your card.' % plan_type

    customer = get_user_customer(request.user)
    error = check_all_payments_disabled()
    if error is None:
        customer.remove_card()

    if is_healer(request.user):
        return healers.views.account(request, error)
    else:
        return redirect('clients_profile')
コード例 #16
0
def invite_or_create_client_friendship(client_user, healer_user, send_client_request_email=False):
	#if the person is in my contacts list > auto add them, otherwise require a confirmation

	is_client = is_my_client(healer_user=healer_user, client_user=client_user)

	if is_client:
		return

	healer = is_healer(healer_user)
	if not healer:
		raise Healer.DoesNotExist

	contact = ContactEmail.objects.filter(email=client_user.email, contact__healer=healer).count()

	if healer.client_screening == Healer.SCREEN_ALL or \
		(healer.client_screening == Healer.SCREEN_NOT_CONTACTS and not contact):

		invitation_to = ClientInvitation.objects.filter(from_user=client_user, to_user=healer_user, status="2")

		if not invitation_to:
			invitation = ClientInvitation(from_user=client_user, to_user=healer_user, message="", status="2")
			invitation.save()

		if send_client_request_email:
			ctx = {
				"client_name": str(client_user.client),
				"accept_url": get_full_url('friend_accept', args=['clients', client_user.id]),
				"decline_url": get_full_url('friend_decline', args=['clients', client_user.id])
			}

			subject = render_to_string("friends/client_request_subject.txt", ctx)
			send_hs_mail(subject, "friends/client_request_message.txt", ctx, settings.DEFAULT_FROM_EMAIL, [healer_user.email])

	elif healer.client_screening == Healer.SCREEN_NONE or \
	     (healer.client_screening == Healer.SCREEN_NOT_CONTACTS and contact):

		Clients.objects.create(from_user=healer_user, to_user=client_user)

	else:
		raise Exception
コード例 #17
0
def is_healer_processor(request):
    healer = False
    beta_tester = True

    func = getattr(request.user, "client", None)
    if func:
        healer = is_healer(request.user)


#		beta_tester = request.user.client.beta_tester
    return {
        'is_healer':
        healer,
        'is_beta_tester':
        beta_tester,
        'is_wellness_center':
        is_wellness_center(healer),
        'healers_in_wcenter_with_schedule_perm':
        get_healers_in_wcenter_with_schedule_editing_perm(healer),
        'is_stripe_connect_beta_tester':
        True,  #request.user.username in settings.STRIPE_CONNECT_BETA_USERS
        'is_gift_certificates_beta_tester':
        True  # request.user.username in settings.GIFT_CERTIFICATES_BETA_USERS
    }
コード例 #18
0
	def __call__(self, request, access, token, account_type=None, is_ajax=False,
				is_signup=False, is_ambassador=False, is_phonegap=False):
		user_data = self.fetch_user_data(request, access, token)
		if 'error' in user_data:
			if is_ajax:
				return None, "Error during facebook login."
			return redirect('login_page')

		redirect_to = self.redirect_url(request)
		if not request.user.is_authenticated():
			try:
				user = self.lookup_user(request, access, user_data)
			except FacebookNoEmail:
				message = (
					"Your Facebook account does not have an email "
					"associated with it, so you must sign up "
					"using the regular signup form. "
					"Thanks and sorry for the inconvenience.")
				if is_ajax:
					return None, message
				request.session['oauth_error_message'] = message
				return redirect('oauth_error')
			if user is None:
				if is_ajax and not is_signup:
					return None, "You have no account on healersouce.com"
				if not account_type:
					request.session["token"] = token
					return redirect('select_account_type', access.service)
				else:
					user = self.handle_no_user(request, access, user_data, account_type, is_ambassador, is_phonegap)
			else:
				user = self.handle_unauthenticated_user(request, user, access, token, user_data)
		else:
			user = access.lookup_user(identifier=self.identifier_from_data(user_data))
			if user and user != request.user:
				facebook_associate_new_account = request.session.pop('facebook_associate_new_account', False)
				if facebook_associate_new_account:
					ua = UserAssociation.objects.filter(user=user, service="facebook")[0]
					ua.user = request.user
					ua.save()
				else:
					message = "There is another user connected to this account on facebook."
					if is_ajax:
						return None, message
					request.session['oauth_error_message'] = message
					request.session['oauth_error_is_facebook_duplicate'] = True
					return redirect('oauth_error')

			user = request.user

		if user:
			kwargs = {"identifier": self.identifier_from_data(user_data)}

			# for first time, save fb data, load fb friends for healer
			ua = UserAssociation.objects.filter(user=user, service="facebook")
			if not ua.count():
				save_facebook_data(user, user_data)
				save_facebook_picture(user, user_data['id'], token)
			if is_healer(user.client) or "send_healing_facebook" in request.session:
				ContactsImportStatus.objects.filter(user=user).delete()
				import_status = ContactsImportStatus.objects.create(user=user, api=FACEBOOK_API, status=STATUS_RUNNING)
				save_facebook_friends_thread(user, import_status, token, request)

			access.persist(user, token, **kwargs)

		if "send_healing_facebook" in request.session:
			del request.session["send_healing_facebook"]
			request.session['got_friends_from_fb'] = True
			redirect_to = reverse("send_healing")
		if is_ajax:
			set_signup_source(user, request, is_phonegap)
			return user, None
		return redirect(redirect_to)
コード例 #19
0
 def get(self, request, format=None):
     return Response(is_healer(request.user) is not None)
コード例 #20
0
def save_join_request_form(request,
                           form,
                           is_to_healer=False,
                           is_for_review=False,
                           is_for_ambassador=False):
    # for client always create invitation
    invite_provider_recommend = form.cleaned_data.get(
        'invite_provider_recommend', True) if is_to_healer else True

    email_template = subject_template = body_template = None
    if type(form) in [
            ContactsJoinInviteRequestForm, PostcardJoinInviteRequestForm
    ]:
        if is_for_review:
            subject_template = "friends/join_invite_review_subject.txt"
            body_template = "friends/join_invite_review_message.txt"
            email_template = "friends/invite_review_postcard_message.txt"
        else:
            # recommend message only for healer
            if is_to_healer and invite_provider_recommend:
                email_template = "friends/invite_recommend_postcard_message.txt"
            else:
                email_template = "friends/invite_postcard_message.txt"

    emails = []
    if 'emails' in form.cleaned_data:
        if type(form.cleaned_data['emails']) == unicode:
            emails.append(form.cleaned_data['emails'])
        else:
            emails.extend(form.cleaned_data['emails'])
    if 'email_list' in form.cleaned_data:
        emails.extend(form.cleaned_data['email_list'])
    if 'contacts' in form.cleaned_data:
        emails.extend(o.email for o in form.cleaned_data['contacts'])


#	if healer:
#		healer.invite_message = form.cleaned_data["message"]
#		healer.save()

    invitations = []
    email_invitation_list = []
    client_requests_list = []
    provider_requests_list = []

    existing_users = []
    if 'providers' in form.cleaned_data:
        existing_users.extend(o.user for o in form.cleaned_data['providers'])
    for email in emails:
        users = EmailAddress.objects.get_users_for(email)
        if users:
            existing_users.append(users[0])
        else:
            email_invitation_list.append(email)

    for to_user in existing_users:
        if is_to_healer and is_healer(to_user):
            friend_type = 'referrals'
            provider_requests_list.append(to_user.email)
        else:
            friend_type = 'clients'
            client_requests_list.append(to_user.email)

        friend_process(request, friend_type, to_user.id, "add")

    for email in email_invitation_list:
        invitations.append(
            SiteJoinInvitation.objects.send_invitation(
                request.user,
                email,
                form.cleaned_data["message"],
                is_to_healer=is_to_healer,
                create_friendship=invite_provider_recommend,
                html_template_name=email_template,
                subject_template=subject_template,
                body_template=body_template,
                postcard_background=form.cleaned_data.get(
                    'postcard_background', None),
                is_for_ambassador=is_for_ambassador))

    return invitations, email_invitation_list, client_requests_list, provider_requests_list
コード例 #21
0
def after_signup(new_user, account_type=None, email_confirmed=True):
	def get_model_class():
		if account_type == 'healer':
			return Healer
		elif account_type == 'wellness_center':
			return WellnessCenter
		else:
			return Client

	def process_dummy_users(new_user):
		""" Move dummy user objects to new user, confirms appointments, remove dummy users """

		def copy_friendship(friendship_class, user, new_user):
			friends = friendship_class.objects.friends_for_user(user)
			for friend in friends:
				try:
					if friend['friendship'].from_user == user:
						friendship_class.objects.get_or_create(from_user=new_user, to_user=friend['friendship'].to_user)
					if friend['friendship'].to_user == user:
						friendship_class.objects.get_or_create(to_user=new_user, from_user=friend['friendship'].from_user)
				except IntegrityError:
					# friendship exists
					pass

		dummy_users = User.objects.filter(email__iexact=new_user.email).exclude(id=new_user.id)
		if len(dummy_users):
			# copy clients and referrals
			client = Client.objects.get(user=new_user)
			referred_by = []
			for user in dummy_users:
				copy_friendship(Clients, user, new_user)
				copy_friendship(Referrals, user, new_user)
				dummy_client = user.client
				if client.approval_rating < dummy_client.approval_rating:
					client.approval_rating = dummy_client.approval_rating
				if dummy_client.referred_by:
					referred_by.append(dummy_client.referred_by)
				dummy_client.phone_numbers.update(client=client)
				dummy_client.clientlocation_set.update(client=client)
				ContactInfo.objects.filter(client=dummy_client).update(client=client)
				IntakeFormSentHistory.objects.filter(client=dummy_client).update(client=client)

				#clear friendship invitation for dummy_user
				FriendshipInvitation.objects.filter(Q(from_user=user) | Q(to_user=user)).delete()
				FriendshipInvitationHistory.objects.filter(Q(from_user=user) | Q(to_user=user)).delete()
			#			SiteJoinInvitation.objects.filter(contact__email__iexact=user.email).delete()

			client.referred_by = ', '.join(referred_by)

			client.save()

			# confirm appointments
			dummy_user_ids = [u.id for u in dummy_users]
			client = Client.objects.get(user=new_user)
			appts = Appointment.objects.filter(client__user__id__in=dummy_user_ids)
			for appt in appts:
				if not appt.confirmed:
					if Appointment.check_for_auto_confirm(appt.healer, client):
						appt.confirm()
						appt.notify_created(client.user)
					else:
						appt.notify_requested(new_user)

				requested_friendships = []
				if appt.healer.id not in requested_friendships:
				#				request_friendship(client.user, appt.healer.user, ClientInvitation)
					invite_or_create_client_friendship(client.user, appt.healer.user)
					requested_friendships.append(appt.healer.id)

			appts.update(client=client)

			# remove all dummy users for this email
			dummy_users.delete()

	model_class = get_model_class()
	client = model_class.objects.get_or_create(user=new_user)[0]

	if not email_confirmed:
		return

	for join_invitation in SiteJoinInvitation.objects.filter(contact__email__iexact=new_user.email):
		ContactInfo.objects.filter(contact=join_invitation.contact).update(client=client)

		#is_from_site == unregistered booking
		if not join_invitation.is_from_site:
			if not is_healer(join_invitation.from_user):
				raise Healer.DoesNotExist

			if is_healer(new_user) and join_invitation.is_to_healer:
				FriendClass = Referrals
			else:
				FriendClass = Clients

			if join_invitation.create_friendship:
				friendship_exists = Friendship.objects.filter(
						from_user=join_invitation.from_user,
						to_user=new_user).exists()
				if not friendship_exists:
					FriendClass.objects.create(
						from_user=join_invitation.from_user,
						to_user=new_user)

			client.approval_rating = 100
			client.save()

			# fixes occurred problem.
			try:
				join_invitation.delete()
			except JoinInvitation.DoesNotExist:
				pass

	process_dummy_users(new_user)