Ejemplo n.º 1
0
def account_form(request, id=None):
    '''
    edit account info
    '''

    if not has_elevated_perm(request, 'membership', 'add_account'):
        return HttpResponseRedirect(reverse('welcome'))

    context = RequestContext(request)
    if id:
        account = get_object_or_404(models.Account, id=id)
        context['edit'] = True
        old_values = copy.deepcopy(account.__dict__)
    else:
        account = models.Account()
    if request.method == 'POST':
        if 'cancel' in request.POST:
            if id:
                return HttpResponseRedirect(reverse('account', args=[id]))
            else:
                return HttpResponseRedirect(reverse('accounts'))
        if 'delete' in request.POST:
            account.delete()
            log(request, account, 'delete')
            return HttpResponseRedirect(reverse('accounts'))
        form = forms.AccountForm(request.POST, instance=account)
        related_member_formset = forms.RelatedMemberFormSet(request.POST, 
                instance=account, prefix='related_member')
        if form.is_valid() and related_member_formset.is_valid():
            if context.get('edit'):
                account = form.save()
                log(request, account, 'edit', old_values=old_values)
            else:
                account = form.save()
                log(request, account, 'add')
            _setattr_formset_save(request, related_member_formset, 'account', account)
            return HttpResponseRedirect(reverse('account', args=[account.id]))
    else:
        form = forms.AccountForm(instance=account)
        related_member_formset = forms.RelatedMemberFormSet(instance=account, 
                prefix='related_member')
    context['account'] = account
    context['form'] = form
    context['formsets'] = [
        (related_member_formset, 'Members'), 
    ]
    template = get_template('membership/account_form.html')
    return HttpResponse(template.render(context))
Ejemplo n.º 2
0
def _setattr_formset_save(request, formset, name, value):
    instances = formset.save(commit=False)
    for instance in instances:
        setattr(instance, name, value)
        instance.save()
        log(request, instance, 'add')
Ejemplo n.º 3
0
def member_signup_review(request):
    if not has_elevated_perm(request,'membership','add_member'):
        return HttpResponseRedirect(reverse('welcome'))

    context = RequestContext(request)

    MemberSignUpReviewFormSet = formset_factory(forms.MemberSignUpReviewForm)

    '''
    We have to populate the choices for the referring member form item. We could have 
    done this in the form itself, but that would have caused each and every form to 
    hit the database for the list of members, so instead we do one query on the 
    database here and set it for each form we are about to show to the user.
    
    Here we just create the list, and we set it in each form later. The key here is 
    that the choices have to be set before each form is validated.
    '''
    #members = models.Member.objects.filter(date_departed__isnull=True)
    #member_choices = [('','')]
        
    #for member in members:
    #    member_choices.append((member.id, str(member)))


    if request.method == "POST":

        formset = MemberSignUpReviewFormSet(request.POST)
        
        review_action = request.POST["review_action"]
        context["review_action"] = review_action

        record_ids = request.POST["record_ids"].split(',')
        record_states = request.POST["record_states"].split(',')

        new_members = []

        formset_errors = False
        
        for n in range(0, formset.total_form_count()):

            new_member = models.MemberSignUp.objects.get(id=record_ids[n])
            new_members.append(new_member)

            if record_states[n] == RECORD_STATE_INACTIVE:
                continue

            form = formset.forms[n]
            #form.set_referring_member_choices(member_choices)

            # We need to check if a given form has been selected, but the selected
            # value only appears in POST if the user has actually selected... I am sure there 
            # is a better way to handle this, but I don't have time to figure it out now - TM
            try:
                if not request.POST['form-' + str(n) + '-selected']:
                    # We clear any validation errors on forms that haven't been selected
                    form.errors.clear()
                    continue
            except MultiValueDictKeyError:
                # if the form wasn't selected, then we can just continue on to the next one
                #formset.data['form-' + str(n) + '-record_id'] = unicode(new_member.id)
                form.errors.clear()
                continue

            if review_action == "spam":
                new_member.spam = True
                new_member.active = False
                new_member.save()
                record_states[n] = RECORD_STATE_INACTIVE
            elif review_action == "delete":
                new_member.active = False
                new_member.save()
                record_states[n] = RECORD_STATE_INACTIVE
            elif review_action == "save":
                if form.is_valid():
                    # Create user
                    user = User.objects.create_user(form.cleaned_data['user_name'].strip(), password=User.objects.make_random_password())
                    user.email = new_member.email
                    user.first_name = new_member.first_name
                    user.last_name = new_member.last_name

                    '''
                    We save this here because the user needs a primary key value before
                    we can add a group
                    '''
                    user.save()

                    user.groups.add(Group.objects.get(name="member"))
                    user.save()

                    log(request, user, 'add')

                    # Create member
                    member = models.Member()
                    member.user = user
                    member.status = 'd' # departed
                    member.work_status = 'n' # no workshift

                    # Per Dana: the departed date is set to a very specific value for new members
                    # depending upon whether or not they have paid for the equity at sign up
                    if form.cleaned_data["payment_verified"] and new_member.equity_paid > 0:
                        member.date_departed = datetime.date(1904, 01, 01)

                    else:
                        member.date_departed = datetime.date(1904, 02, 02)
                        
                    member.referral_source = new_member.referral_source
                    member.orientation = new_member.orientation
                    member.referring_member = form.cleaned_data["referring_member"];

                    #if form.cleaned_data["referring_member"] and member.referral_source == "Current Member":
                    #    member.referring_member = models.Member.objects.get(id=form.cleaned_data["referring_member"])

                    member.save()

                    log(request, member, 'add')

                    address = models.Address()
                    address.type = 'h'
                    address.address1 = new_member.address1
                    address.address2 = new_member.address2
                    address.city = new_member.city
                    address.state = new_member.state
                    address.postal_code = new_member.postal_code
                    address.country = new_member.country
                    address.member = member
                    address.save()

                    phone = models.Phone()
                    phone.type = 'h'
                    phone.number = new_member.phone
                    phone.member = member
                    phone.save()
                   
                    # Create account
                    current_date = unicode(datetime.date.today())
                    account = models.Account() 
                    account.name = unicode(new_member) + " " + current_date
                    account.note = u'Joined Online %s' % current_date
                    account.save()

                    log(request, account, 'add')

                    # Create account member
                    account_member = models.AccountMember.objects.create(account=account, member=member)

                    log(request, account_member, 'add')

                    # Perform equity transaction if there was one
                    if form.cleaned_data["payment_verified"] and new_member.equity_paid > 0:
                        equity_transaction = a_models.Transaction.objects.create(account=account, member=member, purchase_type='O', purchase_amount=Decimal(new_member.equity_paid), note=u'Joined Online %s' % current_date)
                        equity_transaction = a_models.Transaction.objects.create(account=account, member=member, purchase_type='S', purchase_amount=Decimal(0) - Decimal(new_member.equity_paid), note=u'Joined Online %s' % current_date)

                    new_member.saved = True
                    new_member.save()

                    record_states[n] = RECORD_STATE_INACTIVE
                else:
                    formset_errors = True

        # If there are no errors, just return a fresh GET request
        if not formset_errors:
            return HttpResponseRedirect(reverse('member-signup-review'))
    else:

        new_members = models.MemberSignUp.objects.filter(saved=False).filter(spam=False).filter(active=True)
        new_members_count = new_members.count()

        record_ids = []
        record_states = []

        for n in range(0, new_members_count):
            record_ids.append(str(new_members[n].id))
            record_states.append(RECORD_STATE_ACTIVE)

        data = {
            'form-TOTAL_FORMS': unicode(new_members_count),
            'form-INITIAL_FORMS': unicode(new_members_count),
            'form-MAX_NUM_FORMS': u'',
            }
    
        formset = MemberSignUpReviewFormSet(data)

        '''
        We have to clear the errors on a GET request because for some reason the forms are trying to 
        validate, even on GETs. We also take the opportunity to set the referring member choices 
        here
        '''
        for form in formset.forms:
            form.errors.clear()
            #form.set_referring_member_choices(member_choices)

    context["formset"] = formset
    context["record_ids"] = ','.join(record_ids)
    context["record_states"] = ','.join(record_states)
    context["formset_members_recordstates"] = zip(formset.forms, new_members, record_states)

    template = get_template('membership/member_signup_review.html')
    return HttpResponse(template.render(context))
Ejemplo n.º 4
0
def account_form(request, id=None):
    '''
    edit account info
    '''

    if not has_elevated_perm(request, 'membership', 'add_account'):
        return HttpResponseRedirect(reverse('welcome'))

    context = RequestContext(request)
    if id:
        account = get_object_or_404(models.Account, id=id)
        context['edit'] = True
        old_values = copy.deepcopy(account.__dict__)
    else:
        account = models.Account()
    if request.method == 'POST':
        if 'cancel' in request.POST:
            if id:
                return HttpResponseRedirect(reverse('account', args=[id]))
            else:
                return HttpResponseRedirect(reverse('accounts'))
        if 'delete' in request.POST:
            #account.delete()
            #log(request, account, 'delete')
            return HttpResponseRedirect(reverse('accounts'))
        form = forms.AccountForm(request.POST, instance=account)
        related_member_formset = forms.RelatedMemberFormSet(request.POST, 
                instance=account, prefix='related_member')
        if form.is_valid() and related_member_formset.is_valid():


            if context.get('edit'):
                account = form.save()
                log(request, account, 'edit', old_values=old_values)
            else:
                account = form.save()
                log(request, account, 'add')

            #account_log_entry = c_models.LogEntry()
            #account_log_entry.record_entry(account, request.user)
            #account_log_entry.save()

            _setattr_formset_save(request, related_member_formset, 'account', account)

            '''
            We call account.save once last time here because this it is
            during account's post_save signal that the new account 
            revision is created, and we need that formset saved before
            getting an accurate revision
            '''
            account.save()

            return HttpResponseRedirect(reverse('account', args=[account.id]))
    else:
        form = forms.AccountForm(instance=account)
        related_member_formset = forms.RelatedMemberFormSet(instance=account, 
                prefix='related_member')
    context['account'] = account
    context['form'] = form
    context['formsets'] = [
        (related_member_formset, 'Members'), 
    ]
    template = get_template('membership/account_form.html')
    return HttpResponse(template.render(context))
Ejemplo n.º 5
0
def member_form(request, username=None):
    '''
    edit member info
    '''
    edit = bool(username)
    if edit:
        user = get_object_or_404(User, username=username)
        member = user.get_profile()
        user_old_values = copy.deepcopy(user.__dict__)
        member_old_values = copy.deepcopy(member.__dict__)
    else:
        user = User()
        user.set_password(User.objects.make_random_password())
        member = models.Member()

    is_errors = False
    if request.method == 'POST':
        if 'cancel' in request.POST:
            if edit:
                # FIXME this is bad if member has more than one account
                return HttpResponseRedirect(member.accounts.all()[0].get_absolute_url())
            else:
                return HttpResponseRedirect(reverse('accounts'))
        if 'delete' in request.POST:
            # We dpn't allow deleting members from MESS anymore
            #member.delete()
            #user.delete()
            return HttpResponseRedirect(reverse('accounts'))
        user_form = forms.UserForm(request.POST, prefix='user', instance=user)
        user_email_form = forms.UserEmailForm(request.POST, instance=user)
        member_form = forms.MemberForm(request.POST, prefix='member', instance=member)
        member_interest_form = forms.MemberInterestForm(request.POST, prefix='member_interest', instance=member)
        if has_elevated_perm(request, 'membership', 'add_member'):
            related_account_formset = forms.RelatedAccountFormSet(request.POST, 
                    instance=member, prefix='related_account')
            LOA_formset = forms.LeaveOfAbsenceFormSet(request.POST, 
                    instance=member, prefix='leave_of_absence')
        address_formset = forms.AddressFormSet(request.POST, instance=member,
                prefix='address')
        phone_formset = forms.PhoneFormSet(request.POST, instance=member,
                prefix='phone')
        if has_elevated_perm(request, 'membership', 'add_member'):
            if (user_form.is_valid() and member_form.is_valid() and 
                    related_account_formset.is_valid() and 
                    LOA_formset.is_valid()): 
                user = user_form.save()

                member = member_form.save(commit=False)
                member.user = user
                member.save()
                member_form.save_m2m()

                if edit:
                    log(request, user, 'edit', old_values=user_old_values)
                    log(request, member, 'edit', old_values=member_old_values)
                else:
                    log(request, user, 'add')
                    log(request, member, 'add')

                for formset in (related_account_formset, LOA_formset): 
                    _setattr_formset_save(request, formset, 'member', member)

                '''
                We perform one more member.save() after the formsets have been 
                saved. We do this because it is during the post_save of 
                member.save() that the member revision is created, and to ensure
                we get an accurate revision the formset has to have been saved
                '''
                member.save()
                
                if not edit:
                    # TODO send member an email with login information see #224
                    # see also password_reset in django.contrib.auth.views.py
                    pass


            else:
                is_errors = True


        else:
            if user_email_form.is_valid():
                user = user_email_form.save()
            else:
                is_errors = True

                # We notify the member coordinator if a non-staff user has updated
                # their own profile
                if not request.user.is_staff and request.user.id == member_instance.user.id:
                    notify_member_coordinator(member_instance)

        # must be after member.save() in case member is newly added
        if address_formset.is_valid() and phone_formset.is_valid() and not is_errors:
            for formset in (address_formset, phone_formset):
                _setattr_formset_save(request, formset, 'member', member)
        else: 
            is_errors = True



        if member_interest_form.is_valid() and not is_errors:
            member_instance = member_interest_form.save(commit=False)
            member_instance.availability = get_member_availability(member_interest_form)
            member_instance.save()
            member_interest_form.save_m2m()
        else:
            is_errors = True

        if not is_errors:
             # FIXME this is bad if member has more than one account
            try:
                redirect = member.accounts.all()[0].get_absolute_url()
            except IndexError:
                redirect = reverse('accounts')
            return HttpResponseRedirect(redirect)
    else:
        user_form = forms.UserForm(instance=user, prefix='user')
        user_email_form = forms.UserEmailForm(instance=user)
        member_form = forms.MemberForm(instance=member, prefix='member')
        member_interest_form = forms.MemberInterestForm(instance=member, prefix='member_interest')
        set_member_availability(member, member_interest_form)
        related_account_formset = forms.RelatedAccountFormSet(instance=member, 
                prefix='related_account')
        address_formset = forms.AddressFormSet(instance=member, 
                prefix='address')
        phone_formset = forms.PhoneFormSet(instance=member, prefix='phone')
        LOA_formset = forms.LeaveOfAbsenceFormSet(instance=member, 
                prefix='leave_of_absence')
    context = RequestContext(request)
    context['member'] = member
    context['user_form'] = user_form
    context['user_email_form'] = user_email_form
    context['member_form'] = member_form
    context['member_interest_form'] = member_interest_form
    if has_elevated_perm(request, 'membership', 'add_member'):
        context['formsets'] = [
            (related_account_formset, 'Accounts'), 
            (LOA_formset, 'Leaves of Absence'),
            (address_formset, 'Addresses'), 
            (phone_formset, 'Phones'),
        ]
    else:
        context['formsets'] = [
            (address_formset, 'Addresses'), 
            (phone_formset, 'Phones'),
        ]
    context['is_errors'] = is_errors
    context['edit'] = edit
    template = get_template('membership/member_form.html')
    return HttpResponse(template.render(context))