Ejemplo n.º 1
0
def save_category_options():
    try:
        data = request.form
        # Setting category limit
        limit_attributes = {
            'user_id': g.user.user_id,
            'category_id': int(data['cat']),
            'value': float(data.get('limit', 0) or 0),
        }

        limit = Limit.get(user_id=g.user.user_id,
                          category_id=limit_attributes['category_id'])
        if data.get('setLimit') and limit_attributes['value'] > 0:
            if limit is None:
                add_to_db(Limit(), **limit_attributes)
            else:
                limit.value = limit_attributes['value']
                db_session.commit()
        else:
            if limit is not None:
                db_session.delete(limit)
                db_session.commit()

        return HttpResponse('Options saved!', status=200)
    except BadRequestKeyError as e:
        return HttpErrorResponse(e, 'Unable to save the options.', status=400)
Ejemplo n.º 2
0
def register():
    if request.method == 'POST':
        name = request.form.get('txtName')
        fun_fact = request.form.get('txtFunFact')
        tribe = request.form.get('txtTribe')
        image_file = request.files['fileToUpload']
        job_title = request.form.get('txtJobTitle')

        filename = secure_filename(image_file.filename)
        image_file.save(os.path.join('Images', filename))
        models.add_to_db(str(name), str(fun_fact), str(tribe), filename, str(job_title))

        return '<h1> Success </h1>'

    return render_template('UploadImage.html')
Ejemplo n.º 3
0
def set_current_user():
    test_user = add_to_db(User(), first_name="Test", last_name="User", email="*****@*****.**")
    def handler(sender, **kwargs):
        g.user = test_user  # User.get(user_id=1)
    with appcontext_pushed.connected_to(handler, app):
        with app.app_context():
            yield
Ejemplo n.º 4
0
def test_get_transactions(client):
    def json_verifier(response, number_of_transactions):
        data = json.loads(response.data.decode('utf-8'))
        assert len(data.get('transactions', [])) == number_of_transactions

    with set_current_user():
        response = client.get('/budgeto/api/transactions')
        assert response.status_code == 200
        json_verifier(response, 0)

        add_to_db(Transaction(),
                  description='Test de transaction',
                  amount=10.55,
                  date=date.today(),
                  bank_id=2,
                  user_id=g.user.user_id)

        response = client.get('/budgeto/api/transactions')
        assert response.status_code == 200
        json_verifier(response, 1)
Ejemplo n.º 5
0
def put_transactions(json_data, user):
    """Save a list of transactions into the database
    Args:
        json_data : str The json containing the bank and the transactions to add
        user : User The user to add to
    Returns:
        The number of transactions added
    """
    bank = Bank.get(name=json_data.get('bank'))
    if bank is None:
        raise ValueError('Bank not supported.')

    added_transactions = 0
    for t in json_data.get('transactions', []):
        transaction = set_attributes(Transaction(),
                                     user_id=user.user_id,
                                     bank_id=bank.bank_id)
        add_to_db(transaction, **t)
        added_transactions += 1

    return added_transactions
Ejemplo n.º 6
0
def transactions_fetcher():
    truncate = lambda data, max: (data[:max - 3] + '...') if len(
        data) > max - 3 else data

    transactions_count = 0
    transactions = json.loads(request.form['transactions'])
    for transaction in transactions:
        try:
            # Getting fields
            attributes = {
                'user':
                g.user,
                'bank':
                Bank.get(name=transaction.get('bank')),
                'description':
                truncate(transaction.get('desc', ''), 256),
                'amount':
                float(transaction.get('amount', '0').replace(',', '.') or 0),
                'date':
                datetime.strptime(transaction.get('date'), '%d-%m-%Y')
                if transaction.get('date') else datetime.today()
            }
            # Fields validation
            if not attributes['description'] or not attributes['bank']:
                continue
            if attributes['date'] > datetime.today():
                attributes['date'] = datetime.today()
            # Trying to find a category
            category = Categorizer.find_category(attributes['description'])
            # Creating transaction
            db_transaction = Transaction.get(**attributes)
            if db_transaction is None:
                db_transaction = add_to_db(Transaction(), **attributes)
                transactions_count += 1
            # Finding or updating category
            if category is not None:
                db_transaction.category = category
                db_session.commit()
        except Exception as e:
            pass  # Skip this transaction

    return HttpResponse('Transactions fetched.', {'count': transactions_count},
                        status=200)
Ejemplo n.º 7
0
def create_keywords():
    values = request.values['keyword'].split(',')
    keywords = Keyword.get_all(Keyword.value.in_(values))
    if len(keywords) == 0:
        keywords = [add_to_db(Keyword(), value=v) for v in values]
        return HttpResponse(
            {
                'keywords': [{
                    'value': k.value,
                    'id': k.keyword_id
                } for k in keywords]
            }, 202)
    else:
        if len(keywords[0].categories) > 0:
            return HttpResponse(
                'Keyword "{0}" already exists in category "{1}"!'.format(
                    keywords[0].value, keywords[0].categories[0].name), 302)
        else:
            return HttpResponse(
                'Keyword "{0}" already exists!'.format(keywords[0].value), 302)
Ejemplo n.º 8
0
def transactions():
    # Retrieve user transactions
    if request.method == 'GET':
        transactions = Transaction.filter(user_id=g.user.user_id).order_by(
            Transaction.date.desc()).all()
        return make_response(to_json(transactions))

    elif request.method in ['PUT', 'POST']:
        data = request.get_json()
        # Allow to insert new transactions
        if request.method == 'PUT':
            try:
                attributes = get_transaction_attributes(data)
                transaction = add_to_db(Transaction(), **attributes)
                return HttpResponse(transaction.as_dict(), status=201)
            except Exception as e:
                return HttpErrorResponse(
                    e,
                    'Unable to add the transaction. Please try again later.',
                    status=400)

        # Allow to edit a transaction
        elif request.method == 'POST':
            transaction = Transaction.get(
                user_id=g.user.user_id, transaction_id=data['transaction_id'])
            if transaction is not None:
                try:
                    from endless import db_session
                    attributes = get_transaction_attributes(data)
                    set_attributes(transaction, **attributes)
                    db_session.commit()
                    return HttpResponse(transaction.as_dict(), status=201)
                except Exception as e:
                    return HttpErrorResponse(
                        e,
                        'Unable to add the transaction. Please try again later.',
                        status=400)
            else:
                return HttpResponse(
                    "Unable to edit the transaction. Please try again later.",
                    status=500)
Ejemplo n.º 9
0
 def generate_from_description(cls, description=''):
     """Create a new keyword from the description of a transaction"""
     if description != '':
         if len(cls.get_all(Keyword.description == description)) == 0:
             from models import add_to_db
             add_to_db(Keyword(), description=description)
Ejemplo n.º 10
0
 def add_keyword(name):
     from models import Keyword
     from models import add_to_db
     add_to_db(Keyword(), value=name)