Пример #1
0
def example_data():
    """Create example data to test the database"""

    password = password_hash('0000')

    u1 = User(fullname="Test Person",
              email="*****@*****.**",
              password=password,
              payer_seller="Payer")

    u2 = User(fullname="Test Person2",
              email="*****@*****.**",
              password=password,
              account_id='acct_19rvdXFByeZDKBFc',
              secret_key='sk_test_FMu4VqVNvb1oqZAWYTBh3kvj',
              payer_seller="Seller")

    u3 = User(fullname="Test Person3",
              email="*****@*****.**",
              password=password,
              payer_seller="Payer")

    u4 = User(fullname="Test Person4",
              email="*****@*****.**",
              account_id='acct_19rvdXFByeZDKBFc',
              secret_key='sk_test_FMu4VqVNvb1oqZAWYTBh3kvj',
              password=password,
              payer_seller="Seller")

    new_trans1 = Transaction(payer_id=1,
                             seller_id=2,
                             is_signed=False,
                             payment_received=False,
                             date=datetime(2017, 06, 06, 0, 0),
                             amount=1000,
                             currency='usd',
                             status='pending approval from seller')

    new_trans2 = Transaction(payer_id=3,
                             seller_id=4,
                             is_signed=False,
                             payment_received=False,
                             date=datetime(2017, 11, 11, 0, 0),
                             amount=1000,
                             currency='usd',
                             status='pending approval from seller')

    db.session.add_all([u1, u2, u3, u4, new_trans1, new_trans2])
    db.session.commit()
Пример #2
0
    def add_split_transactions(cls, trx_date: date, budget_names: list,
                               thing: str, income: int, outcome: int):
        budgets = cls._get_budgets_by_names(budget_names, trx_date)
        total_left = sum(map(lambda x: x.left, budgets))
        cur_outcome = outcome - income
        if cur_outcome > total_left:
            raise BudgetAmountExceedLimitError(total_left)

        trxs = []
        for budget in budgets:
            if cur_outcome == 0:
                break

            left = budget.left
            if left == 0:
                continue

            trx_outcome = cur_outcome
            if trx_outcome > left:
                trx_outcome = left
                cur_outcome -= left
            else:
                cur_outcome = 0
            trx = Transaction(date=trx_date,
                              budget_id=budget.id,
                              thing=thing,
                              income=0,
                              outcome=trx_outcome)
            cls.save(trx)
            trxs.append(trx)
        return trxs
Пример #3
0
def viewUpload():
    if request.method == 'GET':
        return render_template('upload.html')

    elif request.method == 'POST':
        # get file
        file = request.files['transactions_file']
        content = file.read()

        for line in content.splitlines():
            transaction = Transaction()
            for index, item in enumerate(str(line)[2:].split(',')):

                # Date
                if index == 0:
                    transaction.date = item
                elif index == 1:
                    transaction.amount = float(item[1:-1])
                elif index == 2:
                    transaction.name = item[:-1]

            # add transaction
            model.AddTransaction(transaction)

        # complete redirect to upload page
        return render_template('upload.html')
def nova_transakcija(user):
    #pridobi podatke za transakcijo in jo izvede
    placilo = placilo_ali_priliv()
    amount = pridobi_amount(user, placilo)
    note = pridobi_note()
    transakcija = Transaction(amount, note, expense=placilo)
    user.izvedi_transakcijo(transakcija)
    print('Uspešno ste izvedli transakcijo!')
def preveri_priv():
    priliv = bottle.request.forms['priliv']
    opomba = bottle.request.forms['opomba1']
    if model.je_stevilka(priliv):
        transakcija = Transaction(float(priliv), opomba, False)
        prijavljen.izvedi_transakcijo(transakcija)
        return bottle.redirect('/osnovna_stran/')
    else:
        return bottle.template('narobe.tpl', link='/priliv/')
def preveri_nak():
    nakazilo = bottle.request.forms['nakazilo']
    opomba = bottle.request.forms['opomba']
    if model.je_stevilka(nakazilo):
        if prijavljen.account.stanje < float(nakazilo):
            return bottle.template('premalo_denarja.tpl')
        else:
            transakcija = Transaction(float(nakazilo), opomba, True)
            prijavljen.izvedi_transakcijo(transakcija)
            return bottle.redirect('/osnovna_stran/')
    else:
        return bottle.template('narobe.tpl', link='/placilo/')
Пример #7
0
def create_transaction(amount, date, merchant_name, user, account_id):
    """Create and return a new transaction."""

    transaction = Transaction(amount=amount,
                              date=date,
                              merchant_name=merchant_name,
                              user=user,
                              account_id=account_id)

    db.session.add(transaction)
    db.session.commit()

    return transaction
Пример #8
0
 def add_transaction(cls, trx_date: date, budget_name: str, thing: str,
                     income: int, outcome: int):
     budget = budget_service.BudgetService.find_by_name(
         budget_name, trx_date)
     if outcome > budget.left + income:
         raise BudgetAmountExceedLimitError(budget.left)
     trx = Transaction(date=trx_date,
                       budget_id=budget.id,
                       thing=thing,
                       income=income,
                       outcome=outcome)
     cls.save(trx)
     return trx
Пример #9
0
def create_transactions(photo_id, user_id, purchased=True):
    """Creates new transaction"""

    purchase_date = datetime.today()
    trans = Transaction(photo_id=photo_id,
                        user_id=user_id,
                        purchase_date=purchase_date,
                        buy_price=buy_price,
                        purchased=purchased)

    db.session.add(trans)
    db.session.commit()

    return trans
Пример #10
0
def convertAmount():
    # convert amount
    usAmount = request.json.get('usamount', '')
    #rate = float(request.json.get('rateSet'))
    rate = session.query(Rate).first()
    # add a if to check rate
    # calculate gd amount
    gdAmount = float(usAmount) * rate.convertRate
    transaction = Transaction(usAmount=usAmount,
                              gdAmount=gdAmount,
                              rate=rate.convertRate,
                              user_id=current_user.id)
    session.add(transaction)
    session.commit()
    return jsonify({'message': 'successfully added', 'gdAmount': gdAmount})
Пример #11
0
def create_investment():
    """API endpoint to create new investment transactions.
       Note: A company/investment must be created on the investments 
       table before recording a transaction."""

    data = request.get_json()

    new_investment = Transaction(company_id=data["company_id"],
                                 asset=data["asset"],
                                 date=datetime.datetime.utcnow(),
                                 cost_per_share=data["cost_per_share"],
                                 num_shares=data["num_shares"])
    db.session.add(new_investment)
    db.session.commit()

    return jsonify({"message": "New investment transaction."})
Пример #12
0
def order():
    data = request.json
    user = BaseAPI.get_session().user
    trx = Transaction(
        user=user,
        buyer_name=data["name"],
        address=data["address"],
        total_price=data["price"],
        status="Paid",
    )
    trx.save()
    item = Item.get(Item.sku == data["sku"])
    item.stock -= 1
    item.save()
    trx_item = TransactionItem(item=item, transaction=trx, qty=1)
    trx_item.save()
    return BaseAPI(None).respond(trx.to_dict())
Пример #13
0
def deserializer(csv_iterable):
    """
    Generator for converting csv to python
    Handle sparse data and yield
    Transaction model field order (same as csv)
    'id',
    'ts',
    'price',
    'amount',
    'sell',
    'asks',
    'bids',
    'd_high',
    'd_low',
    'd_vwap',
    'd_volume'
    """
    previous_transaction = None

    while True:
        identifier, ts, price, amount, sell, asks, bids, d_high, d_low, d_vwap, d_volume = next(
            csv_iterable)

        if not d_high or not d_low or not d_vwap or not d_volume:
            # Sparse data, set current daily values to previous one
            # Since it does not change that much
            d_high = previous_transaction.d_high
            d_low = previous_transaction.d_low
            d_vwap = previous_transaction.d_vwap
            d_volume = previous_transaction.d_volume

        if not ts or not sell:
            # Cannot do anything for this, passing
            yield None
        else:
            transaction = Transaction(identifier, ts, price, amount, sell,
                                      asks, bids, d_high, d_low, d_vwap,
                                      d_volume)

            yield transaction
            previous_transaction = transaction
Пример #14
0
def logout():
    """Allows the user to log out, ends the session."""

    # Provides a random number of transactions with random data, stores in db as uncategorized for use upon next login
    if session.get('user_id'):
        for i in range(random.randint(1, 10)):
            fin_transaction_id = ''.join(
                ["%s" % random.randint(0, 9) for num in range(0, 10)])
            # print(fin_transaction_id)
            amount = -float(("{0:.2f}".format(random.random() * 10)))
            # print(amount)
            account = random.choice(session.get('account_choices'))
            # print(account)
            fin_description = random.choice([
                'target', 'chick-fil-a', 'starbucks', 'amazon', 'safeway',
                'petco', 'chevron', 'home depot', 'blue bottle'
            ])
            # print(fin_description)
            transaction_date = random.randint(int(session.get('from_date')),
                                              int(round(time.time())))
            # print(transaction_date)

            # Add transactions to db, do inside for loop for each transaction
            newest_transactions = Transaction(
                fin_transaction_id=str(fin_transaction_id),
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)

            db.session.add(newest_transactions)

        # Commits info for all accounts at once to db
        db.session.commit()

        del session['user_id']

    return redirect('/')
Пример #15
0
def create_transaction(form):
    try:
        with create_session() as s:
            t = Transaction(form)

            entities = _get_legal_entities(
                [t.from_legal_entity, t.to_legal_entity], s)
            if len(entities) != 2:
                return 'Invalid entity ids'
            products = _get_products([t.product_sku], s)
            if len(products) != 1:
                return 'Invalid product sku'

            if _get_txns([t.id], s):
                return 'Existed'
            else:
                s.add(t)
                return t.id
    except:
        raise
        return 'Failed'
Пример #16
0
def generate():
    """Generate a transaction from value"""
    value = int(request.form["amount"])
    today = date.today().strftime("%Y-%m-%d")
    not_assigned = True

    while not_assigned:
        # Making sure there isn't any duplicate value
        add_value = randint(0, 999)  # Random 3 digit number for verification
        not_assigned = (Transaction.select().where(
            Transaction.created_at == date.today(),
            Transaction.amount == value + add_value,
        ).exists())

    transaction = Transaction(amount=value + add_value)
    transaction.save()
    print(transaction.created_at)

    return jsonify({
        "transaction_id": transaction.id,
        "amount": value + add_value,
        "status": "success",
    })
Пример #17
0
def generate():
    '''Generate a transaction from value'''
    value = int(request.form['amount'])
    today = date.today().strftime('%Y-%m-%d')
    not_assigned = True

    while not_assigned:
        #Making sure there isn't any duplicate value
        add_value = randint(0, 999)  #Random 3 digit number for verification
        not_assigned = Transaction.select()\
              .where(Transaction.created_at == date.today()\
                  , Transaction.amount == value+add_value)\
              .exists()

    transaction = Transaction(amount=value + add_value)
    transaction.save()
    print(transaction.created_at)

    return jsonify({
        'transaction_id': transaction.id,
        'amount': value + add_value,
        'status': 'success'
    })
Пример #18
0
def show_accounts():
    """Allows users to select and add accounts from their chosen institution."""

    customer_id = session.get('fin_id')
    # print(type(customer_id))
    institution_id = session.get('bank_id')

    # Gets info on ALL (getlist) checkboxed accounts
    # account_choice = request.form['']
    account_choice = request.args.getlist('select_accounts')
    # print(account_choice)

    # Save account_choice in session for use in getting transactions
    session['account_choice'] = account_choice

    # Gets previous account info for all accounts that has been saved in session
    all_accounts_info = session.get('account_choices')
    # print(all_accounts_info)
    # print(all_accounts_info['accounts'])

    # Stores info in db and activates only selected accounts
    for account in all_accounts_info['accounts']:
        # print(account['id'])
        # print(type(account['id']))
        if str(account['id']) in account_choice:
            account_id = str(account['id'])
            account_num = account['number']
            account_name = account['name']
            account_type = account['type']

            # Activate user accounts for daily transaction aggregation
            activate_customer_accounts(customer_id, institution_id, account_id,
                                       account_num, account_name, account_type)

            # Add new user's account info to db
            new_user_accounts = UserBankAccount(fin_account_id=int(account_id),
                                                user_id=session.get('user_id'),
                                                account_name=account_name,
                                                account_num=account_num,
                                                account_type=account_type)

            db.session.add(new_user_accounts)

            # Gets all transactions for the last 12 months for each account (so there is data to pull from for categorizing)
            # PREMIUM FINICITY SERVICE ONLY
            # get_historic_customer_transactions(customer_id, account_id)

    # Non-interactive refresh of customer transactions from all activated accounts
    refresh_customer_accounts(str(customer_id))

    # fromDate = January 10, 2000, gets all transactions Finicity has for a given user
    from_date = str(947462400)

    # Get all transactions for a certain customer within a given date range
    transactions = get_customer_transactions(customer_id, from_date)
    # print(transactions)

    # Loop through transactions to pick out the info that I want to store in the db
    for transaction in transactions['transactions']:
        if str(transaction['accountId']) in account_choice:
            fin_transaction_id = transaction['id']
            amount = transaction['amount']
            account = transaction['accountId']
            fin_description = transaction['memo']
            transaction_date = transaction['postedDate']

            # Add transactions to db, do inside for loop for each transaction
            new_user_transactions = Transaction(
                fin_transaction_id=fin_transaction_id,
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)
            db.session.add(new_user_transactions)

    # Commits info for all accounts at once to db
    db.session.commit()

    get_transactions()

    return redirect('/showunsortedtransactions')
Пример #19
0
def get_transactions():
    """Collects new transactions for a specific customer."""

    user_id = session.get('user_id')
    # print(user_id)
    user_object = User.query.filter(User.user_id == user_id).first()
    # print(user_object)
    customer_id = user_object.fin_id
    # print(customer_id)

    # Non-interactive refresh of customer transactions from all activated accounts
    refresh_customer_accounts(str(customer_id))

    # Set from_date as the timestamp of the last recieved transaction stored in the db
    recent_transact_object = Transaction.query.filter(
        Transaction.user_id == user_id).order_by(
            Transaction.transaction_date.desc()).first()
    # print(recent_transact_object)
    from_date = str(recent_transact_object.transaction_date)
    # print(from_date)
    session['from_date'] = from_date

    # Get new transactions from Finicity
    new_transactions = get_customer_transactions(str(customer_id), from_date)

    user_account_choice = UserBankAccount.query.filter(
        UserBankAccount.user_id == user_id).all()
    # print(user_account_choice)

    account_choices = []

    for account in user_account_choice:
        added_account = account.fin_account_id
        account_choices.append(added_account)

    session['account_choices'] = account_choices

    # print(account_choices)

    # Loop through transactions to pick out the info that I want to store in the db
    for transaction in new_transactions['transactions']:
        if str(transaction['accountId']) in account_choices:
            fin_transaction_id = transaction['id']
            amount = transaction['amount']
            account = transaction['accountId']
            fin_description = random.choice([
                'target', 'chick-fil-a', 'starbucks', 'amazon', 'safeway',
                'petco', 'chevron', 'home depot', 'blue bottle'
            ])
            transaction_date = transaction['postedDate']

            # Add transactions to db, do inside for loop for each transaction
            newest_transactions = Transaction(
                fin_transaction_id=str(fin_transaction_id),
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)

            db.session.add(newest_transactions)

    # Commits info for all accounts at once to db
    db.session.commit()