Esempio n. 1
0
def add_view(request):
    if not request.user.has_perm('membership.add_membership'):
        raise PermissionDenied
    data = json.loads(request.POST['clump_data'])

    account_id = data['account_id']
    membership_type = data['membership_type']
    is_issue_key = data['is_issue_key']
    start_date = _iso_date_str_to_python_date(data['start_date']).date()
    ndc_old_id = data['ndc_old_id']

    membership = Membership(
        start_date=start_date,
        membership_type=membership_type,
        is_issue_key=is_issue_key,
        user_id=account_id
    )
    response = {}
    try:
        membership.save()
        membership_serialized = Membership_serializer(membership).data

        if ndc_old_id!=None:
            user = Ndc_user.objects.get(pk=account_id)
            user.ndc_old_id = ndc_old_id
            user.save()

        response['membership'] = membership_serialized
    except MembershipOverlapError:
        response['error'] = 'Membership overlap error'
    except IntegrityError:
        response['error'] = 'Integrity error - id might already in used'

    return HttpResponse(json.dumps(response, cls=DjangoJSONEncoder),content_type='application/json')
Esempio n. 2
0
def register(request):
    """Return a registration form and create a new authorised user"""
    registration_form = UserRegistrationForm(request.POST or None)
    context = {'registration_form': registration_form}
    if request.user.is_authenticated:
        return redirect(reverse('index'))
    if request.method == "POST":
        if registration_form.is_valid():
            # Ensure username saves as lowercase to the db
            registration_form.save()
            user = auth.authenticate(username=request.POST['username'],
                                     password=request.POST['password1'])
            membership = Membership(user=user)
            membership.save()
            if user:
                auth.login(user=user, request=request)
                messages.success(request, (f"{user.first_name}, you "
                                           "have successfully registered!"))
                return redirect(reverse('index'))
            else:
                messages.error(request,
                               "Unable to register your account at this time")
    else:
        registration_form = UserRegistrationForm()

    return render(request, 'register.html', context)
Esempio n. 3
0
def register(request):
	if request.POST.has_key('user_no'):
		Membership.objects.filter(id=request.POST['user_no']).update(**
		{
			'firstname':request.POST['firstname'], 
			'lastname':request.POST['lastname'], 
			'ph':request.POST['ph'], 
			'street1':request.POST['street1'],
			'street2':request.POST['street2'], 
			'city':request.POST['city'], 
			'state':request.POST['state'].upper(), 
			'zipcode':request.POST['zipcode']
		})
		return HttpResponse("<script>window.alert('Edited!');document.location.replace('/membership/myCart/');</script>")
	else:
		# Avoid registering with a duplicated username
		try:
			Membership.objects.get(username=request.POST['username'])
		except:
			if isNumber(request.POST['zip']) == False:
				return HttpResponse("<script>window.alert('Zip code must be numbers. Please try again');window.history.go(-1);</script>")
			elif isNumber(request.POST['ph']) == False:
				return HttpResponse("<script>window.alert('Phone number must be numbers. Please try again');window.history.go(-1);</script>")
			else:
				if request.POST.has_key('admin') == 'yes':
					admin = 'y'
				else:
					admin = 'n'

				signup = Membership(**
				{
					'username':request.POST['username'], 
					'password':request.POST['password'],
					'firstname':request.POST['firstname'], 
					'lastname':request.POST['lastname'],
					'ph':request.POST['ph'], 
					'street1':request.POST['street1'], 
					'street2':request.POST['street2'], 
					'city':request.POST['city'], 
					'state':request.POST['state'].upper(), 
					'zipcode':request.POST['zip'], 
					'admin':admin
				})
				signup.save()

				login = Membership.objects.get(username=request.POST['username'])
				request.session['username'] = request.POST['username']
				request.session['user_no'] = login.id
				request.session.get_expire_at_browser_close()

			return HttpResponse("<script>window.alert('Thank you for visiting PyMall!\\nEnjoy your shopping!');document.location.replace('/');</script>")
		else:
			return HttpResponse("<script>window.alert('This username has already been taken.\\nPlease choose another username.');history.back();</script>")
Esempio n. 4
0
def try_apply_purchased_membership(request, bag):

    MEMBERSHIP_MIN_ID = 1000

    # check if there was a membership in the bag
    for item_id in list(bag.keys()):
        item_id_int = int(item_id)
        if item_id_int >= MEMBERSHIP_MIN_ID:

            len = None
            is_premium = False

            # TODO: this code is purposefully simple to avoid adding a whole new payment concept
            if item_id_int == 1000:
                len = 1
            elif item_id_int == 1001:
                len = 6
            elif item_id_int == 1002:
                len = 12
            elif item_id_int == 1003:
                len = 1
                is_premium = True
            elif item_id_int == 1004:
                len = 6
                is_premium = True
            elif item_id_int == 1005:
                len = 12
                is_premium = True

            if len:

                expiry = datetime.now()

                # check for existing membership for this user
                try:
                    member_obj = Membership.objects.get(user=request.user)
                    current_datetime = datetime.combine(member_obj.expiry, datetime.min.time())
                    if current_datetime > expiry:
                        expiry = current_datetime
                except Membership.DoesNotExist:
                    member_obj = Membership(user=request.user)

                # calculate end date
                member_obj.expiry = (expiry + relativedelta(months=+len)).date()
                member_obj.is_premium = is_premium

                # insert or update membership entry
                member_obj.save()
Esempio n. 5
0
def create_dummy_member(status, type='P', mid=None):
    if status not in ['N', 'P', 'A']:
        raise Exception("Unknown membership status")  # pragma: no cover
    if type not in ['P', 'S', 'O', 'H']:
        raise Exception("Unknown membership type")  # pragma: no cover
    i = random.randint(1, 300)
    fname = random_first_name()
    d = {
        'street_address': 'Testikatu %d' % i,
        'postal_code': '%d' % (i + 1000),
        'post_office': 'Paska kaupunni',
        'country': 'Finland',
        'phone': "%09d" % (40123000 + i),
        'sms': "%09d" % (40123000 + i),
        'email': '*****@*****.**' % i,
        'homepage': 'http://www.example.com/%d' % i,
        'first_name': fname,
        'given_names': '%s %s' % (fname, "Kapsi"),
        'last_name': random_last_name(),
    }
    contact = Contact(**d)
    contact.save()
    if type == 'O':
        contact.organization_name = contact.name()
        contact.first_name = u''
        contact.last_name = u''
        contact.save()
        membership = Membership(
            id=mid,
            type=type,
            status=status,
            organization=contact,
            nationality='Finnish',
            municipality='Paska kaupunni',
            extra_info='Hintsunlaisesti semmoisia tietoja.')
    else:
        membership = Membership(
            id=mid,
            type=type,
            status=status,
            person=contact,
            nationality='Finnish',
            municipality='Paska kaupunni',
            extra_info='Hintsunlaisesti semmoisia tietoja.')
    logger.info("New application %s from %s:." % (str(contact), '::1'))
    membership.save()
    return membership
Esempio n. 6
0
def create_dummy_member(status, type='P', mid=None):
    if status not in ['N', 'P', 'A']:
        raise Exception("Unknown membership status")  # pragma: no cover
    if type not in ['P', 'S', 'O', 'H']:
        raise Exception("Unknown membership type")  # pragma: no cover
    i = random.randint(1, 300)
    fname = random_first_name()
    d = {
        'street_address' : 'Testikatu %d'%i,
        'postal_code' : '%d' % (i+1000),
        'post_office' : 'Paska kaupunni',
        'country' : 'Finland',
        'phone' : "%09d" % (40123000 + i),
        'sms' : "%09d" % (40123000 + i),
        'email' : '*****@*****.**' % i,
        'homepage' : 'http://www.example.com/%d'%i,
        'first_name' : fname,
        'given_names' : '%s %s' % (fname, "Kapsi"),
        'last_name' : random_last_name(),
    }
    contact = Contact(**d)
    contact.save()
    if type == 'O':
        contact.organization_name = contact.name()
        contact.first_name = u''
        contact.last_name = u''
        contact.save()
        membership = Membership(id=mid, type=type, status=status,
                                organization=contact,
                                nationality='Finnish',
                                municipality='Paska kaupunni',
                                extra_info='Hintsunlaisesti semmoisia tietoja.')
    else:
        membership = Membership(id=mid, type=type, status=status,
                                person=contact,
                                nationality='Finnish',
                                municipality='Paska kaupunni',
                                extra_info='Hintsunlaisesti semmoisia tietoja.')
    logger.info("New application %s from %s:." % (str(contact), '::1'))
    membership.save()
    return membership
Esempio n. 7
0
 def create_membership(self, member):
     m = Membership(
         title=member['TITLE'],
         first_name=member['FIRSTNAME'],
         initial=member['INITIAL'],
         last_name=member['LASTNAME'],
         agency=member['AGENCY'],
         address1=member['ADDRESS 1'],
         address2=member['ADDRESS 2'],
         city=member['CITY'],
         state=member['STATE'],
         zip_code=member['ZIP CODE'],
         telephone=member['TELEPHONE'],
         work_telephone=member['WORKPHONE'],
         email=member['Email Address'],
         member_type=member['TYPE'],
         billing_quarter=member['BILLING_QT'],
         dues_paid=self.convert_date(member['DUES_PAID']),
         digital_newsletter=True if member['E-Newsletter'] else False,
         print_newsletter=True if member['Newsletter'] == 'X' else False,
         create_date=self.convert_date(member['New member']),
         notes=member['NOTE'])
     m.save()
Esempio n. 8
0
    def create_dummy_member(self, i, duplicate_of=None):
        fname = random_first_name()
        d = {
            'street_address' : 'Testikatu %d'%i,
            'postal_code' : '%d' % (i+1000),
            'post_office' : 'Paska kaupunni',
            'country' : 'Finland',
            'phone' : "%09d" % (40123000 + i),
            'sms' : "%09d" % (40123000 + i),
            'email' : '*****@*****.**' % i,
            'homepage' : 'http://www.example.com/%d'%i,
            'first_name' : fname,
            'given_names' : '%s %s' % (fname, "Kapsi"),
            'last_name' : random_last_name(),
        }

        if duplicate_of is not None:
            d['first_name'] = duplicate_of.person.first_name
            d['last_name'] = duplicate_of.person.last_name

        person = Contact(**d)
        person.save()
        membership = Membership(type='P', status='N',
                                person=person,
                                nationality='Finnish',
                                municipality='Paska kaupunni',
                                extra_info='Hintsunlaisesti semmoisia tietoja.')

        self.stdout.write(unicode(person))
        membership.save()

        forward_alias = Alias(owner=membership,
                              name=Alias.email_forwards(membership)[0])
        forward_alias.save()


        login_alias = Alias(owner=membership, account=True,
                            name=choice(Alias.unix_logins(membership)))
        login_alias.save()

        # Services
        forward_alias_service = Service(servicetype=ServiceType.objects.get(servicetype='Email alias'),
                                        alias=forward_alias, owner=membership, data=forward_alias.name)
        forward_alias_service.save()

        unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'),
                                       alias=login_alias, owner=membership, data=login_alias.name)
        unix_account_service.save()

        if random() < 0.6:
            mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'),
                                    alias=login_alias, owner=membership, data=login_alias.name.replace('-', '_'))
            mysql_service.save()
        if random() < 0.6:
            postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'),
                                         alias=login_alias, owner=membership, data=login_alias.name)
            postgresql_service.save()
        # End of services

        logger.info("New application %s from %s:." % (str(person), '::1'))
        return membership
Esempio n. 9
0
def create_member(mdata, logins):
    # legacy fields
    # ['application_id', 'sendinfo', 'memberclass', 'applicationtime', 'sms',
    # 'id', 'email', 'website', 'publicwebsite', 'lastname', 'phone',
    # 'firstnames', 'address', 'nationality', 'post', 'removed', 'publicname',
    # 'name', 'mobile', 'residence', 'time', 'publicemail', 'period_start',
    # 'period_end']
    # TODO: latest billing period start date?
    post_index = mdata['post'].find(' ')
    postcode = mdata['post'][:post_index]
    postoffice = mdata['post'][post_index+1:]
    d = {
        'street_address' : mdata['address'],
        'postal_code' : postcode,
        'post_office' : postoffice,
        'country' : mdata['nationality'],
        'phone' : mdata['phone'].replace(" ", "").replace("-", ""),
        'sms' : mdata['sms'].replace(" ", "").replace("-", ""),
        'email' : mdata['email'].strip(" "),
        'homepage' : mdata['website'].strip(" "),
        'first_name' : mdata['name'].strip(" "),
        'given_names' : mdata['firstnames'].strip(" "),
        'last_name' : mdata['lastname'].strip(" "),
        # mdata['application_id'],
        # mdata['sendinfo'],
    }

    # Hide non-public websites
    if not mdata['publicwebsite']:
        d['homepage'] = ""

    if not mdata['memberclass']:
        mtype = 'P'
        print >> sys.stderr, "# Member type missing for member %d" % mdata['id']
    elif mdata['memberclass'] == 'member':
        mtype = 'P'
    elif mdata['memberclass'] == 'supporting':
        mtype = 'S'
    elif mdata['memberclass'] == 'organization':
        mtype = 'O'
    elif mdata['memberclass'] == 'honorary':
        mtype = 'H'
    else:
        print >> sys.stderr, "! Not importing, member class unknown for member %d" % mdata['id']
        return False

    contact = Contact(**d)
    contact.save()
    if mtype == 'O':
        membership = Membership(id=mdata['id'], type=mtype, status='A',
                                created=datetime.utcfromtimestamp(mdata['time']),
                                approved=datetime.utcfromtimestamp(mdata['time']),
                                organization=contact,
                                nationality=mdata['nationality'],
                                municipality=mdata['residence'],
                                extra_info='Imported from legacy',
                                public_memberlist=bool(mdata['publicname']))
    else:
        membership = Membership(id=mdata['id'], type=mtype, status='A',
                                created=datetime.utcfromtimestamp(mdata['time']),
                                approved=datetime.utcfromtimestamp(mdata['time']),
                                person=contact,
                                nationality=mdata['nationality'],
                                municipality=mdata['residence'],
                                extra_info='Imported from legacy',
                                public_memberlist=bool(mdata['publicname']))
    logger.info("Member %s imported from legacy database." % (unicode(contact)))
    membership.save()

    # Create a period only if there already is one previously. Else let
    # makebills create one.
    if mdata.has_key('period_start'):
        billing_cycle = BillingCycle(membership=membership, is_paid=False,
                                     start=datetime.strptime(mdata['period_start'], "%Y-%m-%d %H:%M:%S"),
                                     end=datetime.strptime(mdata['period_end'], "%Y-%m-%d %H:%M:%S")+timedelta(days=1))
        billing_cycle.save()
        bill = Bill(billingcycle=billing_cycle)
        bill.save()
        # Due to auto_now_add, need to save first before changing
        bill.created=datetime.strptime(mdata['bill_creation'], "%Y-%m-%d %H:%M:%S")
        bill.due_date=datetime.strptime(mdata['bill_dueday'], "%Y-%m-%d %H:%M:%S")
        bill.save()
    for alias in mdata['aliases']:
        if alias in logins:
            a = Alias(owner=membership, name=alias, account=True,
                      created=membership.created)
        else:
            a = Alias(owner=membership, name=alias, account=False,
                      created=membership.created)
        a.save()

        account_alias_count = Alias.objects.filter(owner=a.owner, account=True).count()
        if account_alias_count > 1:
            logger.warning("%i account aliases for %s" % (account_alias_count, a.owner))

    log_change(membership, user, change_message="Imported into system")
    return True
Esempio n. 10
0
    def create_dummy_member(self, i, duplicate_of=None):
        fname = random_first_name()
        d = {
            'street_address': 'Testikatu %d' % i,
            'postal_code': '%d' % (i + 1000),
            'post_office': 'Paska kaupunni',
            'country': 'Finland',
            'phone': "%09d" % (40123000 + i),
            'sms': "%09d" % (40123000 + i),
            'email': '*****@*****.**' % i,
            'homepage': 'http://www.example.com/%d' % i,
            'first_name': fname,
            'given_names': '%s %s' % (fname, "Kapsi"),
            'last_name': random_last_name(),
        }

        if duplicate_of is not None:
            d['first_name'] = duplicate_of.person.first_name
            d['last_name'] = duplicate_of.person.last_name

        person = Contact(**d)
        person.save()
        if random() < 0.2:
            public_memberlist = True
        else:
            public_memberlist = False
        membership = Membership(
            type='P',
            status='N',
            person=person,
            nationality='Finnish',
            municipality='Paska kaupunni',
            public_memberlist=public_memberlist,
            extra_info='Hintsunlaisesti semmoisia tietoja.')

        self.stdout.write(unicode(person))
        membership.save()

        forward_alias = Alias(owner=membership,
                              name=Alias.email_forwards(membership)[0])
        forward_alias.save()

        login_alias = Alias(owner=membership,
                            account=True,
                            name=choice(Alias.unix_logins(membership)))
        login_alias.save()

        # Services
        forward_alias_service = Service(
            servicetype=ServiceType.objects.get(servicetype='Email alias'),
            alias=forward_alias,
            owner=membership,
            data=forward_alias.name)
        forward_alias_service.save()

        unix_account_service = Service(
            servicetype=ServiceType.objects.get(servicetype='UNIX account'),
            alias=login_alias,
            owner=membership,
            data=login_alias.name)
        unix_account_service.save()

        if random() < 0.6:
            mysql_service = Service(servicetype=ServiceType.objects.get(
                servicetype='MySQL database'),
                                    alias=login_alias,
                                    owner=membership,
                                    data=login_alias.name.replace('-', '_'))
            mysql_service.save()
        if random() < 0.6:
            postgresql_service = Service(servicetype=ServiceType.objects.get(
                servicetype='PostgreSQL database'),
                                         alias=login_alias,
                                         owner=membership,
                                         data=login_alias.name)
            postgresql_service.save()
        # End of services

        logger.info("New application %s from %s:." % (str(person), '::1'))
        return membership
Esempio n. 11
0
    def create_dummy_member(self, i, duplicate_of=None):
        fname = random_first_name()
        d = {
            "street_address": "Testikatu %d" % i,
            "postal_code": "%d" % (i + 1000),
            "post_office": "Paska kaupunni",
            "country": "Finland",
            "phone": "%09d" % (40123000 + i),
            "sms": "%09d" % (40123000 + i),
            "email": "*****@*****.**" % i,
            "homepage": "http://www.example.com/%d" % i,
            "first_name": fname,
            "given_names": "%s %s" % (fname, "Kapsi"),
            "last_name": random_last_name(),
        }

        if duplicate_of is not None:
            d["first_name"] = duplicate_of.person.first_name
            d["last_name"] = duplicate_of.person.last_name

        person = Contact(**d)
        person.save()
        if random() < 0.2:
            public_memberlist = True
        else:
            public_memberlist = False
        membership = Membership(
            type="P",
            status="N",
            person=person,
            nationality="Finnish",
            municipality="Paska kaupunni",
            public_memberlist=public_memberlist,
            extra_info="Hintsunlaisesti semmoisia tietoja.",
        )

        self.stdout.write(unicode(person))
        membership.save()

        forward_alias = Alias(owner=membership, name=Alias.email_forwards(membership)[0])
        forward_alias.save()

        login_alias = Alias(owner=membership, account=True, name=choice(Alias.unix_logins(membership)))
        login_alias.save()

        # Services
        forward_alias_service = Service(
            servicetype=ServiceType.objects.get(servicetype="Email alias"),
            alias=forward_alias,
            owner=membership,
            data=forward_alias.name,
        )
        forward_alias_service.save()

        unix_account_service = Service(
            servicetype=ServiceType.objects.get(servicetype="UNIX account"),
            alias=login_alias,
            owner=membership,
            data=login_alias.name,
        )
        unix_account_service.save()

        if random() < 0.6:
            mysql_service = Service(
                servicetype=ServiceType.objects.get(servicetype="MySQL database"),
                alias=login_alias,
                owner=membership,
                data=login_alias.name.replace("-", "_"),
            )
            mysql_service.save()
        if random() < 0.6:
            postgresql_service = Service(
                servicetype=ServiceType.objects.get(servicetype="PostgreSQL database"),
                alias=login_alias,
                owner=membership,
                data=login_alias.name,
            )
            postgresql_service.save()
        # End of services

        logger.info("New application %s from %s:." % (str(person), "::1"))
        return membership