Example #1
0
def transaction(tr_type):
    """Create new transaction."""

    if tr_type == 'minus':
        tr_type = True
    else:
        tr_type = False

    dbs = db.session

    form = TransactionForm()
    # form.tdate.data = date.today()
    form.account_id.choices = active_accounts(True)
    form.group_id.choices = active_groups(True)
    form.category_id.choices = active_categories(True)
    form.party_id.choices = active_parties(True)

    if form.validate_on_submit():
        tr = Transaction()
        tr.tdate = form.tdate.data
        tr.amount = round(float(form.amount.data), 2)
        tr.minus = tr_type
        tr.owner = current_user
        tr.account_id = form.account_id.data
        tr.group_id = form.group_id.data
        tr.category_id = form.category_id.data
        tr.party_id = form.party_id.data
        tr.comment = form.comment.data.strip()

        try:
            # Save transaction to databse
            dbs.add(tr)
            dbs.commit()
            # Increase time_used for account
            tr.account.times_used += 1

            # Increase times_used for group
            tr.group.times_used += 1

            # Increase times_used for category
            tr.category.times_used += 1

            # Increase times_used for party
            tr.party.times_used += 1

            # Subtract expense or add balance from balance
            if tr_type:
                # a.balance = a.balance - tr.amount
                tr.account.balance = tr.account.balance - tr.amount
            else:
                # a.balance = a.balance + tr.amount
                tr.account.balance = tr.account.balance + tr.amount

            dbs.commit()
            flash('Transaction created!', 'success')
            return redirect(url_for('main.index'))
        except IntegrityError:
            dbs.rollback()
            flash('Transaction was not created', 'warning')

    return render_template('transactions/transaction.html', form=form)