Beispiel #1
0
    def form_valid(self, form):
        data = form.cleaned_data
        person = get_contact(
            email=data['email'],
            first_name=data['first_name'],
            last_name=data['last_name'],
            postcode=data['zipcode'],
            phone=data['phone'])
        person.tags.add('self-signup')

        working_group = data['working_group']
        ip_address = self.request.META.get('HTTP_X_FORWARDED_FOR', self.request.META.get('REMOTE_ADDR', 'unknown address'))

        signup_obj = Signup(
                ip_address=ip_address,
                contact=person
        )
        signup_obj.data = data
        if working_group != 'UNKNOWN':
            circle = get_circle(data['working_group'])
            if circle and circle.request_membership(contact=person):
                messages.success(self.request, 'Requested membership in {}'.format(circle))
        signup_obj.save()
        set_last_contact(self.request, person)
        return HttpResponseRedirect('/welcome/guide')
Beispiel #2
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        me = get_contact(email=self.request.user.email)
        contact_id = self.kwargs.get('contact_id', None)
        if contact_id is None:
            contact = me
        else:
            contact = get_object_or_404(Contact, pk=contact_id)

        ctx = {
            'contact':
            contact,
            'leads':
            Circle.objects.filter(
                circlemember__contact=contact,
                circlemember__role__in=LEAD_ROLES).distinct(),
            'members':
            Circle.objects.filter(circlemember__contact=contact).exclude(
                circlemember__role__in=LEAD_ROLES),
            'is_me':
            contact == me,
        }
        couches = contact.couch_set.all()
        if not ctx['is_me']:
            couches = couches.filter(public=True)
        else:
            ctx['form'] = self.form_class()
        ctx['couches'] = couches
        return ctx
Beispiel #3
0
 def propose(self, location, email, phone='', name=''):
     contact = get_contact(email, name=name, phone=phone)
     contact.tags.add('talk-request')
     prop = TalkProposal(requestor=contact)
     prop.location = location
     prop.save()
     return prop
Beispiel #4
0
def approve_membership(request, pk):
    circle = get_object_or_404(Circle, pk=pk)
    contact = get_object_or_404(Contact, pk=request.POST['id'])
    if circle.can_manage(request.user):
        circle.approve_membership(contact, who=get_contact(email=request.user.email))
        messages.success(request, "Approved {}!".format(contact))

    return redirect(circle.get_absolute_url())
Beispiel #5
0
 def form_valid(self, form):
     info = form.cleaned_data['info']
     availability = form.cleaned_data['availability']
     public = form.cleaned_data['public']
     me = get_contact(email=self.request.user.email)
     me.couch_set.create(info=info, availability=availability, public=public)
     messages.success(self.request, "Thank you for your generosity!")
     return HttpResponseRedirect('/circle/person/me/')
Beispiel #6
0
def del_member(request, pk):
    circle = get_object_or_404(Circle, pk=pk)
    contact = get_object_or_404(Contact, pk=request.POST['id'])
    me = get_contact(email=request.user.email)
    if me == contact or circle.can_manage(request.user):
        role = request.POST.get('role', 'member')
        circle.remove_member(contact, role=role, who=request.user)
    return redirect(circle.get_absolute_url())
Beispiel #7
0
def csv_import(request):
    ctx = {}
    can_import = request.user.has_perm('circles.change_circle')
    ctx['can_import'] = can_import
    if can_import and request.method == 'POST':
        f = TextIOWrapper(request.FILES['csv'].file, encoding=request.encoding)
        reader = csv.DictReader(f)
        fields = reader.fieldnames
        email_field = find_field(fields, 'email')
        first_name_field = find_field(fields, ('first', 'first name', 'fname'))
        last_name_field = find_field(fields, ('last', 'last name', 'lname'))
        try:
            wg_field = find_field(fields, ('circle', 'working group', 'wg'))
        except ValueError:
            wg_field = None

        try:
            phone_field = find_field(fields, ('phone number', 'phone'))
        except ValueError:
            phone_field = None

        try:
            tag_field = find_field(fields, ('tags', 'tag'))
        except ValueError:
            tag_field = None

        contacts = set()
        memberships = []
        for row in reader:
            contact = get_contact(
                row[email_field],
                first_name=row[first_name_field],
                last_name=row[last_name_field],
                phone=row[phone_field] if phone_field else None)
            contacts.add(contact)
            messages.success(request, 'Found {}'.format(contact))
            if wg_field and row[wg_field]:
                wg = row[wg_field].split('-')[0].strip()
                try:
                    circle = Circle.objects.filter(
                        name__iexact=wg).order_by('-pk')[0]
                except IndexError:
                    messages.error(request,
                                   'Could not find circle named {}'.format(wg))
                else:
                    if circle.request_membership(contact=contact):
                        messages.success(
                            request,
                            'Requested membership for {} to {}'.format(
                                contact, circle))
            if tag_field and row[tag_field]:
                contact.tags.add(
                    *[t.strip() for t in row[tag_field].split(',')])
        return redirect('circles:person-import')
    response = render(request, 'circles/csv.html', ctx)
    response['Cache-Control'] = 'private'
    return response
Beispiel #8
0
 def request_membership(self, email='', name='', contact=None):
     contact = contact or get_contact(email, name=name)
     if not self.members.filter(pk=contact.id).exists():
         try:
             MembershipRequest.objects.get_or_create(circle=self, requestor=contact)
         except MultipleObjectsReturned:
             pass
         return contact
     else:
         return False
Beispiel #9
0
 def post(self, request, *args, **kwargs):
     job = get_object_or_404(CircleJob, pk=request.POST['id'])
     who = get_contact(email=self.request.user.email)
     job.filled = who
     job.filled_on = now()
     job.save()
     role = job.title or 'member'
     job.circle.add_member(who.email, str(who), contact=who, role=role)
     messages.success(request, "Thanks for signing up for this job!")
     return HttpResponse('ok')
Beispiel #10
0
def person_view(request, contact_id=None):
    if contact_id is None:
        contact = get_contact(email=request.user.email)
    else:
        contact = get_object_or_404(Contact, pk=contact_id)
    ctx = {
        'contact':
        contact,
        'leads':
        Circle.objects.filter(circlemember__contact=contact,
                              circlemember__role__in=['int',
                                                      'ext']).distinct(),
        'members':
        Circle.objects.filter(circlemember__contact=contact,
                              circlemember__role='member'),
        'is_me':
        contact == get_contact(email=request.user.email),
    }
    response = render(request, 'circles/person.html', ctx)
    response['Cache-Control'] = 'private'
    return response
Beispiel #11
0
def show_action(request, slug):
    action = get_object_or_404(Action, slug=slug)
    ctx = {'action': action}
    if request.user.is_authenticated:
        ctx['attendees'] = Attendee.objects.filter(
            action=action).select_related('contact').order_by(
                '-mutual_commitment', '-promised', 'pk')
        ctx['promised'] = ctx['attendees'].filter(promised__isnull=False)
        ctx['default_to_email'] = settings.DEFAULT_FROM_EMAIL
    if action.when < now() and action.public:
        # don't allow signups for public actions that already happened
        ctx['already_happened'] = True
        form = None
    elif request.method == 'POST':
        form = SignupForm(request.POST, action=action)
        if form.is_valid():
            data = form.cleaned_data
            commit = abs(data['commit'] or 0)
            atten = action.signup(data['email'],
                                  data['role'],
                                  name=data['name'][:100],
                                  promised=data['promised'],
                                  commit=commit,
                                  notes=data['notes'])
            next_url = data['next'] or request.headers.get('referer', '/')
            messages.success(
                request,
                "Thank you for signing up for {}!".format(action.html_title))
            if commit:
                messages.info(
                    request,
                    "We will notify you once at least %d others commit" %
                    commit)
            set_last_contact(request, atten.contact)
            return redirect(next_url)
    else:
        contact = get_contact(
            email=request.user.email
        ) if request.user.is_authenticated else get_last_contact(request)
        initial = {}
        if contact:
            initial['email'] = contact.email
            initial['name'] = str(contact)
        form = SignupForm(action=action, initial=initial)
    ctx['form'] = form
    ctx['has_roles'] = list(action.available_role_choices)
    ctx['photos'] = list(action.photos.all())
    resp = render(request, 'action.html', ctx)
    resp['Vary'] = 'Cookie'
    resp['Last-Modified'] = http_date(action.modified.timestamp())
    if request.user.is_authenticated:
        resp['Cache-Control'] = 'private'
    return resp
Beispiel #12
0
 def is_pending(self, request):
     if request.user.is_authenticated:
         contact = get_contact(request.user.email)
     else:
         contact = None
     if contact:
         try:
             return MembershipRequest.objects.get(circle=self, requestor=contact).confirm_date is None
         except MembershipRequest.DoesNotExist:
             return False
     else:
         return str(self.id) in request.session.get('circle_requests', {})
     return False
Beispiel #13
0
    def signup(self, email, role, name='', notes='', promised=None, commit=0):
        if not isinstance(role, ActionRole):
            role = ActionRole.objects.get_or_create(name=role or '')[0]

        user = get_contact(email, name=name)
        atten, created = Attendee.objects.get_or_create(action=self, contact=user, role=role)
        if not created:
            if notes:
                atten.notes = notes
        else:
            atten.notes = notes
            atten.mutual_commitment = commit
        if promised:
            atten.promised = now()
        atten.save()
        return atten
Beispiel #14
0
    def form_valid(self, form):
        data = form.cleaned_data
        jwt_token = data['message']
        try:
            self.decode_token(jwt_token)
        except:  # noqa E722
            return HttpResponseRedirect('/')

        postcode = data['zipcode']
        city, state = zipcode_lookup(postcode)
        person = get_contact(email=data['email'],
                             first_name=data['first_name'],
                             last_name=data['last_name'],
                             postcode=postcode,
                             city=city,
                             state=state,
                             phone=data['phone'])

        # TODO: should we record this?
        ip_address = self.request.META.get(
            'HTTP_X_FORWARDED_FOR',
            self.request.META.get('REMOTE_ADDR', 'unknown address'))

        if data["volunteer"]:
            person.tags.add('volunteer')
            skills = data['skills']

            message = bleach.clean(data['anything_else'])
            if data["skill_other"]:
                other_skill = bleach.clean(data["skill_other_value"])
                # was going to make this another skill tag but don't want random users
                # adding tags
                message = 'otherskill: {0}\nmessage: {1}'.format(
                    other_skill, message)

            try:
                volunteer = VolunteerRequest.objects.get(
                    contact__email=person.email)
            except VolunteerRequest.DoesNotExist:
                volunteer = VolunteerRequest.objects.create(contact=person,
                                                            message=message)
            for skill in skills:
                volunteer.tags.add(skill)

        set_last_contact(self.request, person)
        return HttpResponseRedirect(reverse('extinctionr.info:thankyou'))
 def handle(self, *args, **kwargs):
     first = True
     with open(kwargs['filename'], 'r') as fp:
         reader = csv.DictReader(fp)
         for row in reader:
             # if first:
             #     first = False
             #     continue
             first_name = row['first_name']
             last_name = row['last_name']
             email = row['email']
             zipcode = row['zip_code']
             city = row['can2_user_city']
             if email:
                 c = get_contact(email,
                                 first_name=first_name,
                                 last_name=last_name,
                                 postcode=zipcode,
                                 city=city)
                 self.stdout.write(str(c))
Beispiel #16
0
 def has_module_permission(self, request):
     if not request.user.is_anonymous:
         contact = get_contact(email=request.user.email)
         return contact.circlemember_set.exists()
Beispiel #17
0
 def save_model(self, request, obj, form, change):
     if not obj.creator:
         obj.creator = get_contact(email=request.user.email)
     super().save_model(request, obj, form, change)
Beispiel #18
0
 def is_me(self, user):
     return get_contact(user.email) == self.owner
Beispiel #19
0
 def can_manage(self, user):
     return user.has_perm('circles.change_circle') or self.leads.filter(pk=get_contact(email=user.email).id).exists()
Beispiel #20
0
 def add_member(self, email, name, contact=None, role='member'):
     contact = contact or get_contact(email, name=name)
     CircleMember.objects.get_or_create(circle=self, contact=contact, role=role)
Beispiel #21
0
def show_action(request, slug):
    action = get_object_or_404(Action, slug=slug)
    ctx = {"action": action}
    if request.user.is_authenticated:
        ctx["attendees"] = (
            Attendee.objects.filter(action=action)
            .select_related("contact")
            .order_by("-mutual_commitment", "-promised", "pk")
        )
        ctx["promised"] = ctx["attendees"].filter(promised__isnull=False)
        ctx["default_to_email"] = settings.DEFAULT_FROM_EMAIL
    if action.when < now() and action.public:
        # don't allow signups for public actions that already happened
        ctx["already_happened"] = True
        form = None
    elif request.method == "POST":
        form = SignupForm(request.POST, action=action)
        if form.is_valid():
            data = form.cleaned_data
            commit = abs(data["commit"] or 0)
            attendee = action.signup(
                data["email"],
                data["role"],
                name=data["name"][:100],
                promised=data["promised"],
                commit=commit,
                notes=data["notes"],
            )
            next_url = data["next"] or request.headers.get("referer", "/")
            messages.success(
                request, "Thank you for signing up for {}!".format(action.html_title)
            )
            if commit:
                messages.info(
                    request,
                    "We will notify you once at least %d others commit" % commit,
                )
            set_last_contact(request, attendee.contact)
            ical_data = str(actions_to_ical([action]))
            # Send confirmation email.
            confirm_rsvp(action, attendee, ical_data)
            return redirect(next_url)
    else:
        contact = (
            get_contact(email=request.user.email)
            if request.user.is_authenticated
            else get_last_contact(request)
        )
        initial = {}
        if contact:
            initial["email"] = contact.email
            if contact.first_name:
                initial["name"] = str(contact)
        form = SignupForm(action=action, initial=initial)
    ctx["form"] = form
    ctx["has_roles"] = list(action.available_role_choices)
    ctx["photos"] = list(action.photos.all())
    if action.image:
        ctx["image"] = action.image
    resp = render(request, "action.html", ctx)
    resp["Vary"] = "Cookie"
    resp["Last-Modified"] = http_date(action.modified.timestamp())
    if request.user.is_authenticated:
        resp["Cache-Control"] = "private"
    return resp