Beispiel #1
0
 def create(self, validated_data):
     """Create new user with encrypted password, personal organization and wallet of organization and returns user"""
     user = get_user_model().objects.create_user(**validated_data)
     wallet = Wallet(amount=0)
     wallet.save()
     org = Organization(name=user.name, wallet=wallet)
     org.save()
     org.users.set([user])
     return user
Beispiel #2
0
 def setUp(self):
     self.user = get_user_model().objects.create_user(
         '*****@*****.**',
         'Ime Korisnika',
         'password123'
     )
     self.organization = Organization(name="Org")
     self.organization.save()
     self.organization.users.add(self.user)
     self.client = APIClient()
     self.client.force_authenticate(self.user)
Beispiel #3
0
 def save(self, user):
     try:
         name = self.validated_data['name']
         wallet = None
         if self.validated_data['wallet']:
             wallet = Wallet(amount=0)
             wallet.save()
         org = Organization(name=name, wallet=wallet, information="Info")
         org.save()
         users = [get_user_model().objects.get(uuid=uuid) for uuid in self.validated_data['users_uuid']] \
             if 'users_uuid' in self.validated_data else [user]
         org.users.add(*users)
     except Exception as e:
         print(e)
Beispiel #4
0
class PrivateOrganizationApiTests(TestCase):
    """Tests authorized tasks endpoints"""

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            '*****@*****.**',
            'Ime Korisnika',
            'password123'
        )
        self.organization = Organization(name="Org")
        self.organization.save()
        self.organization.users.add(self.user)
        self.client = APIClient()
        self.client.force_authenticate(self.user)

    def test_create_task_on_authorized_user_successful(self):
        time_limit = datetime.datetime.now() + datetime.timedelta(hours=10)
        payload = {'name': "Test", 'description': "Ovo je neki desc", 'priority': "normal", 'time_limit': time_limit,
                   'organization_uuid': self.organization.uuid, 'status': "wait"}
        res = self.client.post(TASK_URL, payload)
        tasks = Task.objects.all()
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.user.uuid, tasks[0].users.all()[0].uuid)

    def test_create_task_on_requested_users_successful(self):
        time_limit = datetime.datetime.now() + datetime.timedelta(hours=10)
        user1 = get_user_model().objects.create_user(
            '*****@*****.**',
            'user1',
            'password123'
        )

        user2 = get_user_model().objects.create_user(
            '*****@*****.**',
            'user2',
            'password123'
        )

        users = [user1.uuid, user2.uuid]

        payload = {'name': "Test", 'description': "Ovo je neki desc", 'priority': "normal", 'time_limit': time_limit,
                   'organization_uuid': self.organization.uuid, 'status': "wait",
                   "users_uuid": users}
        res = self.client.post(TASK_URL, payload)
        tasks = Task.objects.all()
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        for u in tasks[0].users.all().order_by('name'):
            self.assertIn(u.uuid, users)
    def test_fetch_organizations(self):
        """Test fetching organizations"""
        org = Organization(name='tester')
        org.save()
        org.users.set([self.user])

        org1 = Organization(name='tester1')
        org1.save()
        org1.users.set([self.user])

        res = self.client.get(ORGANIZATION_URL)
        organizations = Organization.objects.all().order_by('name')
        serializer = OrganizationSerializer(organizations, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(dict(res.data)['results'], serializer.data)
Beispiel #6
0
    def form_valid(self, form):
        """
        Process the validated Event Organizer signup page
        """

        # Get the email address and see if they are in the database
        email = form.cleaned_data['email']

        # Get paypal info
        pay_pal = form.cleaned_data['pay_pal']

        # Check the passwords match
        password = form.cleaned_data['password']
        """
        pass_confirm = form.cleaned_data['pass_confirm']
        
        if password != self.password:
            if  password != pass_confirm:
                form._errors['password'] = ErrorList(["The passwords do not match"])
                return self.form_invalid(form)
        """
        # Make sure they agree
        if not form.cleaned_data['agree']:
            form._errors['agree'] = ErrorList(["Please check agreement"])
            return self.form_invalid(form)

        user = self.request.user

        # Is this a new account?
        if user.is_anonymous():

            # See if this is an exist account
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                username = email[0:30]
                user = User.objects.create_user(username=username,
                                                email=email,
                                                password=password)
                user.save()

                profile = Profile(user=user)
                profile.save()
            else:
                # This is an attendee who is now signing up.
                profile = user.get_profile()
                if profile.is_agreed:
                    if not user.check_password(password):
                        form._errors['email'] = ErrorList(
                            ["This email already exists"])
                        return self.form_invalid(form)

        # An existing user is changing their email address
        elif email != user.email:
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                user.email = email
            else:
                form._errors['email'] = ErrorList(
                    ["This email already exists"])
                return self.form_invalid(form)

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

        if password != self.password:
            user.set_password(password)

        user.save()

        profile = user.get_profile()
        profile.is_agreed = True
        profile.save()

        # See if the organization and chapter exist
        """ Take this out for now. One organizer, chapter per user 
        name = form.cleaned_data['chapter']
     
        try:
            organization = Organization.objects.get( name = name, organizer =  )
        except Organization.DoesNotExist:
            organization = Organization( name = name )
            organization.save()
        """

        # See if the chapter exists. If its blank its the same as the organization name
        name = form.cleaned_data['chapter']
        if name == '':

            # See if the user already has chapters
            chapters = Chapter.objects.for_user(user=user)

            # Take the first one now
            if len(chapters) >= 1:
                chapter = chapters[0]
            else:
                # If the used did not give a chapter and none exist
                form._errors['chapter'] = ErrorList(
                    ["Please provide a chapter name"])
                return self.form_invalid(form)
        else:
            try:
                chapter = Chapter.objects.get(name=name, organizer=user)

            except Chapter.DoesNotExist:

                # If this is the first time here create a chapter
                if not profile.is_organizer:
                    """ Temporarily one organizer per chapter """
                    organization = Organization(name=name)
                    organization.save()

                    chapter = Chapter(name=name,
                                      organizer=user,
                                      organization=organization,
                                      paypal=pay_pal)
                    chapter.save()

                    # Create an Eventbrite record for them
                    eventbrite = Eventbrite(chapter=chapter)
                    eventbrite.save()

                # Otherwise this is a rename
                else:
                    chapters = Chapter.objects.for_user(user)
                    chapter = chapters[0]

        chapter.name = name
        chapter.paypal = pay_pal
        chapter.save()

        # Login the new user
        user = auth.authenticate(username=user.username, password=password)
        if user is not None and user.is_active:
            auth.login(self.request, user)

        # If you had a profile
        if profile.is_organizer:
            return HttpResponseRedirect(reverse('or_dash') + "?state=profile")
        else:
            profile.is_organizer = True
            profile.save()
            return HttpResponseRedirect(
                reverse('or_invite') + '?chapter=' + str(chapter.id))
Beispiel #7
0
def spreadsheet(email, password):

    # Open Google Docs and get the spreadsheet
    spreadsheet = GoogleSpreadSheet(email, password)
    result = spreadsheet.getSpreadSheet(SPREADSHEET)
    if result == None or result.title.text != SPREADSHEET:
        print "Google Spreadsheet Error, Found: "  + result.title.text + \
              " Looking for: " + SPREADSHEET
        return None

    # Open the Organizers worksheet
    spreadsheet.getWorkSheet('Organization')
    organizations = spreadsheet.getCells()

    # Put all organizers in the database
    for organization in organizations:

        # Make sure all the necessary keys are present
        try:
            name = organization['Organization'].rstrip()
            chapter = organization['Chapter'].rstrip()
            email = organization['Organizer Email'].rstrip()
            organizer = organization['Chapter Organizer'].rstrip()
            user_key = organization['API User Key'].rstrip()
            org_id = organization['Organizer ID'].rstrip()

        except KeyError, error:
            print "Key Error:" + str(error)
            continue

        # Test this to make sure user_id and organizer_id are OK
        app_key = EVENTBRITE['APP_KEY']
        evb = EventbriteClient(tokens=app_key, user_key=user_key)

        try:
            events = evb.organizer_list_events({'id': org_id})
        except:
            print "Eventbrite ID Error:" + name +\
                  " user_id = " + str(user_key) +\
                  " organization_id = "+ str(org_id)

            ans = raw_input('Continue anyway (y/n)')
            if ans != 'y':
                pass
            else:
                continue

        else:
            # Check if you get an error from Eventbrite
            if 'error' in events:
                print 'Eventbrite Error: ' + events['error'][
                    'error_type'] + ' for ' + name + ' = ' + org_id
                ans = raw_input('Continue anyway (y/n)')
                if ans != 'y':
                    pass
                else:
                    continue

        # Get the organization or create one
        try:
            d_organization = Organization.objects.get(name=name)
            state = 'Exists:'
        except Organization.DoesNotExist:
            d_organization = Organization(name=name)
            d_organization.save()
            state = 'Create:'

        print state + \
              name      + ' ' +\
              chapter   + ' ' +\
              email     + ' ' +\
              organizer + ' ' +\
              user_key  + ' ' +\
              org_id

        # Get the organizer or create one
        try:
            user = User.objects.get(email=email)
            profile = user.get_profile()

        except User.DoesNotExist:

            # Create a temporary password and username which is 30 chars max
            first, last = organizer.split()
            password = first + '$' + last
            username = email[0:30]
            user = User.objects.create_user(username=username,
                                            email=email,
                                            password=password)
            user.first_name = first.capitalize()
            user.last_name = last.capitalize()
            user.save()
            profile = Profile(user=user)
            profile.is_organizer = True
            profile.save()

        # Get the chapter or create one
        try:
            d_chapter = Chapter.objects.get(name=chapter)
            d_chapter.organizer = user

        except Chapter.DoesNotExist:
            d_chapter = Chapter(name=chapter,
                                organization=d_organization,
                                organizer=user)
        d_chapter.save()

        # Get a list of the current sponsors
        buyer_list = d_chapter.buyers()

        # Get the eventbrite access
        try:
            ticket = Eventbrite.objects.get(user_key=user_key,
                                            organizer_id=org_id)
        except Eventbrite.DoesNotExist:
            ticket = Eventbrite(user_key=user_key, organizer_id=org_id)

        # Set the current chapter
        ticket.chapter = d_chapter
        ticket.save()

        # Get all the sponsers for the current chapter
        result = spreadsheet.getWorkSheet(chapter)

        # Check to make sure there is a corresponding worksheet with sponsors
        if result == None:
            print 'No Work Sheet for: ' + chapter
            continue

        sponsers = spreadsheet.getCells()
        for sponser in sponsers:

            # Check to make sure all fields exist
            try:
                email = sponser['Sponsor Email'].rstrip()
                first = sponser['Sponsor First Name'].rstrip()
                last = sponser['Sponsor Last Name'].rstrip()
            except KeyError, error:
                print "Key Error:" + str(error)
                continue

            if 'Sponsor Company' in sponser:
                company = sponser['Sponsor Company'].rstrip()
            else:
                company = None
            if 'Sponsor Title' in sponser:
                title = sponser['Sponsor Title'].rstrip()
            else:
                title = None
            if 'Sponsor Website' in sponser:
                website = sponser['Sponsor Website'].rstrip()
            else:
                website = None
            if 'Sponsor Phone' in sponser:
                phone = sponser['Sponsor Phone'].rstrip()
            else:
                phone = None

            if 'Sponsor LinkedIn' in sponser:
                linkedin = sponser['Sponsor LinkedIn'].rstrip()
            else:
                linkedin = None

            if 'Sponsor Twitter' in sponser:
                twitter = sponser['Sponsor Twitter'].rstrip()
            else:
                twitter = None

            if 'Sponsor Deal' in sponser:
                deal_term = sponser['Sponsor Deal'].rstrip()
            else:
                deal_term = 'cancel: ,20'

            # Get or create the user
            try:
                user = User.objects.get(email=email)
                profile = user.get_profile()

            except User.DoesNotExist:
                password = first + '$' + last,
                username = email[0:30]
                user = User.objects.create_user(username=username,
                                                email=email,
                                                password=password)
                user.first_name = first.capitalize()
                user.last_name = last.capitalize()
                user.save()
                profile = Profile(user=user)
                profile.save()

            profile.company = company
            profile.title = title
            profile.website = website
            profile.phone = phone
            profile.linkedin = linkedin
            profile.twitter = twitter

            profile.is_leadbuyer = True
            profile.save()

            # Get or create a lead buyer for this user
            try:
                lb = LeadBuyer.objects.get(user=user)
            except LeadBuyer.DoesNotExist:
                lb = LeadBuyer(user=user)
                lb.save()

            # Any key that does not start with Sponsor is an interest key = ( key, value )
            for key in sponser.iteritems():

                # Check optional sponsor details
                if 'Sponsor' in key[0]:
                    continue

                # Get or create an interest, make sure their is an 'x' in the box
                if key[1] != 'x':
                    continue

                # Get the interest
                key = key[0].lstrip().rstrip()
                try:
                    interest = Interest.objects.get(interest=key)
                except Interest.DoesNotExist:
                    interest = Interest(interest=key)
                    interest.save()

                # Get or create a deal
                try:
                    deal = Deal.objects.get(chapter=d_chapter,
                                            interest=interest)
                except Deal.DoesNotExist:
                    deal = Deal(
                        chapter=d_chapter,
                        interest=interest,
                    )
                    deal.save()

                # Get or create a term
                term_type, cost = deal_term.split(',')
                term_type = term_type.split(':')

                # See if this term exists
                try:
                    term = Term.objects.get(deal=deal,
                                            buyer=user,
                                            status='approved')

                # If not create it
                except Term.DoesNotExist:
                    term = new_term(deal, user, term_type, cost)

                # Otherwise update the existing term
                else:
                    term = update_term(term, term_type, cost)

                    # Take them out of the buyer list
                    if user in buyer_list:
                        buyer_list.remove(user)

                # In order to get child object, you have to query the db
                term = Term.objects.get(deal=deal,
                                        buyer=user,
                                        status='approved')
                cterm = term.get_child()
                if isinstance(cterm, Budget):
                    lb.budget = cterm.remaining
                    lb.save()

                print 'Deal: %-35s Buyer: %-40s %s:%s,%s'%\
                      ( deal.interest.interest,
                        user.email,
                        term_type[0],
                        term_type[1],
                        cost )
 def type_name(self, request):
     return Response(Organization.get_type_name())