Esempio n. 1
0
def add_company():
    form = CompanyForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            company = Company(
                company_name=form.company_name.data,
                company_address=form.company_address.data,
                company_city=form.company_city.data,
                company_state=form.company_state.data,
                company_zipcode=form.company_zipcode.data,
                company_website=form.company_website.data,
                company_phone_number=form.company_phone_number.data,
                company_email=form.company_email.data,
                author=current_user)
        else:
            company = Company(
                company_name=form.company_name.data,
                company_address=form.company_address.data,
                company_city=form.company_city.data,
                company_state=form.company_state.data,
                company_zipcode=form.company_zipcode.data,
                company_website=form.company_website.data,
                company_phone_number=form.company_phone_number.data,
                company_email=form.company_email.data)
        db.session.add(company)
        db.session.commit()

        flash('Thank you, the company has been added!')
        return redirect(url_for('index'))
    return render_template('report.html', title='Report', form2=form)
    def test_company_membership(self):
        # create companies
        c1 = Company(company_name='test', email='*****@*****.**')
        c2 = Company(company_name='test2', email='*****@*****.**')

        # create employees with memberships
        e1 = Employee(email='*****@*****.**',
                      first_name='thomas',
                      last_name='mcdonnell',
                      is_admin=True,
                      member_of=c1)
        e2 = Employee(email='*****@*****.**',
                      first_name='tom',
                      last_name='jones',
                      member_of=c2)

        # commit to database
        db.session.add(c1)
        db.session.add(c2)
        db.session.add(e1)
        db.session.add(e2)
        db.session.commit()

        # test memberships
        self.assertEqual(c1.employees.count(), 1)
        self.assertEqual(c2.employees.count(), 1)

        # test memberships
        self.assertEqual(c1.employees.all(), [e1])
        self.assertNotEqual(c1.employees.all(), [e2])
        self.assertEqual(c2.employees.all(), [e2])
        self.assertNotEqual(c2.employees.all(), [e1])
Esempio n. 3
0
 def test_boiler_user_access(self):
     c1 = Company(company_name="Company1")
     c2 = Company(company_name="Company2")
     db.session.add(c1)
     db.session.add(c2)
     b1 = Boiler(boiler_name="Boiler1", company=c1)
     b2 = Boiler(boiler_name="Boiler2", company=c2)
     b3 = Boiler(boiler_name="Boiler3", company=c2)
     db.session.add(b1)
     db.session.add(b2)
     db.session.add(b3)
     db.session.commit()
     r = Role.query.filter_by(name='Repr').first()
     u1 = User(email='*****@*****.**',
               password='******',
               role=r,
               company=c1)
     u2 = User(email='*****@*****.**',
               password='******',
               role=r,
               company=c2)
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     self.assertTrue(u1.boiler_access(b1.id))
     self.assertFalse(u1.boiler_access(b2.id))
     self.assertFalse(u1.boiler_access(b3.id))
     self.assertFalse(u2.boiler_access(b1.id))
     self.assertTrue(u2.boiler_access(b2.id))
     self.assertTrue(u2.boiler_access(b3.id))
Esempio n. 4
0
    def test_post_filter(self):
        # create company
        c1 = Company(id=1,
                     company_name='Paint pods',
                     company_address='Boise',
                     company_zipcode='83706',
                     company_website='Paintteam.com',
                     company_phone_number='20867832',
                     company_email='*****@*****.**')
        c2 = Company(id=2,
                     company_name='Bob Team',
                     company_address='Salt Lake City',
                     company_zipcode='81504',
                     company_website='Paintteam.com',
                     company_phone_number='2086783456',
                     company_email='*****@*****.**')
        db.session.add(c1)
        db.session.add(c2)
        db.session.commit()

        # create four users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        # create services
        s1 = Service(parent_id=1, title='plumbing')
        s2 = Service(parent_id=2, title='electrical')
        db.session.add(s1)
        db.session.add(s2)
        db.session.commit()

        # create four posts
        now = datetime.utcnow()
        p1 = Post(body="post from john",
                  timestamp=now + timedelta(seconds=1),
                  service_id=1,
                  company_id=1)
        p2 = Post(body="post from john",
                  timestamp=now + timedelta(seconds=1),
                  service_id=1,
                  company_id=1)
        p3 = Post(body="Test post",
                  timestamp=now + timedelta(seconds=1),
                  service_id=2,
                  company_id=2)
        p4 = Post(body="test post",
                  timestamp=now + timedelta(seconds=1),
                  service_id=2,
                  company_id=2)
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        # check service_posts function
        check1 = u1.filter_posts(1, "Boise", "None", "None")

        # check that the correct posts are returned
        self.assertEqual(check1.count(), 2)
Esempio n. 5
0
def seed_companies():

    c1 = Company(userId_fk=10, companyName='Company 1')
    c2 = Company(userId_fk=11, companyName='Company 2')

    db.session.add(c1)
    db.session.add(c2)

    db.session.commit()
Esempio n. 6
0
 def test_company_admin_access(self):
     c1 = Company(company_name="Company1")
     c2 = Company(company_name="Company2")
     r = Role.query.filter_by(name='Administrator').first()
     u1 = User(email='*****@*****.**',
               password='******',
               role=r,
               company=c2)
     self.assertTrue(u1.company_access(c1.id))
     self.assertTrue(u1.company_access(c2.id))
Esempio n. 7
0
 def test_company_inspector_access(self):
     c1 = Company(company_name="Company1")
     c2 = Company(company_name="Company2")
     r = Role.query.filter_by(name='Inspector').first()
     u1 = User(email='*****@*****.**',
               password='******',
               role=r,
               company=c1)
     self.assertTrue(u1.company_access(c1.id))
     self.assertTrue(u1.company_access(c2.id))
Esempio n. 8
0
 def create_company(self):
     Company.query.delete()
     company = Company(name='abc',
                       transaction_date=datetime(2020, 12, 1),
                       per_share_deal_price=55.55)
     db.session.add(company)
     db.session.commit()
Esempio n. 9
0
    def test_can_retrieve_a_company_with_founders(self):
        demo = Company(
            name=data1['name'],
            website=data1['website'],
            bio=data1['bio'],
        )
        demo.save()

        # Add founders into the database
        # with reference to the newly created company
        company_id = Company.query.first().id

        auth_token = self.get_auth_token(staff=True)

        for founder in data1['founders']:
            Founder(company_id=company_id,
                    name=founder['name'],
                    email=founder['email'],
                    role=founder['role']).save()

        # GET request
        response = self.client.get(
            f'/companies/{company_id}',
            headers=self.get_authorized_header(auth_token))
        self.assertEqual(response.status_code, 200)
        response_ = json.loads(response.data.decode())
        self.assertIn('founders', response_)
        self.assertIn('role', str(response_['founders']))
        self.assertIn('@demo.com', str(response_['founders']))
Esempio n. 10
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        email = form.email.data
        username = form.username.data

        user = User(email=email, username=username)
        user.password = form.password.data

        company = Company()
        company.name = form.company.data

        db.session.add(user)
        db.session.add(company)

        company.set_company_owner(user)
        company.add_user(user)

        db.session.commit()
        company.company_materials_setup()

        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(
            user.email,
            "Confirm Your Account",
            "auth/email/confirm",
            user=user,
            token=token,
        )
        flash("A confirmation email has been sent to you by email.")
        return redirect(url_for("auth.login"))
    return render_template("auth/register.html", form=form)
Esempio n. 11
0
def company_list():
    try:
        rows = Company.query.all()
        for row in rows:
            db.session.delete(row)
        db.session.commit()
        nasdaqURL = 'https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download'
        nyseURL = 'https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nyse&render=download'
        df1 = pd.read_csv(nasdaqURL, sep=',')
        df2 = pd.read_csv(nyseURL, sep=',')

        c_dict = {}

        for s in df1.values:
            print(s)
            c_dict.update({s[0]: s[1]})

        for s in df2.values:
            c_dict.update({s[0]: s[1]})

        count = 0
        for k, v in c_dict.items():
            temp = v
            if len(temp) > 64:
                temp = temp[0:60]
                temp = temp + "..."
            c = Company(company_symbol=k, company_name=temp)

            db.session.add(c)
        db.session.commit()
        rows = db.session.query(Company).count()
        return "Committed" + str(rows)
    except Exception as inst:
        print(inst)
        return str(inst)
Esempio n. 12
0
def create_contact():
    form = CreateContact()
    if form.validate_on_submit():
        company = Company.query.filter_by(company_name=form.company_name.data)
        email = Email.query.filter_by(email=form.email.data)
        phone = Phone.query.filter_by(phone=form.phone.data)
        if email.count() == 1:
            flash('Email already exist')
            return redirect(url_for('create_contact'))
        if phone.count() == 1:
            flash('Phone already exist')
            return redirect(url_for('create_contact'))
        if company.count() == 1:
            contact = Contact(last_name=form.last_name.data,
                              first_name=form.first_name.data,
                              job_position=form.job_position.data,
                              contact_status=form.contact_status.data)
            company = company.first()
            company.contacts.append(contact)

        else:
            contact = Contact(last_name=form.last_name.data,
                              first_name=form.first_name.data,
                              job_position=form.job_position.data,
                              contact_status=form.contact_status.data)
            company = Company(company_name=form.company_name.data)
            company.contacts.append(contact)
        db.session.add_all([company, contact])
        db.session.commit()
        flash('Congratulations, you have create a new contact !')

    return render_template('create_contact.html',
                           title='Create contact',
                           form=form)
Esempio n. 13
0
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    page = request.args.get('page', 1, type=int)
    form = CompanyRegistrationForm()
    if form.validate_on_submit():
        company = Company(company_name=form.company_name.data)
        db.session.add(company)
        db.session.commit()
        accept = Affiliates(accepted=True)
        accept.user_id = current_user.id
        company.affiliate.append(accept)
        db.session.commit()
        return redirect(url_for('user', username=user.username))
    my_affiliates = Affiliates.query.filter_by(user_id=user.id,
                                               accepted=True).all()
    #for affiliate in my_affiliates:
    #	affiliate.comp_id = affiliate.company_id
    #affiliate.company = Company.query.filter_by(id=affiliate.company_id).first()
    posts = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('user', username=user.username, page=posts.next_num) \
           if posts.has_next else None
    prev_url = url_for('user', username=user.username, page=posts.prev_num) \
           if posts.has_prev else None
    return render_template('user.html',
                           title=user.username,
                           user=user,
                           posts=posts.items,
                           prev_url=prev_url,
                           next_url=next_url,
                           form=form,
                           my_affiliates=my_affiliates)
Esempio n. 14
0
def load_companies_data():
    with open(COMPANIES_DATA, 'r') as f:
        companies = json.load(f)

    for company in companies:
        db.session.add(Company(id=company['index'], name=company['company']))
    db.session.commit()
Esempio n. 15
0
    def test_get_company_by_created(self, mocker):

        expected_results = [
            Company(name='Inmobiliaria Europa S.A',
                    nif=432827568,
                    created_at=datetime.datetime.now(),
                    last_modified_at=datetime.datetime.now()
                    )
        ]

        date = strftime('%Y-%m-%d')

        # Se crea la consulta con django-mock-queries para crear el Mock QuerySets
        # con el cual logramos omitir la consulta a la base de datos
        qs = MockSet(expected_results[0])

        # Patch el metodo qet_queryset para modificar su comportamiento
        # Se modifica el comportamiento con patch el metodo qet_queryset
        # para que retorne nuestro queryset y no el da la base de datos
        mocker.patch.object(Company.objects, 'get_queryset', return_value=qs)

        result = list(Company.objects.get_company_by_created(date))

        assert result == expected_results
        assert str(result[0]) == expected_results[0].name
Esempio n. 16
0
def company_register():
	if current_user.is_authenticated:
		return redirect(url_for("main.home"))
	form = RegistrationForm()
	if form.validate_on_submit():
		if not form.validate_email(form.email):
			flash("Email already being used. Please try again", "danger")
		elif not form.validate_address(form.address):
			flash("Address already being used. Please try again", "danger")
		elif not form.validate_phone_number(form.phone_number):
			flash("Phone number already being used. Please try again", "danger")
		elif not form.validate_website(form.website):
			flash("Website already being used. Please try again", "danger")
		else:
			hashed_password = bcrypt.generate_password_hash(form.password.data)
			user_id = unicode(uuid4())
			company = Company(id=user_id,
						name=form.name.data.lower(),
                        address=form.address.data.lower(),
                        city=form.city.data.lower(),
                        zip_code=form.zip_code.data,
                        state=form.state.data,
                        country=form.country.data,
                        phone_number=form.phone_number.data,
                        email=form.email.data.lower(),
                        website=form.website.data.lower(),
                        password=hashed_password)
			database.session.add(company)
			database.session.commit()
			flash("Your company has been registered! Please sign in!", "success")
			return redirect(url_for("companies.login"))
	return render_template("register_company.html", form=form)
Esempio n. 17
0
def signup():
    form = RegisterForm(request.form)
    if request.method == "POST":
        if form.validate():
            user = User(form.email.data, form.password.data)
            if user:
                user.name = form.name.data
                if user.second_name is not None:
                    user.second_name = form.second_name.data
                user.lastname = form.lastname.data
                if user.second_lastname is not None:
                    user.second_lastname = form.second_lastname.data 
                user.rfc = form.rfc.data
                # add company
                db.session.add(user)
                try:
                    db.session.commit()
                except IntegrityError:
                    db.session.rollback()
                    mess = "Either Email or the RFC exist in the database"
                    flash(mess)
                    return render_template("auth/signup.html", form=form, title="Sign Up")
                company = Company(form.company.data)
                company.user_id = user.id
                db.session.add(company)
                db.session.commit()
                flash("%s Signed Up successfuly with your Company %s" % (user.name, company.name))
                return redirect(url_for("auth.login"))
            flash("Something went wrong, please try again.", 'error-message')
        else:
            return jsonify(form.errors), 400
    return render_template("auth/signup.html", form=form, title="Sign Up")
Esempio n. 18
0
    def handle(self, *args, **options):
        print('Importing.')
        Company.objects.all().delete()
        Person.objects.filter(source='flagma.kz').delete()
        Person2Company.objects.all().delete()
        urls = []
        for cnt in range(1, 1000):
            urls.append('https://flagma.kz/kompanii-k-%s.html' % cnt)

        for url in urls:
            print("Importing %s" % url)
            time.sleep(1)
            i = Import()
            i.url = url
            i.save()
            rez = requests.get(url)
            soup = bs4.BeautifulSoup(rez.text, 'html.parser')
            items = soup.findAll('div', {"class": "page-list-item-info"})
            for i in items:
                name = i.find('a').text
                location = i.find('span', {"itemprop": "location"}).text
                boss = i.find('span', {"itemprop": "employee"}).text
                arrboss = boss.split(',')
                c = Company()
                c.name_ru = name
                c.name_kz = name
                c.faunders_text = boss
                c.city_text = location
                c.save()
                parse_company(c)
                print('Saving.....%s' % name)
Esempio n. 19
0
def create_company(cc_code, link="", name=""):
    company = Company()
    company.id = cc_code
    company.name = name
    company.link = link
    db.session.add(company)
    db.session.commit()
Esempio n. 20
0
def manager(mname):
    form = CompanyForm()

    if form.validate_on_submit():
        company = Company(crypto=form.crypto.data, manager=current_user)
        db.session.add(company)
        db.session.commit()
        flash('Your company is now live!')
        return redirect(url_for('main.manager', mname=mname))
    manager = Manager.query.filter_by(email=mname.lower() +
                                      "@getresponse.com").first_or_404()
    page = request.args.get('page', 1, type=int)

    if manager == current_user:
        companies = manager.followed_companies().paginate(
            page, current_app.config['COMPANIES_PER_PAGE'], False)
        next_url = url_for('main.index', page=companies.next_num) \
            if companies.has_next else None
        prev_url = url_for('main.index', page=companies.prev_num) \
            if companies.has_prev else None
        return render_template('manager.html',
                               title=mname,
                               manager=manager,
                               companies=companies.items,
                               form=form,
                               next_url=next_url,
                               prev_url=prev_url)
    else:
        companies = manager.companies.all()
        return render_template('manager.html',
                               title=mname,
                               manager=manager,
                               companies=companies)
Esempio n. 21
0
    def test_service_add_company(self):
        # create service
        s1 = Service(parent_id=1, title='plumbing')
        s2 = Service(parent_id=2, title='electrical')
        db.session.add(s1)
        db.session.add(s2)
        db.session.commit()

        # create company
        c1 = Company(company_name='Paint Team',
                     company_address='123 Main St.',
                     company_website='Paintteam.com',
                     company_phone_number='2086783456',
                     company_email='*****@*****.**')
        c2 = Company(company_name='Bob Team',
                     company_address='123 Main St.',
                     company_website='Paintteam.com',
                     company_phone_number='2086783456',
                     company_email='*****@*****.**')
        db.session.add(c1)
        db.session.add(c2)
        db.session.commit()

        # add company to service
        check1 = s1.add_company(c1)
        db.session.commit()
        check2 = s2.add_company(c1)
        db.session.commit()

        # check that the connection was made
        self.assertEqual(c1.services.count(), 2)
        self.assertEqual(s1.companies.first().company_name, 'Paint Team')
        self.assertEqual(c1.services.first().id, 1)
        print(c1.services.first().id)

        # remove companies
        check3 = s2.remove_company(c1)

        # check that it was removed
        self.assertEqual(c1.services.count(), 1)

        # add services to company
        check4 = c2.services.append(s1)

        # check that the connection was made
        self.assertEqual(c2.services.count(), 1)
        self.assertEqual(c2.services.first().title, 'plumbing')
Esempio n. 22
0
 def test_default_password(self):
     Company(name="Demo", website="http://www.demo.com").save()
     company_id = Company.query.first().id
     Founder(name="Tu",
             email="*****@*****.**",
             role="CEO",
             company_id=company_id).save()
     user = User.query.first()
     self.assertTrue(bcrypt.check_password_hash(user.password, 'founder'))
Esempio n. 23
0
    def set_up_test_db():
        person1 = Person(index=0, name='Test', age=30, has_died=False, eye_color='black', phone='000', address='test')
        person2 = Person(index=1, name='Test', age=30, has_died=False, eye_color='black', phone='000', address='test')
        friend = Person(index=2, name='Friend', age=30, has_died=False, eye_color='brown', phone='000', address='test')
        company = Company(index=0, name='Test')
        no_employees_company = Company(index=1, name='No Employees')
        vegetable = Food(index=0, name='Lettuce', type=Food.VEGETABLE)
        fruit = Food(index=1, name='Banana', type=Food.FRUIT)

        person1.company = company
        person1.foods.append(vegetable)
        person1.foods.append(fruit)
        person2.company = company
        person1.befriend(friend)
        person2.befriend(friend)

        db.session.add(person1)
        db.session.add(no_employees_company)
Esempio n. 24
0
def sign_up():
    content = request.get_json()
    print(content)
    db_session.add(Company(content['email'], content['companyName'], pbkdf2_sha256.hash(content['password']),
                           content['countryId'], content['country']))
    db_session.commit()
    company = Company.query.filter_by(email=content['email']).first()
    add_user(content['email'], content['password'], company.id, user_type="Owner")
    return "SUCCESS", status.HTTP_202_ACCEPTED
Esempio n. 25
0
def sample_data():
    set_up()

    user1 = User(username="******",
                 email="*****@*****.**",
                 password="******",
                 confirmed=True)
    user2 = User(username="******",
                 email="*****@*****.**",
                 password="******",
                 confirmed=True)
    user3 = User(username="******",
                 email="*****@*****.**",
                 password="******",
                 confirmed=True)
    user4 = User(username="******",
                 email="*****@*****.**",
                 password="******",
                 confirmed=True)

    company1 = Company(name="ExampleCompanyOne.com")
    company2 = Company(name="ExampleCompanyTwo.com")

    db.session.add(user1)
    db.session.add(user2)
    db.session.add(user3)
    db.session.add(user4)

    company1.add_user(user1)
    company1.add_user(user2)
    company1.set_company_owner(user1)
    company1.add_asset("company1_asset")
    db.session.add(company1)

    company2.add_user(user3)
    company2.add_user(user4)
    company2.set_company_owner(user3)
    company2.add_asset("company2_asset")
    db.session.add(company2)

    db.session.commit()
    company1.company_materials_setup()
    company2.company_materials_setup()
    db.session.commit()
Esempio n. 26
0
def load_companies(file='../data/companies.json'):
    input_file = open(file, encoding='utf-8')
    json_array = json.load(input_file)

    for item in json_array:
        company = Company(name=item['name'],
                          dic=item['dic'],
                          residence=item['residence'])
        db.session.add(company)
    db.session.commit()
Esempio n. 27
0
    def test_list(self, rf, mocker):
        # django-pytest nos permite pasar por inyeccion de dependencia
        # a nuestros tests algunos objetos, en este objeto RequestFactory(rf)
        # y mocker para hacer patch a objetos y funciones
        url = reverse('company-list')
        request = rf.get(url)

        queryset = MockSet(
            Company(id=1, name='Inmobiliaria Europa 1', nif=43282757),
            Company(id=2, name='Inmobiliaria Europa 2', nif=43282758),
            Company(id=3, name='Inmobiliaria Europa 3', nif=43282759)
        )

        mocker.patch.object(CompanyViewSet, 'get_queryset',
                            return_value=queryset)
        response = CompanyViewSet.as_view({'get': 'list'})(request).render()

        assert response.status_code == status.HTTP_200_OK
        assert len(json.loads(response.content)) == 3
Esempio n. 28
0
 def test_company_model(self):
     company = Company(name="RBS",
                       description="International bank",
                       address="36 St Andrew Square",
                       city="Edinburgh",
                       post_code="EH2 2YB")
     db.session.add(company)
     db.session.commit()
     self.assertEqual(Company.query.count(), 1)
     self.assertFalse(company.is_new)
     company = Company(name="New company",
                       description="placeholder",
                       address="placeholder",
                       city="placeholder",
                       post_code="placehldr")
     db.session.add(company)
     db.session.commit()
     self.assertEqual(Company.query.count(), 2)
     self.assertTrue(company.is_new)
Esempio n. 29
0
def add_company():
    form = CompanyForm()
    if form.validate_on_submit():
        company = Company(company_name=form.name.data,
                          description=form.description.data)
        db.session.add(company)
        db.session.commit()
        flash('Successfully added company')
        return redirect(url_for('home'))
    return render_template('add_company.html', form=form)
Esempio n. 30
0
    def test_expected_serialized_json(self):
        expected_results = {
            'id': 1,
            'name': 'Inmobiliaria Europa S.A',
            'nif': 432827568
        }

        company = Company(**expected_results)
        results = CompanySerializer(company).data

        assert results == expected_results