From 0bdc9d5ef20efa20e4330a9180aef008a9c5a78b Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Sat, 13 Jun 2015 01:18:56 +0200 Subject: [PATCH] Add get method to have an account at a specific date or for a range. --- accountant/api/models/accounts.py | 60 +++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/accountant/api/models/accounts.py b/accountant/api/models/accounts.py index 0255b8d..a4de255 100644 --- a/accountant/api/models/accounts.py +++ b/accountant/api/models/accounts.py @@ -14,11 +14,15 @@ You should have received a copy of the GNU Affero General Public License along with Accountant. If not, see . """ +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