Ejemplo n.º 1
0
    def setUp(self):
        # create an organisation
        user = User(username='******')
        user.save()
        org = Organisation(name='test_org')
        org.user = user
        org.save()

        # create three questions
        self.q1 = Question(question='What is your name?', organisation=org)
        self.q1.save()

        # create a candidate
        self.candidate = Candidate(name='Terry',
                                   participating=True,
                                   popit_id=1234)
        self.candidate.save()
        # post-save hook on candidate will automatically assign q1

        q2 = Question(question='What is your quest?', organisation=org)
        q2.save()
        q3 = Question(question='What is your favourite colour?',
                      organisation=org)
        q3.save()

        # assign 1 question to the candidate
        self.answer = Answer.objects.get(question=self.q1,
                                         candidate=self.candidate)
Ejemplo n.º 2
0
    def test_should_return_identities_for_an_environment(self):
        client = self.set_up()

        # Given
        identifierOne = 'user1'
        identifierTwo = 'user2'
        organisation = Organisation(name='ssg')
        organisation.save()
        project = Project(name='project1', organisation=organisation)
        project.save()
        environment = Environment(name='environment1', project=project)
        environment.save()
        identityOne = Identity(identifier=identifierOne,
                               environment=environment)
        identityOne.save()
        identityTwo = Identity(identifier=identifierTwo,
                               environment=environment)
        identityTwo.save()
        # When
        response = client.get('/api/v1/environments/%s/identities/' %
                              environment.api_key)
        # Then
        self.assertEquals(response.data['results'][0]['identifier'],
                          identifierOne)
        self.assertEquals(response.data['results'][1]['identifier'],
                          identifierTwo)
Ejemplo n.º 3
0
    def with_organisation(self, organisation):
        valid_election_types = organisation.election_types.all()
        if self.election_type not in valid_election_types:
            raise Organisation.ValidationError(
                "'%s' is not a valid organisation for election type '%s'" %\
                (organisation, self.election_type)
            )

        if organisation.start_date and organisation.start_date > self.date:
            raise Organisation.ValidationError(
                'Organisation start date after election date')
        if organisation.end_date and organisation.end_date < self.date:
            raise Organisation.ValidationError(
                'Organisation end date before election date')

        # if this is a top-level group id
        # we associate the election object with an organisation
        # but the organisation doesn't form part of the id
        if organisation.organisation_type == self.election_type.election_type:
            self._use_org = False
            self.organisation = Organisation.objects.get(
                organisation_type=self.election_type.election_type)
        else:
            self._use_org = True
            self.id = self.id.with_organisation(organisation.slug)
            self.organisation = organisation
        return self
Ejemplo n.º 4
0
 def test_model_creation(self):
     """
     More of a smoke test for the model creation
     """
     o = Organisation(name="test")
     o.save()
     self.assertTrue(bool(o.created))
     self.assertEqual(o.name, "test")
     self.assertTrue(o.auth_token)
Ejemplo n.º 5
0
 def generate_database_models(identifier='user1'):
     organisation = Organisation(name='ssg')
     organisation.save()
     project = Project(name='project1', organisation=organisation)
     project.save()
     environment = Environment(name='environment1', project=project)
     environment.save()
     feature = Feature(name="feature1", project=project)
     feature.save()
     identity = Identity(identifier=identifier, environment=environment)
     identity.save()
     return identity, project
Ejemplo n.º 6
0
    def test_should_create_a_project(self):
        client = self.set_up()

        # Given
        organisation = Organisation(name='ssg')
        organisation.save()
        project_name = 'project1'
        project_template = '{ "name" : "%s", "organisation" : "%s" }'
        # When
        client.post('/api/v1/projects/',
                    data=project_template % (project_name, organisation.id),
                    content_type='application/json')
        project = Project.objects.filter(name=project_name)
        # Then
        self.assertEquals(project.count(), 1)
Ejemplo n.º 7
0
def add_organisation():
    form = OrganisationForm()

    if request.method == "POST" and form.validate():
        organisation = Organisation(code=form.code.data,
                                    name=form.name.data,
                                    description=form.description.data,
                                    is_active=form.is_active.data)
        db.session.add(organisation)
        db.session.flush()

        if organisation:
            org_id = organisation.id
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(form.password.data, salt)
            admin = User(firstname=form.firstname.data,
                         lastname=form.lastname.data,
                         email=form.email.data,
                         username=form.username.data,
                         password=hashed_password,
                         organisation=organisation,
                         is_admin=True)
            print(org_id)
            db.session.add(admin)
            db.session.flush()
            db.session.commit()
            return redirect(url_for('view_organisations'))

    return render_template('organisations/organisationform.html',
                           form=form,
                           action='new')
Ejemplo n.º 8
0
 def create_ffadminuser():
     Helper.clean_up()
     organisation = Organisation(name='test org')
     organisation.save()
     project = Project(name="test project", organisation=organisation)
     project.save()
     environment = Environment(name="test env", project=project)
     environment.save()
     user = FFAdminUser(username="******",
                        email="*****@*****.**",
                        first_name="test",
                        last_name="user")
     user.set_password("testuser123")
     user.save()
     user.organisations.add(organisation)
     user.save()
     return user
Ejemplo n.º 9
0
def update_organisation_tiers():
    organisations = Organisation.scan()
    tiers = ['tier_one', 'tier_two', 'tier_three']

    for organisation in organisations:
        conn.put_item('django-dynamo-example',
                      organisation.pk,
                      organisation.sk,
                      attributes=dict(tier=random.choice(tiers)))
Ejemplo n.º 10
0
    def setUp(self):
        user = User(username='******')
        user.save()
        o1 = Organisation(name='Organisation 1')
        o1.user = user
        o1.save()

        user = User(username='******')
        user.save()
        o2 = Organisation(name='Organisation 2')
        o2.user = user
        o2.save()

        c1 = Candidate(popit_id=1235,
                       name='Bob',
                       contact_address='*****@*****.**',
                       participating=True)
        c1.save()
        self.candidate = c1

        q1 = Question(
            organisation=o1,
            question='What is your name?',
            type='text',
        )
        q1.save()
        q2 = Question(
            organisation=o2,
            question='What is your quest?',
            type='text',
        )
        q2.save()

        a1 = Answer(candidate=c1,
                    question=q1,
                    completed=True,
                    completed_timestamp=datetime.datetime(
                        2015, 1, 1, tzinfo=timezone.get_current_timezone()))
        a1.save()
        self.a1 = a1

        a2 = Answer(candidate=c1, question=q2, completed=False)
        a2.save()
        self.a2 = a2
Ejemplo n.º 11
0
    def test_join_organisation(self):
        # Given
        client = self.set_up()
        organisation_2 = Organisation(name="test org 2")
        organisation_2.save()
        invite = Invite(email="*****@*****.**",
                        organisation=organisation_2)
        invite.save()
        user = FFAdminUser.objects.get(email="*****@*****.**")
        token = Token(user=user)
        token.save()

        # When
        response = client.post("/api/v1/users/join/" + invite.hash + "/",
                               HTTP_AUTHORIZATION="Token " + token.key)
        user.refresh_from_db()

        # Then
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(user.organisations.all().count(), 2)
Ejemplo n.º 12
0
    def test_registration_and_login(self):
        Helper.generate_database_models()
        # When
        register_response = self.client.post(
            self.auth_base_url + "register/",
            data=self.register_template %
            ("*****@*****.**", "john", "doe", "johndoe123", "johndoe123"),
            content_type='application/json')

        # Then
        self.assertEquals(register_response.status_code,
                          status.HTTP_201_CREATED)
        self.assertIn("key", register_response.content)
        # Check user was created
        self.assertEquals(
            FFAdminUser.objects.filter(email="*****@*****.**").count(), 1)
        user = FFAdminUser.objects.get(email="*****@*****.**")
        organisation = Organisation(name="test org")
        organisation.save()
        user.organisation = organisation
        user.save()
        # Check user can login
        login_response = self.client.post(
            self.auth_base_url + "login/",
            data=self.login_template % ("*****@*****.**", "johndoe123"),
            content_type='application/json')
        self.assertEquals(login_response.status_code, status.HTTP_200_OK)
        self.assertIn("key", login_response.content)

        # verify key works on authenticated endpoint
        content = json.loads(login_response.content)
        organisations_response = self.client.get("/api/v1/organisations/",
                                                 HTTP_AUTHORIZATION="Token " +
                                                 content['key'])
        self.assertEquals(organisations_response.status_code,
                          status.HTTP_200_OK)

        Helper.clean_up()
Ejemplo n.º 13
0
    def create_organisation(self, name='Die Hard', status=None):
        """
        Helper to create Organisation instance.

        Args:
            name (str): Organisation name
            status (int): OrganisationStatus value
        """
        params = {'name': name}
        if status:
            # default status is ENABLED
            params['status'] = status

        return Organisation.create(db_session=self.db_session, **params)
Ejemplo n.º 14
0
def generate_projects():
    organisations = [org for org in Organisation.query('ORG', limit=4)]
    project_types = ['freelance', 'contract', 'full_time']
    project_status = ['pending', 'in_progress', 'on_hold', 'complete']
    for _ in range(40):
        print("Generating a project")
        organisation = random.choice(organisations)
        serializer = ProjectSerializer(
            data=dict(organisation_id=organisation.model_id,
                      name=fake.word(),
                      project_type=random.choice(project_types),
                      status=random.choice(project_status)))

        if serializer.is_valid():
            serializer.save()
Ejemplo n.º 15
0
def add_organisation():
    form = OrganisationForm()

    if request.method == "POST" and form.validate():
        organisation = Organisation(
            code=form.code.data,
            name=form.name.data,
            description=form.description.data,
            #admin = form.admin.data,
            is_active=form.is_active.data)
        db.session.add(organisation)
        db.session.commit()
        return redirect(url_for('view_organisations'))

    return render_template('organisations/organisationform.html',
                           form=form,
                           action='new')
Ejemplo n.º 16
0
    def on_delete(self, req, resp, object_id):
        """
        Delete Object instance

        Args:
            req (falcon.request.Request): Request object
            resp (falcon.response.Response): Response object
            object_id: (int): Object instance ID

        Raises::
            (HTTPNotFound): Organisation instance does not exist
        """
        instance = req.context['instance']

        users_no = len(instance.users)
        if users_no > 0:
            raise falcon.HTTPConflict(
                f'This Organisation is assign to {users_no} airport(s). Remove users before delete!'
            )

        response = Organisation.delete_by_id(req.context['db_session'], object_id)
        resp.status = falcon.HTTP_204 if response else falcon.HTTP_404
Ejemplo n.º 17
0
def generate_project_employees():
    organisation = Organisation.get(
        "ORG", range_key="ORG#65a7b51dee5049565f65dc6839aa423d")
    projects = [
        project for project in Project.query(organisation.sk,
                                             Project.sk.startswith('PRO'))
    ]

    employees = [
        employee for employee in Employee.query(organisation.sk,
                                                Employee.sk.startswith('EMP'))
    ]

    for employee in employees:
        project = projects[0]
        serializer = ProjectEmployeeSerializer(
            data=dict(organisation_id=organisation.model_id,
                      employee_id=employee.model_id,
                      project_id=project.model_id))

        if serializer.is_valid():
            serializer.save()

        else:
            print(serializer.errors)

    for project in projects:
        employee = employees[0]
        serializer = ProjectEmployeeSerializer(
            data=dict(organisation_id=organisation.model_id,
                      employee_id=employee.model_id,
                      project_id=project.model_id))

        if serializer.is_valid():
            serializer.save()

        else:
            print(serializer.errors)
Ejemplo n.º 18
0
def generate_employees():
    organisations = [org for org in Organisation.query('ORG', limit=4)]

    for _ in range(20):
        print("Generating Employee")
        organisation = random.choice(organisations)

        days = [_ for _ in range(1, 29)]
        months = [_ for _ in range(1, 13)]
        years = [_ for _ in range(1993, 2001)]
        serializer = EmployeeSerializer(
            data=dict(organisation_id=organisation.model_id,
                      name=f"{fake.first_name()} {fake.last_name()}",
                      email=fake.email(),
                      date_of_birth=timezone.datetime(
                          year=random.choice(years),
                          month=random.choice(months),
                          day=random.choice(days)).strftime('%Y-%m-%d')))

        if serializer.is_valid():
            serializer.save()

        else:
            print(serializer.errors)
Ejemplo n.º 19
0
def make_organisation(auth_token, name="test"):
    o = Organisation(name=name, auth_token=auth_token)
    o.save()
Ejemplo n.º 20
0
def org_new(request):
	error = None
	args = {}
	if isUserLogged(request):
		usr_details = request.session['usr_details']
		if request.POST:
			formOrg = CYMOrganisationCreationForm(request.POST)
			formAddress = AddressForm(request.POST)
			if formOrg.is_valid() & formAddress.is_valid():

				address = Address()
				organisation = Organisation()
				settings = OrgSettings()
				address.address_line1 = formAddress.cleaned_data['address_line1']
				address.address_line2 = formAddress.cleaned_data['address_line2']
				address.address_city = formAddress.cleaned_data['address_city']
				address.address_state = formAddress.cleaned_data['address_state']
				pin = formAddress.cleaned_data['address_pincode']
				address.address_pincode = pin
				address.address_status = True

				organisation.org_name = formOrg.cleaned_data['org_name']
				organisation.org_brand = formOrg.cleaned_data['org_brand']
				organisation.org_phone = formOrg.cleaned_data['org_phone']
				organisation.org_active = formOrg.cleaned_data['org_active']
				organisation.org_emailid = formOrg.cleaned_data['org_emailid']
				settings.orgsettings_status = formOrg.cleaned_data['org_active']
				try:
					with transaction.atomic():
						address.save()
						settings.save()
						organisation.org_address = address
						organisation.org_settings = settings
						organisation.save()
						organisation.org_billing_id = organisation.org_id
						identifier = str(organisation.org_id) + '_' + organisation.org_brand
						organisation.org_identifier = identifier.replace(" ", "")
						organisation.save()
						success = createSuperUserAndGroup(organisation.org_emailid,organisation.org_phone,organisation,'Super Admin',organisation.org_identifier)
						if success:
							print 'Super User Created'
						else:
							print 'Error while creating super user'
						send_mail_to_org_admin(organisation)
					args['usr_details'] = usr_details
					args['new_org_added'] = organisation.org_name
					args['new_org_id'] = organisation.org_id
					return render_to_response('org_dashboard.html',args)
				except IntegrityError:
					traceback.print_exc()
					error = 'Error creating new organisation'
			else:
				error = 'Error creating new organisation. Invalid form!'
		else:
			formOrg = CYMOrganisationCreationForm()
			formAddress = AddressForm()
		args.update(csrf(request))
		args['formOrg'] = formOrg
		args['formAddress'] = formAddress
		args['usr_details'] = usr_details
		args['error'] = error
		return render_to_response('org_new.html',args)
	else:
		return userSessionExpired()
Ejemplo n.º 21
0
                         'content': l_company.organisation.content,
                         'street': l_company.organisation.street,
                         'suburb': l_company.organisation.suburb,
                         'city': l_company.organisation.city,
                         'country': l_company.organisation.country,
                         'state': l_company.organisation.state,
                         'post_code': l_company.organisation.post_code,
                         'phone': l_company.organisation.phone,
                         'fax': l_company.organisation.fax,
                         'mobile': l_company.organisation.mobile,
                         'email': l_company.organisation.email,
                         'website': l_company.organisation.website,
                         'website_name': l_company.organisation.website_name,
                     }
                 
                     organisation = Organisation(**o_kwargs)
 
                     try:
                         organisation.full_clean()
                     except ValidationError, e:
                         # Do something based on the errors contained in e.message_dict.
                         # Display them to a user, or handle them programatically.
                         print e
                     else:
                         # pass
                         # organisation.save()
                         if organisation.save():
                             organisation.organisation_type = l_org_types
                         print u'=== === === saving %s' % organisation
                 else:
                     
Ejemplo n.º 22
0
    def handle(self, *args, **options):
        """
        Projects
        """
        
        articles_to_link = []
        projects_to_link = []
        unlinked_projects = []
        
        publisher = Publisher.objects.get(pk=1)
        user = User.objects.get(pk=1)
        
        l_projects = ProjectsProject.objects.all()        
    
        for l_project in l_projects:
            
            # Get related data
            sites = Site.objects.filter(pk=1)
            
            ProjectsProjectProjectCategories
            categories = ProjectsProjectcategory.objects.filter(projectsprojectprojectcategories__project_id=l_project.id)
            types = ProjectsProjecttype.objects.filter(projectsprojectprojecttypes__project_id=l_project.id)
            
            try:
                status = ProjectsProjectstatus.objects.get(projectsproject__id=l_project.id)
            except:
                status = None
            
            # print u''
            #             print u'===================================='
            #             print u''
            print u'%s' % l_project.title
            # print u''
            #             print u'::: Categories: %s ::: Types: %s ::: Status: %s' % (categories.values_list(flat=True), types.values_list(flat=True), status)
            
            
            # ============================
            # List & Create new records
            
            #### Organisations
            
            
            
            #### Projects
            
            p_kwargs = {
                'title': l_project.title,
                'building_area': l_project.building_area,
                'budget_total': l_project.budget_total,
                'city': l_project.city,
                'client': l_project.client,
                'client_website': l_project.client_website,
                'client_website_name': l_project.client_website_name,
                'construction': l_project.construction,
                'content': l_project.content,
                'country': l_project.country,
                'created': datetime.datetime.now(),
                'created_by': user,
                'design_documentation': l_project.design_documentation,
                'old_id': l_project.id,
                'is_published': True,
                'number_of_stories': l_project.number_of_stories,
                'post_code': l_project.post_code,
                'project_website': l_project.client_website,
                'published': datetime.datetime.now(),
                'published_by': user,
                'publisher': publisher,
                'short_title': l_project.title,
                'site_size': l_project.site_size,
                'slug': SlugifyUniquely(truncate_words(l_project.title, 4), Project),
                'state': l_project.state,
                'street': l_project.street,
                'suburb': l_project.suburb,
                'summary': l_project.summary
            }
            project = Project(**p_kwargs)
            
            if status:
                try:
                    project.project_status = ProjectStatus.objects.get(pk=1)
                except:
                    pass
                
            try:
                project = Project.objects.get(title=project.title)
            except ObjectDoesNotExist:
                # Create new
                try:
                    project.full_clean()
                    # pass
                except ValidationError, e:
                    # Do something based on the errors contained in e.message_dict.
                    # Display them to a user, or handle them programatically.
                    print e
                else:
                    # Save new
                    # project.save()
                    # if project.save():
                    # project.organisation_type = l_org_types
                    project.save()
                    print u'=== === === saving project %s' % project
            else:
                # Once saved, add related items == 
                print u'=== === === project exists %s' % project
                # Clean up or add
            
                # Products
                l_p_products = ProjectsProjectproduct.objects.filter(project=l_project)
                for l_p_product in l_p_products:
                    print u'--- --- %s :: %s' % (l_p_product.label, l_p_product.products)
                    pp_kwargs = {
                        'project': project,
                        'label': l_p_product.label,
                        'products': l_p_product.products
                    }
                    project_product = ProjectProduct(**pp_kwargs)
                    try:
                        project_product.full_clean()
                        # pass
                    except ValidationError, e:
                        # Do something based on the errors contained in e.message_dict.
                        # Display them to a user, or handle them programatically.
                        print e
                    else:
                        try:
                            pp = ProjectProduct.objects.get(label=l_p_product.label, project=l_project)
                        except MultipleObjectsReturned:
                            pps = ProjectProduct.objects.filter(label=l_p_product.label, project=l_project)[2:]
                            ipdb.set_trace()
                            for pp in pps:
                                pp.delete()
                                print u'=== === === deleting products :: %s' % pp
                        except ObjectDoesNotExist:
                            project_product.save()
                            print u'=== === === saving new products :: %s' % project_product
                        else:
                            print u'=== === === products already exists :: %s' % project_product

                        
                
                ##### Project Roles
                
                # Individuals
                l_p_individuals = ProjectsProjectindividual.objects.filter(project=l_project)
                # l_p_individuals = [] # prevents from processing
                for l_p_individual in l_p_individuals:
                    
                    try:
                        organisation = Organisation.objects.get(title=l_p_individual.organisation.title)
                    except ObjectDoesNotExist:
                        """
                        Does not exist, so create new.
                        """
                        o_kwargs = {
                            'title': l_p_individual.organisation.title,
                            'content': l_p_individual.organisation.content,
                            'street': l_p_individual.organisation.street,
                            'suburb': l_p_individual.organisation.suburb,
                            'city': l_p_individual.organisation.city,
                            'country': l_p_individual.organisation.country,
                            'state': l_p_individual.organisation.state,
                            'post_code': l_p_individual.organisation.post_code,
                            'phone': l_p_individual.organisation.phone,
                            'fax': l_p_individual.organisation.fax,
                            'mobile': l_p_individual.organisation.mobile,
                            'email': l_p_individual.organisation.email,
                            'website': l_p_individual.organisation.website,
                            'website_name': l_p_individual.organisation.website_name,
                        }
                    
                        organisation = Organisation(**o_kwargs)
                        print u'=== === saving %s' % organisation
                        try:
                            organisation.full_clean()
                        except ValidationError, e:
                            # Do something based on the errors contained in e.message_dict.
                            # Display them to a user, or handle them programatically.
                            print e
                        else:
                            organisation.save()
                            print u'=== === === saving %s' % organisation
                    
                    p_individual = {
                        'project': project,
                        # 'role': role_type,
                        # 'individual': None,
                        'credit': l_p_individual.credit,
                        'custom_credit': l_p_individual.role,
                        'organisation': organisation,
                    }
                    project_individual = ProjectIndividual(**p_individual)
                    try:
                        project_individual.full_clean()
                    except ValidationError, e:
                        # Do something based on the errors contained in e.message_dict.
                        # Display them to a user, or handle them programatically.
                        print e