def setUp(self): 
     self.c = Club()
     self.c.name = "test club"
     self.c.full_clean()
     self.c.save()
     
     self.user1 = User()
     self.user1.first_name = "Justin"
     self.user1.last_name = "Gray"
     self.user1.username = "******"
     self.user1.save()
     
     self.user2 = User()
     self.user2.first_name = "Sirius"
     self.user2.last_name = "Gray"
     self.user2.username = "******"
     self.user2.save()
     
     m= Membership()
     m.user_prof = self.user1.get_profile()
     m.club = self.c
     m.num = 1
     m.start = datetime.date.today() - datetime.timedelta(days=300)
     m.valid_thru = datetime.date.today()+datetime.timedelta(days=1)
     m.paid = True
     
     m.full_clean()
     m.save()
 def setUp(self): 
     self.c = Club()
     self.c.name = "test club"
     self.c.full_clean()
     self.c.save()
     
     self.season = Season()
     self.season.club = self.c
     self.season.year = 2011
     self.season.save()
     
     self.race_class = RaceClass()
     self.race_class.name = "CSP"
     self.race_class.pax = .875
     self.race_class.club = self.c
     self.race_class.save()
     
     self.e = Event()
     self.e.name = "test event"
     self.e.date = datetime.date.today()
     self.e.season = self.season
     self.e.club = self.c
     self.e.save()        
     
     self.user = User()
     self.user.first_name = "justin"
     self.user.last_name = "gray"
     self.user.username = "******"
     self.user.save()
     
     self.user2 = User()
     self.user2.first_name = "sirius"
     self.user2.last_name = "gray"
     self.user2.username = "******"
     self.user2.save()
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "justin"
        self.user.last_name = "gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "sirius"
        self.user2.last_name = "gray"
        self.user2.username = "******"
        self.user2.save()
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.user1 = User()
        self.user1.first_name = "Justin"
        self.user1.last_name = "Gray"
        self.user1.username = "******"
        self.user1.save()

        self.user2 = User()
        self.user2.first_name = "Sirius"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        m = Membership()
        m.user_prof = self.user1.get_profile()
        m.club = self.c
        m.num = 1
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today() + datetime.timedelta(days=1)
        m.paid = True

        m.full_clean()
        m.save()
    def test_coupon_notification(self):

        user = User()
        user.first_name = "justin"
        user.last_name = "gray"
        user.username = "******"
        user.email = "*****@*****.**"
        user.save()

        club = Club()
        club.name = "test-test"
        club.save()

        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.user_prof = user.get_profile()
        c.save()

        #make sure notification email was sent
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, u'New example.com coupon')
Exemplo n.º 6
0
 def get(self, request):
     context = {
         'totalprojects':
         Project.project_query().get('allprojects').count(),
         'totalusers': User.user_query().get('allusers').count(),
         'allocatepercent': employeesallocated().get('allocatepercent'),
         'allocatedusers': User.user_query().get('allusers').count(),
         'failpercent': employeesallocated().get('failpercent'),
         'finishpercent': employeesallocated().get('finishpercent'),
         'wellpercent': employeesallocated().get('wellpercent')
     }
     return render(request, 'dashboard.html', context)
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = 0.875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)
Exemplo n.º 9
0
 def testEventisRegd(self): 
     
     self.e.save()
     
     u = User()
     u.first_name = "Justin" 
     u.last_name = "Gray"
     u.username = "******"
     
     u.save()
     
     rc = RaceClass()
     rc.abrv = "CSP"
     rc.name = "CSP"
     rc.pax = 1
     rc.club = self.c
     rc.save()
             
     self.assertFalse(self.e.is_regd(u))        
     
     r = Registration()
     r.event = self.e
     r.number = 11
     r.race_class = rc
     r.user_profile = u.get_profile()
     r.club = self.c
     r.save()
     
     self.assertTrue(self.e.is_regd(u))
Exemplo n.º 10
0
def valid_email(request):
    """
    Return true if the email is valid and false otherwise. Used exclusively for form validation.
    """

    email = request.GET.get('email')
    user = request.user
    try:
        User.valid_email(email, user)
        valid = True
    except ValidationError:
        valid = False

    return ajax_http(True, extra_json={'valid': valid})
    def test_coupon_notification(self):     

        user = User()
        user.first_name = "justin"
        user.last_name = "gray"
        user.username = "******"
        user.email = "*****@*****.**"
        user.save()

        club = Club()
        club.name ="test-test"
        club.save()
 
        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.user_prof = user.get_profile()
        c.save()

        #make sure notification email was sent
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 
            u'New example.com coupon')
Exemplo n.º 12
0
 class Meta(UserCreationForm.Meta):
     fields = [
         User.get_email_field_name(),
         "first_name",
         "last_name",
         "password1",
         "password2",
     ]
     labels = {
         User.get_email_field_name(): _("Email"),
         "first_name": _("First Name"),
         "last_name": _("Last Name"),
         "password1": _("Password"),
         "password2": _("Confirm Password"),
     }
Exemplo n.º 13
0
def valid_email(request):
    """
    Return true if the email is valid and false otherwise. Used exclusively for form validation.
    """

    email = request.GET.get('email')
    user = request.user
    try:
        User.valid_email(email, user)
        valid = True
    except ValidationError:
        valid = False

    return ajax_http(True,
                     extra_json={'valid': valid})
Exemplo n.º 14
0
def create_payment_intent(request):
    if request.method == 'POST':
        user = User.get_user(request.session['user'])

        amount = int(request.data['amount'])
        currency = request.data['currency']
        coupon = request.data['coupon']
        stripe_customer_id = None
        stripe.api_key = settings.STRIPE_PRIVATE_KEY

        metadata = {
            'payment_flow': 'any description here ',
            'booking_type': 'instant_booking',
            'listing_price_at_booking_time': 'add listing price here ',
            'lesson_duration': '60 mins',
        }
        intent = stripe.PaymentIntent.create(
            amount=(amount * 100),
            currency=currency,
            metadata=metadata,
            receipt_email=user.email,
            customer=stripe_customer_id,
            description='instant booking amount paid by ' +
            user.key.urlsafe().decode(),
        )
        return Response({
            'status': status.HTTP_200_OK,
            'intent_id': intent.id,
            'client_secret': intent.client_secret
        })
Exemplo n.º 15
0
 def authenticate(self, email=None, password=None, email_confirm_link=None):
     """
     This authentication method tries to look up the user by both email address and email confirmation link.
     We want to log users in after they click the email confirmation link, but the server won't have their password
     after they click it. Thus, we want to be able to authenticate a user solely based on that email link object.
     """
     user = None
     if email and password:
         period_found = False
         at_found = False
         for char in email:
             if char == '@':
                 at_found = True
             elif char == '.':
                 period_found = True
         # If an email address was submitted, look up user via unique email
         if period_found and at_found:
             user = User.get_user_by_email(email)
             if not (user and user.check_password(password)):
                 user = None
     elif email_confirm_link:
         user = email_confirm_link.get_user_from_link()
     else:
         # Run the default password hasher once to reduce the timing
         # difference between an existing and a non-existing user (Django ticket #20760).
         make_password(password)
     return user
Exemplo n.º 16
0
    def handle(self, *args, **options):
        if options['truncate']:
            User.objects.all().delete()

        with open(SEED_FILE) as f:
            friends = json.load(f)

        bulk_friend = []
        for friend in friends:
            bulk_friend.append(
                User(
                    username=friend['domain'],
                    email='*****@*****.**',
                    password=make_password('52412630aA'),
                    first_name=friend['first_name'],
                    last_name=friend['last_name'],
                    city=friend['city'],
                    country='Беларусь',
                    number_phone=friend['id'],
                    avatar=friend['avatar']
                )
            )
            self.stdout.write(f"Friends {friend['first_name']} processed")

        User.objects.bulk_create(bulk_friend)
    def test_with_raceclass(self):
        f = StringIO.StringIO("\n".join(self.data))

        user = User()
        user.first_name = "CHRIS"
        user.last_name = "brubaker"
        user.username = "******"
        user.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.rc
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        result = parse_axtime(self.e, self.session, f)[0]
        runs = result.runs.all()

        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        reg = result.reg
        self.assertEqual(reg.user, user)

        self.assertEqual(reg.number, 73)
Exemplo n.º 18
0
 def test_fields_required(self):
     form = SignUpForm()
     for field in (
             User.get_email_field_name(),
             "first_name",
             "last_name",
             "password1",
             "password2",
     ):
         self.assertTrue(form.fields[field].required)
Exemplo n.º 19
0
def allocationchart_query():
    projects = []
    allocation = []
    for project in Project.project_query().get('allprojects')[:10]:
        allocation.append(int(ProjectAllocation.objects.filter(project_id=project.id).count()))
        projects.append(project.name)
    allocation.append(User.user_query().get('allusers').count())
    context = {
        'projects': projects,
        'allocation': allocation
    }
    return context
Exemplo n.º 20
0
def get_payment_method(request):
    if request.method == 'GET':
        user = User.get_user(request.session['user'])
        stripe.api_key = settings.STRIPE_PRIVATE_KEY
        user_cards = None
        if user.stripe_customer_id is not None:
            response = stripe.Customer.retrieve(user.stripe_customer_id)
            user_cards = response.sources.data
        return Response({
            'status': status.HTTP_200_OK,
            'user_cards': user_cards
        })
Exemplo n.º 21
0
    def create(self, validated_data):
        user = User(
            name=validated_data['name'],
            contact=validated_data['contact'],
            txn_id=validated_data['txn_id'],
            email=validated_data['email'],
            username=validated_data['username'],
            # first_name=validated_data['first_name'],
            # last_name=validated_data['last_name'],
            college=validated_data['college'],
            branch=validated_data['branch'],
            course=validated_data['course'],
            sem=validated_data['sem'],
            address=validated_data['address'],
            pay_mode=validated_data['pay_mode'],
        )

        # if User.objects.filter(contact=contact).exists():
        #     raise serializers.ValidationError('An account with this email already exists.')
        #     return Response(content, status=status.HTTP_409_CONFLICT)

        user.set_password(validated_data['password'])
        user.save()
        send_sms(user.contact)
        return user
    def test_with_raceclass(self):
        f = StringIO.StringIO("\n".join(self.data))

        user = User()
        user.first_name = "CHRIS"
        user.last_name = "brubaker"
        user.username = "******"
        user.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.rc
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        result = parse_axtime(self.e, self.session, f)[0]
        runs = result.runs.all()
        
        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        reg = result.reg
        self.assertEqual(reg.user, user)

        self.assertEqual(reg.number, 73)
Exemplo n.º 23
0
def register(request):
    if request.method == 'POST': # If the form has been submitted...
        form = RegistrationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            post_data = request.POST
            #:import ipdb;ipdb.set_trace()
            rec = User(username=post_data["username"],
                               first_name=post_data["first_name"],
                               last_name=post_data['last_name'],
                               email=post_data['email'],
                               date_of_birth=post_data['dob_dd']+'/'+post_data['dob_mm']+'/'+post_data['dob_yy'],
                               sex=post_data['sex'])
            rec.save()
            return HttpResponseRedirect('/registration/list/') # Redirect after POST
    else:
        form = RegistrationForm() # An unbound form

    return render(request, 'registration/registration.html', {
        'form': form,
    })    
Exemplo n.º 24
0
def get_balance(request):
    if request.method == 'GET':
        user = User.get_user(request.session['user'])
        stripe.api_key = settings.STRIPE_PRIVATE_KEY
        if user.stripe_connect_account_id is None:
            all_transfers = None
        else:
            all_transfers = stripe.Transfer.list(
                destination=user.stripe_connect_account_id, limit=1000)
        return Response({
            'status': status.HTTP_200_OK,
            'all_transfers': all_transfers
        })
Exemplo n.º 25
0
def get_payout_method(request):
    if request.method == 'GET':
        user = User.get_user(request.session['user'])
        stripe.api_key = settings.STRIPE_PRIVATE_KEY
        if user.stripe_connect_account_id is None:
            acct = None
        else:
            acct = stripe.Account.retrieve(user.stripe_connect_account_id, )
        return Response({
            'status':
            status.HTTP_200_OK,
            'acct':
            acct.external_accounts.data if acct != None else []
        })
Exemplo n.º 26
0
def register_parent_app(request, phone_no):
    data = {}
    response = 0
    if request.method == 'POST':
        try:
            registration_id = request.data["gid"]
            print str(registration_id[0])
            profile_type = request.data["type"]
            print profile_type[0]
            google_registration_id = GoogleRegistrationId.objects.create(registration_id=registration_id[0])
            user_profile = UserProfile.objects.create(regid=google_registration_id, type=profile_type[0])
            r = User(phone_no=phone_no, user_profile=user_profile)
            r.save()
            response = 1
            message = "Saved to database"
        except Exception as e:
            print e
            response = 0
            message = e.message
        data.update({
            'response': response,
            'message': message
        })
        return Response(data)
Exemplo n.º 27
0
def delete_payout_method(request):
    if request.method == 'POST':
        user = User.get_user(request.session['user'])
        stripe.api_key = settings.STRIPE_PRIVATE_KEY

        stripe.Account.delete_external_account(request.data['acc_id'],
                                               request.data['bank_id'])
        acct = None
        if user.stripe_connect_account_id is not None:
            acct = stripe.Account.retrieve(user.stripe_connect_account_id, )

        return Response({
            'status': status.HTTP_200_OK,
            'acct': acct.external_accounts.data
        })
Exemplo n.º 28
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        email_field = User.get_email_field_name()
        self.fields[email_field].validators.extend((
            validators.HTML5EmailValidator(),
            validators.validate_confusables_email,
            validators.CaseInsensitiveUnique(User, email_field,
                                             "This email is unavailable"),
        ))
        self.label_suffix = ""

        # This overrides the default labels set by UserCreationForm
        for field, label in self._meta.labels.items():
            self.fields[field].label = label

        for field in self._meta.fields:
            self.fields[field].required = True
Exemplo n.º 29
0
    def create(self, validated_data):
        user = User(
            name=validated_data['name'],
            contact=validated_data['contact'],
            email=validated_data['email'],
            college=validated_data['college'],
            branch=validated_data['branch'],
            course=validated_data['course'],
            sem=validated_data['sem'],
            city=validated_data['city']
        )

        user.otp = random.randint(100000,999999)       
        user.set_password(validated_data['password'])
        user.username = str(user.contact)
        user.save()
        message = 'Your OTP is '+ str(user.otp)
        send_sms(user.contact, message)
        return user
Exemplo n.º 30
0
def add_payment_method(request):
    if request.method == 'POST':
        user = User.get_user(request.session['user'])
        stripe.api_key = settings.STRIPE_PRIVATE_KEY
        if user.stripe_customer_id is None:
            response = stripe.Customer.create(
                email=user.email,
                name=user.first_name,
                description=user.first_name + ' ' + user.last_name,
            )
            user.stripe_customer_id = response.id
            user.put()
        source = stripe.Customer.create_source(
            user.stripe_customer_id, source=request.data['card_token'])
        return Response({
            'status': status.HTTP_200_OK,
            'user': to_json_ndb(user)
        })
Exemplo n.º 31
0
 def create(self, validated_data):
     user = User(email=validated_data['email'],
                 username=validated_data['username'],
                 first_name=validated_data['first_name'],
                 last_name=validated_data['last_name'],
                 contact=validated_data['contact'],
                 college_name=validated_data['college_name'],
                 branch_name=validated_data['branch_name'],
                 sem=validated_data['sem'],
                 address=validated_data['address'])
     user.set_password(validated_data['password'])
     user.save()
     return user
Exemplo n.º 32
0
def add_bank_account(request):
    if request.method == 'POST':
        user = User.get_user(request.session['user'])
        if not user.stripe_connect_account_id:
            country = 'GB'
            stripe.api_key = settings.STRIPE_PRIVATE_KEY
            acct = stripe.Account.create(
                country=country,
                type="custom",
                email=user.email,
                legal_entity={
                    "first_name": user.first_name,
                    "last_name": user.last_name,
                    "type": 'individual',
                    "dob": {
                        "day": '1',
                        "month": '11',
                        "year": '2000'
                    }
                },
                tos_acceptance={
                    "date": datetime.datetime.now(),
                    "ip": "119.156.76.23"
                    # "ip": self.request.remote_addr
                },
                metadata={
                    'slug': user.key.urlsafe().decode(),
                    'email': user.email,
                },
            )
            user.stripe_connect_account_id = acct.id
            user.stripe_connect_country = country
            user.put()
        acct = stripe.Account.create_external_account(
            user.stripe_connect_account_id,
            external_account=request.data['bank_token'])
        return Response({
            'status': status.HTTP_200_OK,
            'account': acct,
        })
Exemplo n.º 33
0
def userallocatedinproject():
    if User.user_query().get('allusers').count() and Project.project_query().get(
                'allprojects').count():

        context = {
            'allocatedusers': User.objects.filter(id__in=ProjectAllocation.objects.all().values('user_id')),
            'allocatepercent': (User.objects.filter(id__in=ProjectAllocation.objects.all().values('user_id')).count() / User.user_query().get(
                'allusers').count()) * 100,
            'failpercent': (Project.objects.filter(status='closed').count() / Project.project_query().get(
                    'allprojects').count()) * 100,
            'finishpercent': (Project.objects.filter(status='created').count() / Project.project_query().get(
                    'allprojects').count()) * 100,
            'wellpercent': (Project.objects.filter(status='Underprogress').count() / Project.project_query().get(
                    'allprojects').count()) * 100
        }
    else:
        context = {
            'allocatedusers': User.objects.filter(id__in=ProjectAllocation.objects.all().values('user_id')),
            'allocatepercent': (User.objects.filter(id__in=ProjectAllocation.objects.all().values('user_id')).count() / 1) * 100,
            'failpercent': (Project.objects.filter(status='closed').count() / 1) * 100,
            'finishpercent': (Project.objects.filter(status='created').count() / 1) * 100,
            'wellpercent': (Project.objects.filter(status='Underprogress').count() / 1) * 100
        }
    return context
Exemplo n.º 34
0
def user_registration(request):
    """
        End-point for user registration
    """
    
    # Validating data through serializer
    serializer = UserRegistrationSerializer(data = request.data)
    if not serializer.is_valid():
        
        logger.debug('USER REGISTRATION: Invalid data. Errors: %s' % serializer.errors)
        # Return error response if request data is invalid
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
    
    # Creating User instance and assigning data
    user = User()
    user.name = serializer.data['name']
    user.email = serializer.data['email']
    user.password = make_password(serializer.data['password'])
    user.address = serializer.data['address']
    
    # Saving user object to database
    try:
        user.save()
        logger.info("USER REGISTRATION: User object saved successfully. \
                        User email: %s, User ID: %s" % (user.email, user.id))
    except Exception as e:
        logger.debug("USER REGISTRATION: User already registered with email id %s. \
                        Error: %s" % (serializer.data['email'], e))
        return Response({'detail':'User already registered with the provided email'}, 
                        status = status.HTTP_400_BAD_REQUEST)
    
    # Calling save geo details task to run in background
    save_geo_details.apply_async([user.id, serializer.data['address']])
    
    return Response({'message':'User registered successfully', 'user_id':user.id},
                    status=status.HTTP_201_CREATED)
class TestOrder(unittest.TestCase): 
    
    def tearDown(self): 
        clear_db()
            
    def setUp(self): 
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()
        
        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()        
        
        self.user = User()
        self.user.first_name = "justin"
        self.user.last_name = "gray"
        self.user.username = "******"
        self.user.save()
        
        self.user2 = User()
        self.user2.first_name = "sirius"
        self.user2.last_name = "gray"
        self.user2.username = "******"
        self.user2.save()
    
    def test_total_price(self): 
        self.o = Order()
        self.o.user_prof = self.user.get_profile()
        self.o.save()        
        
        item1 = Registration()
        item1.number = 11
        item1.race_class = self.race_class
        item1.pax_class = None
        item1.event = self.e
        item1.price = "40.00"
        item1.order = self.o
        item1.club = self.c
        item1.save()
        
        item2 = Membership()
        item2.user_prof = self.user.get_profile()
        item2.club = self.c
        item2.num = 1
        item2.start = datetime.date.today() - datetime.timedelta(days=300)
        item2.valid_thru = datetime.date.today()+datetime.timedelta(days=1)
        item2.price = "60.00"
        item2.order = self.o
        item2.save()
        
        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, "100.00")

        club = Club()
        club.name ="test-test"
        club.save()
        
        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.save()
        
        self.o.coupon = c
        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, '90.00')        
class TestRegistration(unittest.TestCase):
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = 0.875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)

    def tearDown(self):

        clear_db()

    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = 0.5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        # set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        # make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)

    def test_calc_times_empty_results(self):
        self.r.save()

        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 0)
        self.assertEqual(self.r.total_index_time, 0)

    def test_calc_times(self):
        self.r.save()

        sess = Session()
        sess.name = "AM"
        sess.event = self.e
        sess.club = self.c
        sess.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        self.r.save()
        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 20.0)
        self.assertEqual(self.r.total_index_time, self.r.total_raw_time * self.race_class.pax)

    def testAnon(self):

        self.r._anon_f_name = "Justin"
        self.r._anon_l_name = "Gray"
        self.r._anon_car = "1990 Mazda Miata"

        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

        self.r.associate_with_user(self.user2.username)
        self.r.save()

        self.assertEqual("Eli", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testWithCar(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testAllowedNumberRaceClass(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'11 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

        # make sure you can save an existing reg
        self.r2.number = 12
        self.r2.save()

        self.r.number = 12
        # self.r.save()

        try:
            self.r.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'12 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.r3 = Registration()
        self.r3.number = 77
        self.r3.race_class = self.race_class
        self.r3.pax_class = None
        self.r3.event = self.e2
        self.r3.club = self.c
        self.r3.save()

        self.e.child_events.add(self.e2)
        self.e.save()

        self.r2.number = 77

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'77 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testMaxUserRegLimit(self):
        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.race_class.user_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.event = self.e
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e2
        self.r2.club = self.c
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'You have reached the registration limit for CSP.']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testEventRegLimit(self):
        self.race_class.event_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.event = self.e
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 21
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'Only 1 registrations for CSP are " "allowed for an event. The class is full']}",
                str(err),
            )
        else:
            self.fail("ValidationError expected")

        # test that a user can only register once, regardless of class
        self.race_class.event_reg_limit = 10
        self.race_class.save()

        self.r2.number = 111
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'You have already registered to run as 11 CSP']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testCarDeleteFromReg(self):
        """Check to make sure reg_car gets set to null if a car gets deleted"""

        self.r.car = self.car

        self.r.save()

        self.assertEqual(self.r.car, self.car)

        self.car.delete()
        reg = Registration.objects.filter(number=11).get()

        self.assertIsNone(reg.car)

    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)

    def testMakeAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()
        regs = Registration.objects.filter(event=e2).all()
        self.assertEqual(len(regs), 1)

    def testUpdateAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()

        self.r.number = 10
        self.r.save()
        self.r.update_assoc_regs()

        reg = Registration.objects.filter(event=e2).get()
        self.assertEqual(reg.number, self.r.number)
    def test_coupon_is_valid(self): 
        
        user = User()
        user.first_name = "justin"
        user.last_name = "gray"
        user.username = "******"
        user.email = "*****@*****.**"
        user.save()
        
        user2 = User()
        user2.first_name = "sirius"
        user2.last_name = "gray"
        user2.username = "******"
        user2.save()

        club = Club()
        club.name ="test-test"
        club.save()
 
        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.save()
        
        o = Order()
        o.coupon = c
        o.user_prof = user.get_profile()
        o.save()
        
        self.assertTrue(c.is_valid(user))
        c.uses_left = 0
        self.assertTrue(c.is_valid(user))

        c.expires = datetime.date.today() - datetime.timedelta(days=1)    
        self.assertTrue(c.is_valid(user))

        c.permanent = False
        self.assertFalse(c.is_valid(user))

        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.uses_left = 1
        self.assertTrue(c.is_valid(user))
        c.uses_left = 0
        self.assertFalse(c.is_valid(user))
        
        c.uses_left = 1
        c.user_prof = user.get_profile()
        self.assertFalse(c.is_valid(user2))
        
        c.user_prof = None
        c.single_use_per_user = True
        self.assertFalse(c.is_valid(user))
class TestRegistration(unittest.TestCase):
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)

    def tearDown(self):

        clear_db()

    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = .5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        #set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        #make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)

    def test_calc_times_empty_results(self):
        self.r.save()

        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 0)
        self.assertEqual(self.r.total_index_time, 0)

    def test_calc_times(self):
        self.r.save()

        sess = Session()
        sess.name = "AM"
        sess.event = self.e
        sess.club = self.c
        sess.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        self.r.save()
        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 20.0)
        self.assertEqual(self.r.total_index_time,
                         self.r.total_raw_time * self.race_class.pax)

    def testAnon(self):

        self.r._anon_f_name = "Justin"
        self.r._anon_l_name = "Gray"
        self.r._anon_car = "1990 Mazda Miata"

        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

        self.r.associate_with_user(self.user2.username)
        self.r.save()

        self.assertEqual("Eli", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testWithCar(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testAllowedNumberRaceClass(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'11 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

        #make sure you can save an existing reg
        self.r2.number = 12
        self.r2.save()

        self.r.number = 12
        #self.r.save()

        try:
            self.r.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'12 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.r3 = Registration()
        self.r3.number = 77
        self.r3.race_class = self.race_class
        self.r3.pax_class = None
        self.r3.event = self.e2
        self.r3.club = self.c
        self.r3.save()

        self.e.child_events.add(self.e2)
        self.e.save()

        self.r2.number = 77

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'77 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testMaxUserRegLimit(self):
        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.race_class.user_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.event = self.e
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e2
        self.r2.club = self.c
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'You have reached the registration limit for CSP.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testEventRegLimit(self):
        self.race_class.event_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.event = self.e
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 21
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'Only 1 registrations for CSP are "
                "allowed for an event. The class is full']}", str(err))
        else:
            self.fail("ValidationError expected")

        #test that a user can only register once, regardless of class
        self.race_class.event_reg_limit = 10
        self.race_class.save()

        self.r2.number = 111
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'You have already registered to run as 11 CSP']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testCarDeleteFromReg(self):
        """Check to make sure reg_car gets set to null if a car gets deleted"""

        self.r.car = self.car

        self.r.save()

        self.assertEqual(self.r.car, self.car)

        self.car.delete()
        reg = Registration.objects.filter(number=11).get()

        self.assertIsNone(reg.car)

    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)

    def testMakeAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()
        regs = Registration.objects.filter(event=e2).all()
        self.assertEqual(len(regs), 1)

    def testUpdateAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()

        self.r.number = 10
        self.r.save()
        self.r.update_assoc_regs()

        reg = Registration.objects.filter(event=e2).get()
        self.assertEqual(reg.number, self.r.number)
Exemplo n.º 39
0
class TestMembership(unittest.TestCase):
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.user1 = User()
        self.user1.first_name = "Justin"
        self.user1.last_name = "Gray"
        self.user1.username = "******"
        self.user1.save()

        self.user2 = User()
        self.user2.first_name = "Sirius"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        m = Membership()
        m.user_prof = self.user1.get_profile()
        m.club = self.c
        m.num = 1
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today() + datetime.timedelta(days=1)
        m.paid = True

        m.full_clean()
        m.save()

    def tearDown(self):

        clear_db()

    def test_is_active_member(self):
        self.assertTrue(self.c.is_active_member(self.user1))
        self.assertFalse(self.c.is_active_member(self.user2))

        m = Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.num = 2
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()

        m.full_clean()
        m.save()

        #make sure expired memberships don't report as active
        self.assertFalse(self.c.is_active_member(self.user2))

    def test_duplicate_id(self):
        m = Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.num = 1
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today() + datetime.timedelta(days=1)

        try:
            m.full_clean()
            m.save()
        except ValidationError as err:
            self.assertEqual(
                str(err),
                "{'__all__': [u'A member with that number already exists']}")
        else:
            self.fail("ValidationError expected")

    def test_auto_increment_number(self):
        m = Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()

        m.full_clean()
        m.save()

        self.assertEqual(m.num, 2)

    def test_is_member(self):
        up = self.user1.get_profile()

        self.assertTrue(up.is_member(self.c))
Exemplo n.º 40
0
class TestDibs(unittest.TestCase): 
    
    def setUp(self): 
        
        self.today = datetime.date.today()
        
        self.c = Club()
        self.c.name = "test"
        self.c.events_for_dibs = 2
        self.c.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.s = Season()
        self.s.year = 2011
        self.s.club = self.c
        self.s.save()
        
        self.e1 = Event()
        self.e1.name = "event1"
        self.e1.date = self.today-datetime.timedelta(days=10)
        self.e1.season = self.s
        self.e1.club = self.c
        self.e1.save()
        
        self.e2 = Event()
        self.e2.name = "event2"
        self.e2.date = self.today-datetime.timedelta(days=8)
        self.e2.season = self.s
        self.e2.club = self.c
        self.e2.save()
        
        self.e3 = Event()
        self.e3.name = "event3"
        self.e3.date = self.today-datetime.timedelta(days=5)
        self.e3.season = self.s
        self.e3.club = self.c
        self.e3.save()
        
        self.e4 = Event()
        self.e4.name = "event4"
        self.e4.date = self.today+datetime.timedelta(days=10)
        self.e4.season = self.s
        self.e4.club = self.c
        self.e4.save()
        
        self.events = [self.e1, self.e2, self.e3]       
        
        for event in self.events: 
            s = Session()
            s.event = event
            s.name = "AM"
            s.club = self.c
            s.save()
        
        self.u1 = User()
        self.u1.username = "******"
        self.u1.save()
        
        self.u2 = User()
        self.u2.username = "******"
        self.u2.save()
        
        self.u3 = User()
        self.u3.username = "******"
        self.u3.save()
        
        self.users = [self.u1, self.u2, self.u3]
        
        for i, user in enumerate(self.users): 
            up = user.get_profile()
            for j, event in enumerate(self.events): 
                if j<=i: 
                    r = Registration()
                    r.number = "%d"%(i+1)
                    r.race_class = self.race_class
                    r.pax_class = None
                    r.event = event    
                    r.user_profile = up
                    r.club = self.c
                    r.save()
                    
                    result = Result()
                    result.reg = r
                    result.session = event.sessions.all()[0]
                    result.club = self.c
                    result.save()
                    
                    for k in range(0, 3):
                        r = Run()
                        r.base_time = 10.0
                        r.calc_time = 10.0
                        r.index_time = 10.0
                        r.result = result
                        r.club = self.c
                        r.save()
   
    def tearDown(self): 
        self.u3.delete()
        self.u2.delete()
        self.u1.delete()
        self.s.delete()
        self.c.delete()
        
    def test_1_dibs(self): 
        
        self.c.assign_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        Dibs.objects.all().delete()
        
    def test_no_dibs(self): 
        reg = Registration()
        up = UserProfile.objects.get(user=self.u1)
        reg.user_profile = up
        reg.number = 15
        reg.race_class = self.race_class
        reg.pax_class = None
        reg.event = self.e4
        reg.club = self.c
        reg.save()   
        
        s = Session()
        s.event = self.e4
        s.name = "AM"
        s.club = self.c
        s.save()
        
        result = Result()
        result.reg = reg
        result.session = s
        result.club = self.c
        result.save()
        
        for k in range(0, 3):
            r = Run()
            r.base_time = 10.0
            r.calc_time = 10.0
            r.index_time = 10.0
            r.result = result
            r.club = self.c
            r.save()        
        
        self.c.assign_dibs()
        self.assertEqual(len(Dibs.objects.all()), 0) 
                        
        reg.delete()
        s.delete()
        
    def test_no_result_reg_dibs(self): 
        reg = Registration()
        up = UserProfile.objects.get(user=self.u2)
        reg.user_profile = up
        reg.number = 15
        reg.race_class = self.race_class
        reg.pax_class = None
        reg.event = self.e3
        reg.club = self.c
        reg.save() 
        
        self.c.assign_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        reg.delete()
        Dibs.objects.all().delete()
        
    def test_update_existing_dibs(self):
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.user_profile = self.u3.get_profile()
        dibs.race_class = self.race_class
        dibs.number = 3
        dibs.duration = 30
        dibs.expires = self.today+datetime.timedelta(days=5)
        dibs.save()
        dibs.created = self.today-datetime.timedelta(days=60)
        dibs.save()
        
        self.c.assign_dibs()       
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.duration, 60)
        self.assertEqual(dibs.expires, self.e3.date+datetime.timedelta(days=60))
        
        dibs.delete()
        
    def test_dont_update_old_dibs(self): 
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.user_profile = self.u1.get_profile()
        dibs.race_class = self.race_class
        dibs.number = 3
        dibs.duration = 30
        dibs.expires = self.today-datetime.timedelta(days=5)
        dibs.save()
        dibs.created = self.today-datetime.timedelta(days=60)
        dibs.save()
        
        self.c.assign_dibs()  
        
        dibs = Dibs.objects.filter(user_profile=self.u1.get_profile()).get()
        
        self.assertEqual(dibs.expires, self.today-datetime.timedelta(days=5))
        self.assertEqual(dibs.duration, 30)
        
    def test_race_class_allow_dibs(self): 
        
        self.race_class.allow_dibs = False
        self.race_class.save()
        
        self.c.assign_dibs()
        
        self.assertEqual(len(Dibs.objects.all()), 0)
        
    def test_clean_dibs(self): 
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.expires = datetime.date.today()-datetime.timedelta(days=10)
        dibs.duration = 30
        dibs.number = 99
        dibs.race_class = self.race_class
        dibs.user_profile = self.u2.get_profile()
        
        dibs.save()

        clean_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u2.get_profile()).all()), 0) 
Exemplo n.º 41
0
 def setUp(self): 
     
     self.today = datetime.date.today()
     
     self.c = Club()
     self.c.name = "test"
     self.c.events_for_dibs = 2
     self.c.save()
     
     self.race_class = RaceClass()
     self.race_class.name = "CSP"
     self.race_class.pax = .875
     self.race_class.club = self.c
     self.race_class.save()
     
     self.s = Season()
     self.s.year = 2011
     self.s.club = self.c
     self.s.save()
     
     self.e1 = Event()
     self.e1.name = "event1"
     self.e1.date = self.today-datetime.timedelta(days=10)
     self.e1.season = self.s
     self.e1.club = self.c
     self.e1.save()
     
     self.e2 = Event()
     self.e2.name = "event2"
     self.e2.date = self.today-datetime.timedelta(days=8)
     self.e2.season = self.s
     self.e2.club = self.c
     self.e2.save()
     
     self.e3 = Event()
     self.e3.name = "event3"
     self.e3.date = self.today-datetime.timedelta(days=5)
     self.e3.season = self.s
     self.e3.club = self.c
     self.e3.save()
     
     self.e4 = Event()
     self.e4.name = "event4"
     self.e4.date = self.today+datetime.timedelta(days=10)
     self.e4.season = self.s
     self.e4.club = self.c
     self.e4.save()
     
     self.events = [self.e1, self.e2, self.e3]       
     
     for event in self.events: 
         s = Session()
         s.event = event
         s.name = "AM"
         s.club = self.c
         s.save()
     
     self.u1 = User()
     self.u1.username = "******"
     self.u1.save()
     
     self.u2 = User()
     self.u2.username = "******"
     self.u2.save()
     
     self.u3 = User()
     self.u3.username = "******"
     self.u3.save()
     
     self.users = [self.u1, self.u2, self.u3]
     
     for i, user in enumerate(self.users): 
         up = user.get_profile()
         for j, event in enumerate(self.events): 
             if j<=i: 
                 r = Registration()
                 r.number = "%d"%(i+1)
                 r.race_class = self.race_class
                 r.pax_class = None
                 r.event = event    
                 r.user_profile = up
                 r.club = self.c
                 r.save()
                 
                 result = Result()
                 result.reg = r
                 result.session = event.sessions.all()[0]
                 result.club = self.c
                 result.save()
                 
                 for k in range(0, 3):
                     r = Run()
                     r.base_time = 10.0
                     r.calc_time = 10.0
                     r.index_time = 10.0
                     r.result = result
                     r.club = self.c
                     r.save()
Exemplo n.º 42
0
def register_user(request):
    """
        Takes in the user registration data from the template, checks to make sure it's all valid, saves to model.
        @param request: A HTTP request object.
        @returns: A redirect to the new user's dashboard if successful, a re-render of the form if not.
    """
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)

        if form.is_valid():
            full_name = form.cleaned_data['full_name']
            email = form.cleaned_data['email']
            zipcode = form.cleaned_data['zipcode']
            password = form.cleaned_data['password']
            password_confirmation = form.cleaned_data['password_confirmation']
            pick_up = form.cleaned_data['pick_up']

            if full_name.isspace():
                return render(request, 'registration/user_registration.html', {'form': form, 'email_not_unique': False, 'password': False, 'whitespace':True})

            if (password == password_confirmation):
                share_zone = ShareZone(request.POST['zipcode'])
                share_zone.save()

                user = User(full_name=full_name, email=email, password=password,
                            zipcode=zipcode, my_zone=share_zone, pick_up=pick_up)
                user.set_password(request.POST['password'])
            else:
                return render(request, 'registration/user_registration.html', {'form': form, 'email_not_unique': False, 'password': True, 'whitespace':False})
            
            try:
                user.save()
            except IntegrityError:
                return (render(request, 'registration/user_registration.html', {'form': form, 'email_not_unique': True, 'password': False,"whitespace": False}))

            """
            creates a community shed if one does not exists and sets up the relationship between the new user and shed
            if the community shed for that zipcode already exists then just add relationship for the new user
            """ 
            if not Sheds.objects.filter(shed_zipcode=zipcode, shed_type=1):
                community_shed = Sheds.objects.create(shed_name='Community'+ str(zipcode), shed_type=1, shed_zipcode=zipcode)
                community_shed.save()
                member = ShedMember.objects.create(user=user, shed=community_shed, member_type=4)
                member.save()
            else:
                community_shed = Sheds.objects.filter(shed_zipcode=zipcode, shed_type=1)[0]
                member = ShedMember.objects.create(user=user, shed=community_shed, member_type=5)
                member.save()

            #create a home shed and relationship for the new user
            home_shed = Sheds.objects.create(shed_zipcode=zipcode, shed_type=3, shed_name=user.email, shed_address=user.address)
            home_shed.save()
            membership = ShedMember.objects.create(user=user, shed=home_shed, member_type=4)
            membership.save()

            new_user = authenticate(email=email, password=password)
            login(request, new_user)

            return HttpResponseRedirect(reverse('home:get_started', args=()))
        else:
            #return HttpResponse(user_registration_form.errors) #Use this one to see where the form is failing validation.
            return(render(request, 'registration/user_registration.html', {'form': form, 'email_not_unique': False}))
    else:
        return render(request, 'home/index')
Exemplo n.º 43
0
class TestMembership(unittest.TestCase): 
    
    def setUp(self): 
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()
        
        self.user1 = User()
        self.user1.first_name = "Justin"
        self.user1.last_name = "Gray"
        self.user1.username = "******"
        self.user1.save()
        
        self.user2 = User()
        self.user2.first_name = "Sirius"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()
        
        m= Membership()
        m.user_prof = self.user1.get_profile()
        m.club = self.c
        m.num = 1
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()+datetime.timedelta(days=1)
        m.paid = True
        
        m.full_clean()
        m.save()
        
    def tearDown(self): 
        
        clear_db()
            
    def test_is_active_member(self):         
        self.assertTrue(self.c.is_active_member(self.user1))
        self.assertFalse(self.c.is_active_member(self.user2))
        
        m= Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.num = 2
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()
        
        m.full_clean()
        m.save()
        
        #make sure expired memberships don't report as active
        self.assertFalse(self.c.is_active_member(self.user2))
        
    
    def test_duplicate_id(self): 
        m= Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.num = 1
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()+datetime.timedelta(days=1)
        
        try: 
            m.full_clean()
            m.save()
        except ValidationError as err: 
            self.assertEqual(str(err),"{'__all__': [u'A member with that number already exists']}")
        else: 
            self.fail("ValidationError expected")
    
    def test_auto_increment_number(self): 
        m= Membership()
        m.user_prof = self.user2.get_profile()
        m.club = self.c
        m.start = datetime.date.today() - datetime.timedelta(days=300)
        m.valid_thru = datetime.date.today()
        
        m.full_clean()
        m.save()
        
        self.assertEqual(m.num,2)

    def test_is_member(self):
        up = self.user1.get_profile()

        self.assertTrue(up.is_member(self.c))
    def test_coupon_is_valid(self):

        user = User()
        user.first_name = "justin"
        user.last_name = "gray"
        user.username = "******"
        user.email = "*****@*****.**"
        user.save()

        user2 = User()
        user2.first_name = "sirius"
        user2.last_name = "gray"
        user2.username = "******"
        user2.save()

        club = Club()
        club.name = "test-test"
        club.save()

        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.save()

        o = Order()
        o.coupon = c
        o.user_prof = user.get_profile()
        o.save()

        self.assertTrue(c.is_valid(user))
        c.uses_left = 0
        self.assertTrue(c.is_valid(user))

        c.expires = datetime.date.today() - datetime.timedelta(days=1)
        self.assertTrue(c.is_valid(user))

        c.permanent = False
        self.assertFalse(c.is_valid(user))

        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.uses_left = 1
        self.assertTrue(c.is_valid(user))
        c.uses_left = 0
        self.assertFalse(c.is_valid(user))

        c.uses_left = 1
        c.user_prof = user.get_profile()
        self.assertFalse(c.is_valid(user2))

        c.user_prof = None
        c.single_use_per_user = True
        self.assertFalse(c.is_valid(user))
Exemplo n.º 45
0
    def handle(self, *args, **options):
        clear_db()

        
        s = Site.objects.all()[0]
        s.domain = "dev.racerslane.com" 
        s.name = "Racerslane.com" 
        s.save()

        print "Loading users"
        reader = csv.DictReader(open('old_data/driver.csv', 'rU'))
        for line in reader: 
            """user_name","email","verified","activation_code",
            "f_name","l_name","address","city","state",
            "zip_code","_password"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None   
                             
            u = User()
            u.username = line['user_name']
            u.email = line['email']
            u.password = "******"%line['_password']
            u.first_name = line['f_name']
            u.last_name = line['l_name']
            u.is_active = True
            u.save()
            
            up = u.get_profile()
            up.address = line['address']
            up.city = line['city']
            up.state = line['state']
            up.zip_code = line['zip_code']
            up.save()
            db.reset_queries()

            
        #dev to make it so I can login to any account    
        justin = User.objects.get(username="******")   
        password = justin.password
        
        #User.objects.all().update(password=password)

        print "Loading Cars"
        car_map = {}
        reader = csv.DictReader(open('old_data/car.csv', 'rb'))
        for line in reader:     
            """id","nickname","make","model","color","avatar_file_loc",
            "avatar_thumb_loc","year","owner_user_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            if line['owner_user_name']: 
                try: 
                    c = Car()
                    c.provisional = False
                    c.name = line['nickname']
                    c.make = line['make']
                    c.model = line['model']
                    if line['color']: 
                        c.color = line['color']
                    c.year = line['year']
                    c.user_profile = User.objects.get(username=line['owner_user_name']).get_profile()
                    s_car_id = (line['owner_user_name'], line['nickname'])
                    if exists('old_data/avatars/%s_%s_avatar'%s_car_id): 
                        c.avatar.save('%s_%s_avatar'%s_car_id, File(open('old_data/avatars/%s_%s_avatar'%s_car_id)))
                        c.thumb.save('%s_%s_thumb'%s_car_id, File(open('old_data/avatars/%s_%s_thumb'%s_car_id)))
                    c.save()
                    db.reset_queries()
                    car_map[line['id']] = c.pk
                except:
                    continue         
     
        print "Loading Clubs"
        #read in clubs
        club_map = {}
        for line in csv.DictReader(open('old_data/club.csv', 'rU')): 
            """"name","web_link","process_payments","points_calc_type",
            "membership_cost","renewal_cost","membership_terms","paypal_email",
            "index_point_method","address","city","state","zip_code","""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            c = Club()
            c.city = line['city']
            c.address = line['address']
            c.zip_code = line['zip_code']
            c.state = line['state']
            c.name = line['name']
            c.process_payments = line['process_payments']
            c.paypal_email = line['paypal_email']
            c.membership_terms = line['membership_terms']
            c.new_member_cost = line['membership_cost']
            c.renew_cost = line['renewal_cost']

            c.save()

            club_map[line['name']] = c
            db.reset_queries()  

        print "loading coupons"
        for line in csv.DictReader(open('old_data/coupon.csv')):    
            """coupon_code","club_name","discount_amount","uses_left","expires",
            "permanent","driver_user_name","registration_id"""    
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None
            
            c = Coupon()
            c.code = line['coupon_code']
            c.permanent = bool(line['permanent'])
            c.club = club_map[line['club_name']]
            c.uses_left = line['uses_left']
            c.discount_amount = line['discount_amount']
            if line['expires']: 
                c.expires = datetime.datetime.strptime(line['expires'], '%Y-%m-%d %H:%M:%S')
            if line['driver_user_name']:
                c.user_prof = User.objects.get(username=line['driver_user_name']).get_profile()
            c.save()    
            db.reset_queries()

        print "loading memberships"
        reader = csv.DictReader(open('old_data/membership.csv', 'rb'))
        for line in reader: 
            """"id","club_name","number","start_date","valid_thru_date",
            "price","paid","token","payer_id","transaction_id","anon_f_name",
            "anon_l_name","driver_user_name"""
            
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None 

            m = Membership()
            m.num = line['number']

            m.start = datetime.datetime.strptime(line['start_date'], '%Y-%m-%d %H:%M:%S')
            m.valid_thru = datetime.datetime.strptime(line['valid_thru_date'], '%Y-%m-%d %H:%M:%S')
            m.paid = bool(line['paid'])
            if line['price']!=None:
                m.price = float(line['price'])

            try: 
                m.user_prof = User.objects.get(username=line['driver_user_name']).get_profile()
            except User.DoesNotExist: 
                continue    
            m.club = club_map[line['club_name']]
            
            m._anon_f_name = line['anon_f_name']
            m._anon_l_name = line['anon_l_name']

            m.save()
            db.reset_queries()

        print "loading locations"
        location_map = {}    
        for line in csv.DictReader(open("old_data/location.csv")):    
            """id","name","address","lat","lng","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None                
            club = Club.objects.get(name=line['club_name'])        
            
            l = Location()
            l.name = line['name']
            l.address = line['address']
            #l.lat = line['lat']
            #l.lon = line['lng']
            l.club = club
            
            l.save()      
            
            location_map[line['id']] = l
            db.reset_queries()

        print "loading seasons"      
        season_map = {}    
        for line in csv.DictReader(open('old_data/season.csv')): 
            s = Season()
            """"id","year","active","club_name","drop_lowest_events"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            club = Club.objects.get(name=line['club_name'])
            s.club = club
            s.year = int(line['year'])
            s.drop_lowest_events = int(line['drop_lowest_events'])
            s.save()
                        
            season_map[line['id']] = s
            db.reset_queries()

        print "loading events"
        event_map = {}
        for line in csv.DictReader(open('old_data/event.csv', 'rU')):
            
            """id","name","note","date","registration_close","member_cost",
            "non_member_cost","pay_at_event_cost","location_id","club_name",
            "season_id","multiplier","count_points"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            
            e = Event()
            e.name = line['name']
            e.note = line['note']
            e.date = datetime.datetime.strptime(line['date'], '%Y-%m-%d %H:%M:%S')
            e.reg_close = line['registration_close']+"-05:00"
            e.member_price = float(line['member_cost'])
            e.non_member_price = float(line['non_member_cost'])
            e.non_pre_pay_penalty = float(line['pay_at_event_cost'])
            e.season = season_map[line['season_id']]
            e.club = e.season.club
            e.count_points = int(line['count_points'])
            e.multiplier = int(line['multiplier'])
            
            if line['location_id']:
                e.location = location_map[line['location_id']]
            
            e.save()
            
            event_map[line['id']] = e
            db.reset_queries()

        print "loading race_classes" 
        race_class_map = {}
        for line in csv.DictReader(open('old_data/raceclass.csv')):
            """id","pax","name","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            
            club = Club.objects.get(name=line['club_name'])                        
            r = RaceClass()
            r.name = line['name']
            r.abrv = line['name']
            r.pax = float(line['pax'])
            r.club = club
            r.save()
            db.reset_queries()
            
            race_class_map[line['id']] = r
            
        index_class = RaceClass()
        index_class.name = 'Index'
        index_class.bump_class = True
        index_class.abrv = "i"
        index_class.pax = 1.0
        index_class.club = club
        index_class.save()
        
        print "loading reg_types" 
        reg_type_map = {}    
        for line in csv.DictReader(open('old_data/regtype.csv')):
            """id","name","class_letters","reg_limit","index",
            "description","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            club = Club.objects.get(name=line['club_name']) 
            r = RaceClass()
            r.pax_class = True
            r.description = line['description']
            r.name = line['name']
            r.abrv = line['class_letters']
            if line['reg_limit']: 
                r.user_reg_limit=line['reg_limit']
            r.pax = 1.0
            r.club = club
            r.save()
            
            reg_type_map[line['id']] = r
            db.reset_queries()

        print "loading registrations" 
        registration_map = {}  
        for line in csv.DictReader(open('old_data/registration.csv')): 
            
            """id","number","paid","token","payer_id","transaction_id",
            "price","class_points","index_points","index_flag","anon_f_name",
            "anon_l_name","anon_car","driver_user_name","event_id","reg_type_id",
            "car_id","race_class_id"""
            
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
                
            if not line['event_id']: 
                continue            
            
            rc = race_class_map[line['race_class_id']]

            r = Registration()

            r.paid = bool(line['paid'])
            if line['price']!=None:
                r.price = float(line['price'])
            
            if line['driver_user_name']: 
                user = User.objects.get(username=line['driver_user_name'])
                r.user_profile = user.get_profile()
            r.number = int(line['number'])
            r.paid = int(line['paid'])
            r.index_points = line['index_points']
            r.class_points = line['class_points']
            if line['price']:
                r.price = float(line['price'])
            else: 
                r.price = 0.00
            r.index_points = int(line['index_points'])
            r.class_points = int(line['class_points'])
            if line['anon_car']: 
                r._anon_car=line['anon_car'].strip()
            if line['anon_l_name']: 
                r._anon_l_name=line['anon_l_name'].strip()
            if line['anon_f_name']: 
                r._anon_f_name=line['anon_f_name'].strip()
            r.race_class = rc
            r.event = event_map[line['event_id']]
            r.club = r.event.club
            try: 
                if line['reg_type_id']: 
                    r.pax_class=reg_type_map[line['reg_type_id']]
            except: 
                pass
            
            if line['index_flag']: 
                r.bump_class=index_class
            try: 
                if line['car_id']:
                    r.car=Car.objects.get(pk=car_map[line['car_id']])
            except: 
                pass
            #TODO race_class_id
            #TODO remove reg_detail class, and associate reg with UserProfile directly
            #TODO registrations can be siblings for joint update
            
            try: 
                r.save()
            except: 
                r.number += 100
                try: 
                    r.save()
                except: 
                    continue   

            registration_map[line['id']] = r.pk
            db.reset_queries()

        print "loading sessions"     
        session_map = {}
        for line in csv.DictReader(open('old_data/session.csv')):
            """id", "name", "event_id", "course_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None             
            
            try: 
                event_map[line['event_id']]
            except: 
                continue
            
            s = Session()
            s.name = line['name']
            s.event = event_map[line['event_id']]
            s.club = s.event.club
            s.save()
            
            session_map[line['id']] = s
            db.reset_queries()

        print "loading results"   
        result_map = {}    
        for line in csv.DictReader(open('old_data/result.csv')):        
            """id","registration_id","event_id","sess_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None                        
    
            try: 
                registration_map[line['registration_id']]
                session_map[line['sess_id']]
            except: 
                continue
            
            r = Result()
            reg = Registration.objects.get(pk=registration_map[line['registration_id']])
            r.reg = reg 

            r.session = session_map[line['sess_id']]
            r.club = r.session.club
            try: 
                r.save()
            except Exception as err: 
                print registration_map[line['registration_id']].pk
                print str(err)
                print registration_map[line['registration_id']]
            
            result_map[line['id']] = r.id
            db.reset_queries()

        print "loading runs" 
        for line in csv.DictReader(open('old_data/run.csv')):
            """id","base_time","calc_time","index_time","cones",
            "penalty","result_id","result_2_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None
                    
            if line['base_time'] == None: 
                continue
            try: 
                r = Run()
                r.base_time = float(line['base_time'])
                r.cones = int(line['cones'])
                if line['penalty']:
                    r.penalty = line['penalty']
                result = Result.objects.get(pk=result_map[line['result_id']])
                r.result = result
                r.club = r.result.club
                r.save()
                db.reset_queries()
            except KeyError: 
                continue

        print "calculating reg times"
        for reg in Registration.objects.select_related('results').all().iterator(): 
            reg.calc_times()


        #House keeping
        nora = Club.objects.get(safe_name='noraascc')
        user = User.objects.get(username="******")
        nora.group.user_set.add(user)