From 8536988b1a6a531d16fb1089b17efdb37aeceaa6 Mon Sep 17 00:00:00 2001 From: NguyenND Date: Tue, 2 Jun 2026 16:09:42 -0400 Subject: [PATCH] 06/02 Update add new balance option --- app/routes/accounts.py | 22 ++++++++++++++++++++-- app/templates/accounts/form.html | 14 ++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/app/routes/accounts.py b/app/routes/accounts.py index 8c61447..26fc7f2 100644 --- a/app/routes/accounts.py +++ b/app/routes/accounts.py @@ -2,8 +2,8 @@ from datetime import date from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify from flask_login import login_required from flask_wtf import FlaskForm -from wtforms import StringField, SelectField, TextAreaField, SubmitField -from wtforms.validators import DataRequired, Length, Optional +from wtforms import StringField, SelectField, TextAreaField, SubmitField, DecimalField +from wtforms.validators import DataRequired, Length, Optional, NumberRange from sqlalchemy import func, extract from app.extensions import db from app.models.account import Account @@ -44,6 +44,8 @@ class AccountForm(FlaskForm): color = StringField('Color', default='#4F81C7') icon = StringField('Icon', default='bi-bank') notes = TextAreaField('Notes', validators=[Optional(), Length(max=500)]) + opening_balance = DecimalField('Opening Balance', places=2, default=0, + validators=[Optional()]) submit = SubmitField('Save') @@ -103,7 +105,23 @@ def new(): balance=0, ) db.session.add(account) + db.session.flush() # get account.id before creating transaction + + opening = float(form.opening_balance.data or 0) + if opening != 0: + from app.models.transaction import Transaction + txn_type = 'income' if opening > 0 else 'expense' + db.session.add(Transaction( + account_id=account.id, + transaction_type=txn_type, + amount=abs(opening), + description='Opening Balance', + date=date.today(), + notes='Initial account balance', + )) + db.session.commit() + calc_balance(account.id) flash(f'Account "{account.name}" created.', 'success') return redirect(url_for('accounts.index')) return render_template('accounts/form.html', form=form, title='New Account', diff --git a/app/templates/accounts/form.html b/app/templates/accounts/form.html index cb1ee66..86d793c 100644 --- a/app/templates/accounts/form.html +++ b/app/templates/accounts/form.html @@ -53,6 +53,20 @@ {{ form.notes(class="form-control", rows=2, placeholder="Optional notes") }} + {% if not account %} +
+ {{ form.opening_balance.label(class="form-label fw-medium", style="font-size:13px;") }} +
+ {{ current_user.currency_symbol }} + {{ form.opening_balance(class="form-control", placeholder="0.00", id="openingBalance") }} +
+
+ Current real-world balance. Leave at 0 if you'll enter all transactions from scratch. + For credit cards, enter a negative value if you currently owe money (e.g. -500). +
+
+ {% endif %} +
{{ form.submit(class="btn btn-primary") }} Cancel