示例#1
0
 def to_company(self, company: Company):
     """Create a transaction to company"""
     if self._has_enough_money_to_transfer():
         self.from_company.balance -= self.amount
         company.balance += self.amount
         self.from_company.save()
         company.save()
 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))
示例#3
0
def cleaning():
    app.app_context().push()
    print("Starting cleaning job...")
    Company.company_cleaning()
    Announcement.announcement_cleaning()
    db.session.commit()
    print("Cleaning job completed...")
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")
示例#5
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']))
示例#6
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)
示例#7
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)
    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])
示例#9
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()
示例#10
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     Company.generate_fake(10)
     Indicators.generate_fake(3)
示例#11
0
    def test_company_from_json(self):
        c = Company.from_json({'name': 'ABC Company', 'symbol': 'ABC', 'index': "NYSE"})
        self.assertTrue(isinstance(c, Company))
        with self.assertRaises(ValueError):
            c = Company.from_json({'name': '', 'symbol': ''})

        c = Company.from_json({'name': 'DEF Company', 'symbol': 'DEF', 'active': False})
        self.assertTrue(isinstance(c, Company))
示例#12
0
    def create(self, user, name=None):
        if user is None:
            raise TypeError('user is None.')

        company = Company(name=name, user=user)
        company.put()

        return company
示例#13
0
def company_create():
    if not request.json or 'name' not in request.json:
        return json.dumps({'error': 'incorrect_params'}), 400, {
            'ContentType': 'application/json'
        }

    name = request.json['name']
    Company.create(name)
    return jsonify({'success': True}), 200, {'ContentType': 'application/json'}
示例#14
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()
示例#15
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))
示例#16
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))
示例#17
0
文件: views.py 项目: Boomatang/Clue
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)
示例#18
0
def test_create_company():
    c = Company()
    c.name = "test name"

    db.session.add(c)

    db.session.commit()

    db_c = Company.query.filter_by(name="test name").first()

    assert db_c == c
示例#19
0
def addCompany(id):
    form = CompanyForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        newCompany = Company(
            userId_fk=id,
            companyName=form.data['companyName'],
        )
        db.session.add(newCompany)
        db.session.commit()
        return newCompany.to_dict()
    return { 'errors': validation_errors_to_error_messages(form.errors)}
示例#20
0
    def test_company_description(self):
        self.app.logger.debug('test_company_description')
        description = u'Über'
        user = self.create_default_user()
        company = Company(user=user, name='A Company')
        company.description = description
        db.session.add(company)
        db.session.commit()

        company = Company.query.first()
        assert company is not None
        assert company.description == description
示例#21
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)
示例#22
0
def test_users_company_name(clean_db):
    company = Company()
    company.name = "test name"

    user1 = User()
    user1.username = "******"

    db.session.add(user1)
    db.session.add(company)

    company.add_user(user1)

    db.session.commit()

    assert user1.company.name == company.name
示例#23
0
def get_name_from_symbol(symbol):
    """
    Use EDGAR online database to find the company name.
    """
    from flask import current_app
    import dryscrape
    from app.models import Company

    if not Company.validate_symbol(symbol):
        return None

    r = requests.get("http://edgaronline.api.mashery.com/v2/companies?primarysymbols={}&appkey={}".format(symbol, current_app.config['EDGAR_APP_KEY']))

    try:
        values = r.json()['result']['rows'][0]['values']
    except (KeyError, IndexError) as e:
        return None

    companyname = None
    for value in values:
        if value.get('field') == "companyname":
            companyname = value.get('value')
            break

    return companyname
示例#24
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)
示例#25
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)
示例#26
0
def create_company():
    """
    [POST] /company
    """
    response = request.get_json()
    c = Company(company_status=response['company_status'],
                company_name=response['company_name'],
                company_city=response['company_city'],
                company_state=response['company_state'],
                company_zip_code=response['company_zip_code'],
                company_phone=response['company_phone'],
                company_website=response['company_website'],
                notes=response['notes'],
                user_id=response['user_id'])
    c.create_company()
    return jsonify([company.to_dict() for company in Company.query.all()])
示例#27
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)
示例#28
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)
示例#29
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()
示例#30
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()
示例#31
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
示例#32
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)
示例#33
0
def get_company_list():
    params = request.args
    page, size = get_pagination(params)
    search = params.get('search')
    deployment = params.get('deployment')
    scenario = params.get('scenario')
    consigner = params.get('consigner')

    query = Company.query

    if consigner:
        query = query.filter_by(consigner=consigner)

    if search:
        users = User.query.filter(User.username.contains(search)).all()
        ids = map(lambda user: getattr(user, 'company_id'), users)
        query = query.filter(
            or_(Company.name.contains(search), Company.id.in_(ids)))

    if deployment and deployment != '0':
        query = query.filter(Company.deployment == deployment)

    if scenario:
        query = query.filter(Company.scenario == scenario)

    pagination = query.options(db.joinedload('screens')) \
        .options(db.joinedload('display_devices')) \
        .add_column(Company.subject_count).order_by(Company.id.desc()).paginate(page, size)
    company_list = []
    for company, subject_count in pagination.items:
        company = company.get_json(with_status=True)
        company['subject_count'] = subject_count
        user = User.query.filter_by(company_id=company['id'],
                                    role_id=UserRole.ROLE_ADMIN).first()
        if user:
            company['username'] = user.username
        company_list.append(company)

    deployments = Company.get_deployment_count()
    deployments['0'] = sum(deployments.values())

    data = {
        'companies': company_list,
        'scenarios': Company.get_scenario_count(),
        'deployments': deployments
    }
    return success_result(data, page_format(pagination))
示例#34
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')
示例#35
0
def add_company(dataset):
    companies = []
    individuals = list(Individual.query.all())
    for i, cmpy in enumerate(dataset):
        jpindividuals = list(JPInvididual.query.all())
        total_capital = 0
        cmpny_to_add = Company(name=cmpy['name'],
                               registry_id=cmpy['registry_id'],
                               established=cmpy['established'])
        if len(dataset) < 11:
            qty = len(dataset)
        else:
            qty = 10
        shareholders = random.sample(individuals, random.randint(1, qty))
        if len(jpindividuals) < 5:
            qty = len(jpindividuals)
        else:
            qty = 5
        if jpindividuals:
            jp_shareholders = random.sample(jpindividuals,
                                            random.randint(1, qty))
            for owner in jp_shareholders:
                print(owner)
                shares = random.randint(2500, 5000)
                total_capital += shares
                a = JpOwnerAssociation(shares=shares,
                                       founder=bool(random.getrandbits(1)),
                                       owner_id=owner.id)
                a.companies_jp_owned = owner
                cmpny_to_add.company_jp_owners.append(a)
        for owner in shareholders:
            print(owner)
            shares = random.uniform(2500, 5000)
            total_capital += shares
            a = NpOwnerAssociation(shares=shares,
                                   founder=bool(random.getrandbits(1)),
                                   owner_id=owner.id)
            a.companies_np_owned = owner
            cmpny_to_add.company_owners.append(a)

        cmpny_to_add.total_capital = total_capital
        print(cmpny_to_add)
        db.session.add(cmpny_to_add)
        db.session.add(apply_jp_values(cmpny_to_add))
        new_entries = db.session.commit()

    return new_entries
示例#36
0
def stock_add(request):
    from app.remote.stocks import StockHistoryClient
    from app.forms import StockWizardForm
    from app.models import Company, Stock

    if request.method == "POST":
        form = StockWizardForm(request.POST)
        pprint(form.is_valid())
        if form.is_valid():
            # save
            company = Company()
            company.name = form.cleaned_data['company_name']
            company.country = form.cleaned_data['company_country']
            company.save()

            stock = Stock()
            stock.company = company
            stock.name = form.cleaned_data['name']
            stock.wkn = form.cleaned_data['wkn']
            stock.isin = form.cleaned_data['isin']
            stock.symbol = form.cleaned_data['symbol']
            stock.type = form.cleaned_data['type']
            stock.default_stock_exchange = form.cleaned_data['default_stock_exchange']
            stock.save()

            return HttpResponseRedirect(reverse('stock', args=(stock.symbol,)))
        else:
            pprint(form.errors)
    else:
        data = None
        if 'wkn_or_isin' in request.GET:
            shc = StockHistoryClient()
            data = shc.get_basics_by_wkn_or_isin(wkn_or_isin=request.GET['wkn_or_isin'])

            data['company_country'] = data['country']
            data['company_name'] = data['name']

        form = StockWizardForm(initial=data)

    return render_to_response(
        'stock_wizard_add.html',
        {
            'form': form
        },
        context_instance=RequestContext(request)
    )
示例#37
0
def _companies_from_json(app, content=''):
    if 'companies' in content:
        for obj in content['companies']:
            user = User.query.filter_by(email=obj['user']).first()
            if user is None:
                app.logger.error('Company: %s, Unknown user: %s' % (obj['name'], obj['user']))
                break

            company = Company.query.filter_by(user=user, name=obj['name']).first()
            if company is None:
                company = Company()
            company.user = user
            company.name = obj['name']
            company.description = obj['description']

            app.logger.debug('adding company: %s' % company)
            db.session.add(company)
        db.session.commit()
示例#38
0
文件: company.py 项目: tomov/celery
def fetch_and_populate_company(name, linkedin_id, callback_url=None, crunchbase_url=None):
    print 'TASK! fetch company ' + str(name.encode('utf8')) + ', ' + str(linkedin_id)

    # 1) Try to find company in database by linkedin id or by name
    if not linkedin_id:
        # TODO make intelligent disambiguiation based on name
        return 'Sorry no linkedin id'
    company = Company.from_linkedin_id(linkedin_id)
    if not company:
        print '                     linkedin id not found; fetching by name...'
        company = Company.from_name(name)

    # 2) fetch it from crunchbase if it doesn't exist or is outdated
    company_info = None
    if company:
        print '    ...company already exists as ' + str(company.name.encode('utf8')) + ', ' + str(company.linkedin_id)
        if not company.last_crunchbase_update or company.last_crunchbase_update < datetime.now() - timedelta(days=EXPIRATION_DAYS):
            print '       crunchbase not updated for ' + str(EXPIRATION_DAYS) + ' days => updating'
            company_info = fetch_company_info_from_crunchbase.delay(company)
        elif crunchbase_url and company.crunchbase_url != crunchbase_url:
            print '       new crunchbase url ' + crunchbase_url.encode('utf8') + ' (old was ' + str(company.crunchbase_url) + ')'
            company.crunchbase_url = crunchbase_url
            company_info = fetch_company_info_from_crunchbase.delay(company)
        else:
            print '       crunchbase updated recently => no crunchbase update necessary'
    else:
        print '     ...' + str(name.encode('utf8')) + ', ' + str(linkedin_id) + ' does not exist => new company' 
        company = Company(name, linkedin_id)
        company.crunchbase_url = crunchbase_url
        db.session.add(company)
        company_info = fetch_company_info_from_crunchbase.delay(company)

    with allow_join_result():
        if company_info:
            print '     waiting for crunchbase result'
            company_info = company_info.wait()
            update_company_with_crunchbase_info(company, company_info)
        db.session.commit()
  
    # 3) send back company to the mother ship
    print 'callback url = ' + str(callback_url)
    if callback_url:
        serialize_and_send_company_to_callback_url(company, callback_url)
    return 'Done?' # TODO return meaningful result 
示例#39
0
def create():
    form = CreateCompanyForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(document=form.document.data, name=form.username.data, email=form.email.data, password=form.password.data)
        company = Company.create(nit=form.nit.data, name=form.name.data, user=user)
        user.put()
        company.put()
        app.logger.debug(company)
        app.logger.debug(user)
    return render('companies/create.html', form=form)
示例#40
0
def bootstrap(app):
    from app.models import DBSession, Company, User

    user = User(document=1128417376, name=u'Willington Vega', email=u'*****@*****.**', password=u'password')
    company = Company.create(nit=9003671435, name=u'Inv. Sinapsis S.A.S', user=user)

    DBSession.add(user)
    DBSession.add(company)
    DBSession.commit()

#    environ = {
#        'path': '/company/create',
#        'method': 'POST',
#        'data': {
#            'nit': '9003671435',
#            'name': 'Inv. Sinapsis S.A.S',
#            'document': '1128417376',
#            'username': '******',
#            'email': '*****@*****.**',
#            'password': '******',
#            'confirm': 'password'
#        }
#    }
示例#41
0
 def test_validate_symbol(self):
     self.assertTrue(Company.validate_symbol("GOOD"))
     self.assertFalse(Company.validate_symbol("Bad"))
示例#42
0
def db_rebuild():
    """
    Destroy and rebuild database with fake data.
    """
    # destroy and rebuild tables
    db.reflect()
    db.drop_all()
    db.create_all()

    # insert roles as defined in model
    Role.insert_roles()

    # insert geos and usertypes as defined in model
    Geo.insert_geos()
    UserType.insert_user_types()

    # insert firm types/tiers as defined in model
    FirmType.insert_firm_types()
    FirmTier.insert_firm_tiers()

    # insert fake admin/test users
    from random import seed
    import forgery_py
    seed()
    test_user_1 = User(
        email='*****@*****.**',
        username='******',
        password='******',
        confirmed=True,
        name='Salim Hamed',
        location='Seattle, WA',
        about_me=forgery_py.lorem_ipsum.sentence(),
        member_since=forgery_py.date.date(True)
    )
    test_user_2 = User(
        email='*****@*****.**',
        username='******',
        password='******',
        confirmed=True,
        name='Bryan Davis',
        location='Seattle, WA',
        about_me=forgery_py.lorem_ipsum.sentence(),
        member_since=forgery_py.date.date(True)
    )
    test_user_3 = User(
        email='*****@*****.**',
        username='******',
        password='******',
        confirmed=True,
        name='Joe Smith',
        location='San Francisco, CA',
        about_me=forgery_py.lorem_ipsum.sentence(),
        member_since=forgery_py.date.date(True)
    )
    test_user_4 = User(
        email='*****@*****.**',
        username='******',
        password='******',
        confirmed=True,
        name='Bill Gates',
        location='Bellevue, WA',
        about_me=forgery_py.lorem_ipsum.sentence(),
        member_since=forgery_py.date.date(True)
    )
    admin_user = User(
        email='*****@*****.**',
        username='******',
        password='******',
        confirmed=True,
        name='Bill Gates',
        location='Seattle, WA',
        about_me=forgery_py.lorem_ipsum.sentence(),
        member_since=forgery_py.date.date(True)
    )
    db.session.add_all([test_user_1, test_user_2, test_user_3, test_user_4,
                        admin_user])
    db.session.commit()

    # insert fake user data
    User.generate_fake(60)

    # insert fake post data
    Post.generate_fake(400)

    # insert fake followers
    Follow.generate_fake(2000)

    # insert fake firms
    Firm.generate_fake(5000)

    # insert fake companies
    Company.generate_fake(10000)

    # insert fake relationships
    Relationship.generate_fake(60000)

    # print results
    inspector = db.inspect(db.engine)
    print 'The following tables were created.'
    print '-'*17
    for table in inspector.get_table_names():
        print table
示例#43
0
def make_data():
    """
    Generate some fake data
    """
    Company.generate_fake(3000)
    Indicators.generate_fake(500)
def get_company_details(throttle=True, count=0, index="NYSE"):
    """
    throttle: true = 1 second wait between requests
    Count < 1 implies get all
    index: NYSE or NASDAQ

    """
    import re
    import time
    import requests
    import string
    from bs4 import BeautifulSoup

    from app.models import Company, Indicators, Index
    from app.utils import cash_to_float, depercentize
    from app import db

    # Add the index if it doesn't exist
    if not Index.query.filter(Index.name == index).first():
        db.session.add(Index(name=index))
        db.session.commit()

    curr = 0
    if count > 0:
        print "Attempting to pull", count, "companies"
    else:
        print "Pull all companies"

    break_out = False
    for c in string.uppercase:
        r = get_symbol_lists(index, c)
        soup = BeautifulSoup(r.text, "lxml")
        table = soup.find_all("table", class_="quotes")[0]
        trs = table.find_all("tr")
        trs.pop(0)  # remove header row
        for tr in trs:
            symbol = tr.td.a.text
            name = tr.td.next_sibling.text
            print curr, "Add", symbol, name
            if symbol and name:
                try:
                    db.session.add(Company.from_json({"name": name, "symbol": symbol, "index": index}))
                    db.session.commit()
                except (IntegrityError, UnmappedInstanceError) as e:
                    print "Caught", e
                    db.session.rollback()
                except ValueError as e:
                    print "Invalid company name or symbol"
                    print e
                    db.session.rollback()

            curr += 1
            if count > 0:
                if curr >= count:
                    break_out = True
                    break

        if throttle:
            time.sleep(1)

        if break_out:
            break
示例#45
0
 def test_validate_name(self):
     self.assertTrue(Company.validate_name("Good Company"))
     self.assertFalse(Company.validate_name("Bad Company**!"))