Exemple #1
0
    def test_get_workers(app_and_db):
        db = app_and_db[1]
        user1 = User(username="******",
                     email="*****@*****.**",
                     password="******")
        user2 = User(username="******",
                     email="*****@*****.**",
                     password="******")
        db.session.add(user1)
        db.session.add(user2)
        db.session.add(Investment(name="test invest 1"))
        db.session.add(Investment(name="test invest 2"))
        db.session.add(Investment(name="test invest 3"))
        db.session.commit()

        user1 = User.get_user(1)
        invest1 = Investment.query.filter_by(id=1).first()
        invest1.workers.append(Worker(position="pos1", user_id=user1.id))
        invest2 = Investment.query.filter_by(id=2).first()
        invest2.workers.append(Worker(position="pos2", user_id=user1.id))

        user2 = User.get_user(2)
        invest3 = Investment.query.filter_by(id=3).first()
        invest3.workers.append(Worker(position="pos3", user_id=user2.id))

        db.session.commit()

        worker1 = Worker.query.filter_by(position="pos1").first()
        worker2 = Worker.query.filter_by(position="pos2").first()

        assert User.get_workers(user_id=1) == [worker1, worker2]
Exemple #2
0
    def test_post_when_delete(app_and_db, client, test_with_authenticated_user,
                              inactive_user):
        db = app_and_db[1]

        investment1 = Investment(name="Test Invest 1")
        user1 = User.query.filter_by(username="******").first()
        user2 = User.query.filter_by(username="******").first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=True, user_id=user2.id)
        investment1.workers.append(worker1)
        investment1.workers.append(worker2)

        investment2 = Investment(name="Test Invest 2")
        worker = Worker(position="pos1", admin=True, user_id=user1.id)
        investment2.workers.append(worker)

        db.session.add(investment1)
        db.session.add(investment2)
        db.session.commit()

        response = client.post(
            url_for("auth.delete_account", username="******"),
            data={"yes": True},
            follow_redirects=True,
        )
        assert response.status_code == 200
        assert not User.query.filter_by(username="******").first()
        assert not Worker.query.filter_by(user_id=user1.id).first()
        assert Worker.query.filter_by(user_id=user2.id).first()
        assert Investment.query.filter_by(name="Test Invest 1").first()
        assert not Investment.query.filter_by(name="Test Invest 2").first()
        assert b"The account has been deleted." in response.data
Exemple #3
0
    def test_get_num_of_admins(app_and_db):
        db = app_and_db[1]
        for i in range(1, 4):
            user = User(
                username="******".format(i),
                email="user_{}@mail.com".format(i),
                password="******",
            )
            user.is_active = True
            db.session.add(user)
        investment = Investment(name="test invest")
        db.session.add(investment)
        db.session.commit()

        user1 = User.get_user(1)
        user2 = User.get_user(2)
        user3 = User.get_user(3)
        invest = Investment.query.filter_by(id=1).first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=False, user_id=user2.id)
        worker3 = Worker(position="pos3", admin=True, user_id=user3.id)
        invest.workers.append(worker1)
        invest.workers.append(worker2)
        invest.workers.append(worker3)
        db.session.commit()

        assert Investment.get_num_of_admins(investment_id=1) == 2
Exemple #4
0
    def test_get_by_user_id(app_and_db, active_user):
        db = app_and_db[1]
        investment = Investment(name="test")
        user = User.query.filter_by(username="******").first()
        worker = Worker(position="test worker", user_id=user.id)
        investment.workers.append(worker)
        db.session.add(investment)
        db.session.commit()

        assert Investment.get_by_user_id(user_id=1)
Exemple #5
0
    def test_is_admin(app_and_db, active_user):
        db = app_and_db[1]
        db.session.add(Investment(name="test invest 1"))
        db.session.add(Investment(name="test invest 2"))
        db.session.add(
            Worker(position="pos1", admin=True, user_id=1, investment_id=1))
        db.session.add(
            Worker(position="pos2", admin=False, user_id=1, investment_id=2))
        db.session.commit()

        assert Worker.is_admin(user_id=1, investment_id=1)
        assert not Worker.is_admin(user_id=1, investment_id=2)
Exemple #6
0
    def test_get_investment(app_and_db, active_user):
        db = app_and_db[1]
        user = User.get_user(1)
        db.session.add(Investment(name="test invest 1"))
        db.session.add(Investment(name="test invest 2"))
        db.session.commit()

        invest1 = Investment.query.filter_by(id=1).first()
        invest1.workers.append(Worker(user_id=user.id))
        invest2 = Investment.query.filter_by(id=2).first()
        invest2.workers.append(Worker(user_id=user.id))
        db.session.commit()

        assert User.get_investments(user_id=1) == [invest1, invest2]
Exemple #7
0
def change_root_permission():
    _id = request.args.get("_id")
    if Worker.is_admin(current_user.id, g.current_invest.id):
        worker = Worker.query.filter_by(id=_id).first()
        if worker:
            num_of_admins = Investment.get_num_of_admins(g.current_invest.id)
            if num_of_admins < 2:
                if worker.admin:
                    flash("You can not delete last admin!")
                    return redirect(url_for("team.team"))
            form = WarrantyForm()
            if form.validate_on_submit():
                if form.yes.data:
                    if worker.admin:
                        worker.admin = False
                    else:
                        worker.admin = True
                    db.session.commit()
                    flash(
                        "You have changed worker's root permission successfully."
                    )
                return redirect(url_for("team.team"))
            return render_template("warranty_form.html",
                                   title="Change Root Permission",
                                   form=form)
    return redirect(url_for("team.team"))
Exemple #8
0
def purchase(username):
    user = UserProfile.query.filter_by(username=username)
    if user is not None:
        user = user.first()
        coin_name = request.form['coin_name'] or None
        coin_conversion_rate = float(request.form['coin_conversion_rate'])
        purchase_amount = float(request.form['purchase_amount'])
        if purchase_amount <= user.balance:
            number_of_coins = purchase_amount / coin_conversion_rate
            coin_investment_instance = None
            for coin in user.coin_investments:
                if coin.coin_name == coin_name:
                    coin_investment_instance = coin
                    break
            if coin_investment_instance is None:
                coin_investment_instance = Investment(user_id=user.id, coin_name=coin_name,
                                                      number_of_coins=number_of_coins, total_price=purchase_amount)
            else:
                coin_investment_instance.number_of_coins += number_of_coins
                coin_investment_instance.total_price += purchase_amount
            db.session.add(coin_investment_instance)
            db.session.commit()
            transaction = Transaction(investment_id=coin_investment_instance.id, coin_name=coin_name,
                                      number_of_coins=number_of_coins, total_price=purchase_amount)
            db.session.add(transaction)
            db.session.commit()
            user.balance -= purchase_amount
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('investments.dashboard', username=user.username))
        else:
            flash("Insufficient balance.")
            return redirect(url_for('investments.checkprice', username=user.username))
    else:
        return render_template('404_error')
Exemple #9
0
    def test_post_when_user_is_lonely_admin(app_and_db, client,
                                            test_with_authenticated_user,
                                            inactive_user):
        db = app_and_db[1]
        investment = Investment(name="Test Invest")
        user1 = User.query.filter_by(username="******").first()
        user2 = User.query.filter_by(username="******").first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=False, user_id=user2.id)
        investment.workers.append(worker1)
        investment.workers.append(worker2)
        db.session.add(investment)
        db.session.commit()

        response = client.post(
            url_for("auth.delete_account", username="******"),
            data={"yes": True},
            follow_redirects=True,
        )
        assert response.status_code == 200
        assert User.query.filter_by(username="******").first()
        assert Worker.query.filter_by(user_id=user1.id).first()
        assert Worker.query.filter_by(user_id=user2.id).first()
        assert (
            b"This accounts is only admin in projects: [&#39;Test Invest&#39;]."
            b" Give root permission to other user and try again"
            in response.data)
Exemple #10
0
    def test_get_team(app_and_db, active_user):
        db = app_and_db[1]
        db.session.add(Investment(name="test invest 1"))
        db.session.add(Worker(position="pos1", admin=True, investment_id=1))
        db.session.add(Worker(position="pos2", admin=False, investment_id=1))
        db.session.add(Worker(position="pos2", admin=False, investment_id=1))
        db.session.add(Investment(name="test invest 2"))
        db.session.add(Worker(position="pos2", admin=False, investment_id=2))
        db.session.add(Worker(position="pos2", admin=False, investment_id=2))
        db.session.commit()

        worker1 = Worker.query.get(1)
        worker2 = Worker.query.get(2)
        worker3 = Worker.query.get(3)

        assert Worker.get_team(investment_id=1) == [worker1, worker2, worker3]
Exemple #11
0
def invest_list() -> str:
    investments = Investment.get_by_user_id(current_user.id)
    return render_template(
        "investments/investments.html",
        title="Investments",
        username=current_user.username,
        investments=investments,
    )
Exemple #12
0
def delete_if_unused(username: str) -> None:
    user = User.query.filter_by(username=username).first()
    if user:
        if user.last_activity + timedelta(seconds=300) < datetime.utcnow():
            for investment in Investment.get_by_user_id(user.id):
                db.session.delete(investment)
            db.session.delete(user)
            db.session.commit()
        else:
            delete_if_unused.apply_async(args=(user.id, ), countdown=600)
Exemple #13
0
    def test_belongs_to_investment(app_and_db, active_user):
        db = app_and_db[1]
        investment = Investment(name="test invest")
        worker = Worker(position="pos1", user_id=1)
        investment.workers.append(worker)
        db.session.add(investment)
        db.session.commit()

        assert Worker.belongs_to_investment(email="*****@*****.**",
                                            investment_id=1)
        assert not Worker.belongs_to_investment(email="*****@*****.**",
                                                investment_id=1)
Exemple #14
0
    def test_check_admins(app_and_db):
        db = app_and_db[1]

        for i in range(1, 5):
            user = User(
                username="******".format(i),
                email="user_{}@mail.com".format(i),
                password="******",
            )
            user.is_active = True
            db.session.add(user)
            investment = Investment(name="test invest {}".format(i))
            db.session.add(investment)
            db.session.commit()

        user1 = Investment.query.filter_by(id=1).first()
        user2 = Investment.query.filter_by(id=2).first()
        user3 = Investment.query.filter_by(id=3).first()

        # one user -> not add to list
        invest1 = Investment.query.filter_by(id=1).first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        invest1.workers.append(worker1)

        # two users, one admin, user1 is admin -> add to list
        invest2 = Investment.query.filter_by(id=2).first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=False, user_id=user2.id)
        invest2.workers.append(worker1)
        invest2.workers.append(worker2)

        # two users, user1 is not admin -> not add to list
        invest3 = Investment.query.filter_by(id=3).first()
        worker1 = Worker(position="pos1", admin=False, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=True, user_id=user2.id)
        invest3.workers.append(worker1)
        invest3.workers.append(worker2)

        # three user, two admin, user1 is admin -> not add to list
        invest4 = Investment.query.filter_by(id=4).first()
        worker1 = Worker(position="pos1", admin=True, user_id=user1.id)
        worker2 = Worker(position="pos2", admin=False, user_id=user2.id)
        worker3 = Worker(position="pos3", admin=True, user_id=user3.id)
        invest4.workers.append(worker1)
        invest4.workers.append(worker2)
        invest4.workers.append(worker3)

        db.session.commit()

        user = User.query.filter_by(username="******").first()
        assert User.check_admins(user_id=user.id)[0] == [invest2]
        assert User.check_admins(user_id=user.id)[1] == [invest1]
Exemple #15
0
    def test_get_current_invest(app_and_db, active_user):
        db = app_and_db[1]

        investment = Investment(name="Test Investment")
        user = User.query.filter_by(username="******").first()
        user.current_invest_id = 1
        worker = Worker(position="test position", user_id=user.id)
        investment.workers.append(worker)
        db.session.add(investment)
        db.session.commit()

        user = User.query.filter_by(username="******").first()
        current_invest = user.get_current_invest()
        print(type(current_invest))
        assert current_invest.name == "Test Investment"
Exemple #16
0
def add_investment(app_and_db, active_user, unlogged_user):
    db = app_and_db[1]
    user1 = User.query.filter_by(username="******").first()
    user2 = User.query.filter_by(username="******").first()
    investment = Investment(name="Test Invest", description="test text")
    worker1 = Worker(position="admin", admin=True, user_id=user1.id)
    worker2 = Worker(position="second worker", admin=False, user_id=user2.id)
    investment.workers.append(worker1)
    investment.workers.append(worker2)
    db.session.add(investment)
    db.session.commit()

    # setting current_invest
    investment = Investment.query.filter_by(name="Test Invest").first()
    user1.current_invest_id = investment.id
    db.session.commit()
Exemple #17
0
    def test_investment(app_and_db, active_user):
        db = app_and_db[1]

        investment = Investment(name="Test Investment")
        user = User.query.filter_by(username="******").first()
        worker = Worker(position="test position", user_id=user.id)
        investment.workers.append(worker)
        db.session.add(investment)
        db.session.commit()

        user = User.query.filter_by(username="******").first()
        worker = Worker.query.filter_by(position="test position").first()
        investment = Investment.query.filter_by(name="Test Investment").first()

        assert user.workers.first() == worker
        assert investment.workers.first() == worker
        assert worker.user_id == user.id
        assert worker.investment_id == investment.id
def connect_finance(connections, ftype):
    if connections:
        for finance in connections:
            try:
                source = Entity.query.filter_by(id=old_to_new[finance['source']]).first()
                target = Entity.query.filter_by(id=old_to_new[finance['target']]).first()
                if ftype == 'funding':
                    grant = Grant(finance['amount'], finance['year'])
                    # Odd civic.json convention of source/target "received"
                    source.grants_received.append(grant)
                    target.grants_given.append(grant)
                elif ftype == 'investment':
                    investment = Investment(finance['amount'], finance['year'])
                    # Odd civic.json convention of source/target "received"
                    source.investments_received.append(investment)
                    target.investments_made.append(investment)
            except KeyError as e:
                # Some IDs in civic.json aren't rendered... 
                # Point to them manually.
                print "Failed to find ID: ", e
Exemple #19
0
def create() -> str:
    form = InvestmentForm()
    if form.validate_on_submit():
        investment = Investment(
            name=form.name.data,
            description=form.description.data,
        )
        worker = Worker(
            position="admin",
            admin=True,
            user_id=current_user.id,
        )
        investment.workers.append(worker)
        db.session.add(investment)
        db.session.commit()
        flash("You have created new investment successfully.")
        return redirect(url_for("investments.invest_list"))
    return render_template("investments/form.html",
                           title="Create Investment",
                           form=form)
Exemple #20
0
 def test_get_by_user_id_when_no_user(app_and_db):
     assert not Investment.get_by_user_id(user_id=1)
Exemple #21
0
app_ctx.push()
db.create_all()
Role.insert_roles()

admin = User(name=u'root',
             email='*****@*****.**',
             password='******',
             major='administrator',
             headline=u"administrator",
             about_me=u"administrator")
user1 = User(name=u'Jing',
             email='*****@*****.**',
             password='******',
             major='Software Engineering',
             headline=u"student")
user2 = User(name=u'test', email='*****@*****.**', password='******')
user3 = User(name=u'alex', email='*****@*****.**', password='******')
user4 = User(name=u'ben', email='*****@*****.**', password='******')

investments = [
    Investment(user1, 6000, "Ethical Investing,Growth Investing"),
    Investment(user1, 7000, "Ethical Investing,Index Investing"),
    Investment(user2, 8000, "Index Investing,Quality Investing"),
    Investment(user3, 9000, "Index Investing,Value Investing")
]

db.session.add_all([admin, user1, user2, user3, user4] + investments)
db.session.commit()

app_ctx.pop()
Exemple #22
0
def investments():
   new_inv_form = NewInvestmentForm()
   if new_inv_form.submit3.data and new_inv_form.validate():
      new_investment = Investment(title=new_inv_form.title.data, category=new_inv_form.category.data)
      db.session.add(new_investment)
      db.session.commit()

      flash('New investment created!')
      return redirect(url_for('investments'))

   form = UploadFormInvestments()
   investments = Investment.query.all()
   form.investment.choices = [(inv.id, inv.title) for inv in investments]
   if form.submit1.data and form.validate():
      new_position = Position(investment=form.investment.data, date=form.date.data, net_amount=form.net_amount.data, gross_amount=form.gross_amount.data)
      db.session.add(new_position)
      db.session.commit()

      flash('New position inserted!')
      return redirect(url_for('investments'))

   goalForm = GoalForm()
   if goalForm.submit.data and goalForm.validate():
      new_goal= InvestmentGoal(amount=goalForm.amount.data, year=date.today().year)
      db.session.add(new_goal)
      db.session.commit()

      flash('New investment goal set!')
      return redirect(url_for('investments'))

   goal = InvestmentGoal.query.filter(InvestmentGoal.year == date.today().year).first()
   if goal:
      goalForm = None   

   #Using session to store the dates used from the last 
   if "init_date_inv" not in session:
      session["init_date_inv"] = date.today().replace(day=1, month=1).strftime("%d%m%Y")
      session["end_date_inv"] = date.today().strftime("%d%m%Y")

   form_date = DatesForm(session["init_date_inv"], session["end_date_inv"])
   if form_date.submit2.data and form_date.validate():
      form_date.initial_date.data = form_date.initial_date.data
      form_date.end_date.data = form_date.end_date.data
      session["init_date_inv"] = form_date.initial_date.data.strftime("%d%m%Y")
      session["end_date_inv"] = form_date.end_date.data.strftime("%d%m%Y")
   elif request.method == 'GET':
      form_date.initial_date.data = datetime.strptime(session["init_date_inv"], "%d%m%Y").date()
      form_date.end_date.data = datetime.strptime(session["end_date_inv"], "%d%m%Y").date()

   try:
      positions_df = pd.read_sql(Position.query.filter((Position.date >= datetime.strptime(session["init_date_inv"], "%d%m%Y")) & (Position.date <= datetime.strptime(session["end_date_inv"], "%d%m%Y"))).statement, db.session.bind) 
      investments_df = pd.read_sql(Investment.query.statement, db.session.bind) 
      investments_df = pd.merge(positions_df, investments_df, how = 'left', left_on = 'investment', right_on = 'id')
      views = get_views_investment(investments_df)
   except:
      views = None

   return render_template('investments.html', 
                           new_inv_form=new_inv_form, 
                           form=form, 
                           form_date=form_date, 
                           goalForm=goalForm,
                           active_page = 'investments',
                           views = views)
Exemple #23
0
    def update_fundingconnections(connections, ftype, direction):
        # Delete and connections that have been removed.
        new_connections = [
            connection['id'] for connection in connections if connection['id']
        ]
        # TODO: See if you can make this generic to handle any set of connections for simplicity.
        # TODO: Maybe list comprehensions in stead depending on how cascade='delete-orphan' works.
        if ftype is 'investment':
            if direction is 'given':
                for connection in entity.investments_made:
                    if connection.id not in new_connections:
                        db.delete(connection)
            elif direction is 'received':
                for connection in entity.investments_received:
                    if connection.id not in new_connections:
                        db.delete(connection)
        elif ftype is 'grant':
            if direction is 'given':
                for connection in entity.grants_given:
                    if connection.id not in new_connections:
                        db.delete(connection)
            elif direction is 'received':
                for connection in entity.grants_received:
                    if connection.id not in new_connections:
                        db.delete(connection)
        db.commit()

        for connection in connections:
            if connection['id']:
                # Connection exists, update amount and year.
                oldconnection = Fundingconnection.query.get(connection['id'])
                if oldconnection.amount != connection['amount']:
                    oldconnection.amount = connection['amount']
                    app.logger.debug('UPDATING ' + ftype + ' AMOUNT: ' +
                                     str(oldconnection.amount))
                if oldconnection.year != connection['year']:
                    oldconnection.year = connection['year']
                    app.logger.debug('UPDATING ' + ftype + ' YEAR: ' +
                                     str(oldconnection.year))
            elif 'entity_id' in connection:
                # Connection doesn't exist, create it connect entities.
                otherentity = Entity.query.get(connection['entity_id'])
                if ftype is 'investment':
                    newconnection = Investment(connection['amount'],
                                               connection['year'])
                    if direction is 'given':
                        entity.investments_made.append(newconnection)
                        otherentity.investments_received.append(newconnection)
                    elif direction is 'received':
                        entity.investments_received.append(newconnection)
                        otherentity.investments_made.append(newconnection)
                elif ftype is 'grant':
                    newconnection = Grant(connection['amount'],
                                          connection['year'])
                    if direction is 'given':
                        entity.grants_given.append(newconnection)
                        otherentity.grants_received.append(newconnection)
                    elif direction is 'received':
                        entity.grants_received.append(newconnection)
                        otherentity.grants_given.append(newconnection)
        db.commit()
Exemple #24
0
def populate_db() -> User:
    # Users
    while True:
        guest_name = get_fake_name_from_buffer(r)
        try:
            guest = get_or_create_user(guest_name, guest=True)
        except (IntegrityError, ValueError):
            db.session.rollback()
        else:
            break

    user2 = get_or_create_user("Fryderyk Pawlak")
    user3 = get_or_create_user("Karina Tomaszewska")
    user4 = get_or_create_user("Jacek Chmiel")
    user5 = get_or_create_user("Honorata Wieczorek")

    # Workers
    worker1 = Worker(position="Visitor", admin=True, user_id=guest.id)
    worker2 = Worker(position="Site Manager", admin=True, user_id=user2.id)
    worker3 = Worker(position="Project Manager", admin=True, user_id=user3.id)
    worker4 = Worker(position="Site Engineer", admin=False, user_id=user4.id)
    worker5 = Worker(position="Quantity Engineer",
                     admin=False,
                     user_id=user5.id)

    # Tasks
    description = "Get to know eCon"
    task1 = Task(
        description=description,
        deadline=date.today() + timedelta(days=2),
        priority=5,
        orderer=worker2,
        executor=worker1,
    )
    task2 = Task(
        description="Very important task",
        deadline=date.today() + timedelta(days=2),
        priority=5,
        orderer=worker2,
        executor=worker3,
    )
    task3 = Task(
        description="Less important task",
        deadline=date.today() + timedelta(days=1),
        priority=2,
        orderer=worker3,
        executor=worker2,
    )

    # Investment
    invest = Investment(
        name="Warsaw Skyscraper",
        description="Office building with reinforced concrete structure.",
    )
    invest.workers.append(worker1)
    invest.workers.append(worker2)
    invest.workers.append(worker3)
    invest.workers.append(worker4)
    invest.workers.append(worker5)
    invest.tasks.append(task1)
    invest.tasks.append(task2)
    invest.tasks.append(task3)
    db.session.add(invest)
    db.session.commit()

    # Task notification
    notification = create_notification(
        worker_id=guest.workers.first().id,
        n_type="task",
        description=
        f"You have a new task: '{description}' from {user2.username}",
    )
    add_notification(r, notification)

    return guest