Add get method to have an account at a specific date or for a range.

This commit is contained in:
Alexis Lahouze 2015-06-13 01:18:56 +02:00
parent cdd776c7b8
commit 0bdc9d5ef2

View File

@ -14,11 +14,15 @@
You should have received a copy of the GNU Affero General Public License
along with Accountant. If not, see <http://www.gnu.org/licenses/>.
"""
from datetime import date
from sqlalchemy import func, case, cast
from sqlalchemy.orm import validates
from accountant import db
from .entries import Entry
from .operations import Operation
class Account(db.Model):
@ -46,5 +50,57 @@ class Account(db.Model):
return query
@classmethod
def get(cls, session, id):
return session.query(cls).filter(cls.id == id).one()
def get(cls, session, account, begin=date.today(), end=None):
if isinstance(account, int) or isinstance(account, str):
account_id = account
else:
account_id = account.id
current = begin if end is None else end
query = session.query(
cls,
func.sum(Operation.value).label("future"),
func.sum(case([(Operation.pointed,
Operation.value,)],
else_=0)).label("pointed"),
func.sum(case([(Operation.operation_date <= str(current),
Operation.value,)],
else_=0)).label("current")
).group_by(cls.id)
if end:
subquery = session.query(
Operation.account_id,
func.sum(case([(func.sign(Operation.value) == -1,
Operation.value)],
else_=0)).label("expenses"),
func.sum(case([(func.sign(Operation.value) == 1,
Operation.value)],
else_=0)).label("revenues"),
func.sum(Operation.value).label("balance")
).filter(
Operation.operation_date >= begin,
Operation.operation_date <= end
).group_by(
Operation.account_id
).subquery()
base_subquery = query.subquery()
query = session.query(
base_subquery, subquery
).select_from(base_subquery, subquery).filter(
base_subquery.c.id == subquery.c.account_id,
base_subquery.c.id == account_id,
)
else:
query = query.filter(cls.id == account_id)
return query.one()
@validates('authorized_overdraft')
def validate_authorized_overdraft(self, key, authorized_overdraft):
assert authorized_overdraft > 0
return authorized_overdraft