From cc79b39cbb3ff28d37fa7579c368d270a4d905a3 Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Mon, 15 Jun 2015 13:03:16 +0200 Subject: [PATCH] Add classmethod to get categories and their expenses and revenues from operations. --- accountant/api/models/entries.py | 3 ++- accountant/api/models/operations.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/accountant/api/models/entries.py b/accountant/api/models/entries.py index cd8e052..bb71687 100644 --- a/accountant/api/models/entries.py +++ b/accountant/api/models/entries.py @@ -15,7 +15,8 @@ along with Accountant. If not, see . """ -from sqlalchemy import distinct, func, cast, extract +from sqlalchemy import distinct, func, case, cast, extract + from accountant import db diff --git a/accountant/api/models/operations.py b/accountant/api/models/operations.py index d0dda60..d1d3c58 100644 --- a/accountant/api/models/operations.py +++ b/accountant/api/models/operations.py @@ -107,3 +107,32 @@ class Operation(db.Model): @classmethod def get(cls, session, id): return session.query(cls).filter(cls.id == id).one() + + @classmethod + def get_categories_for_range(cls, session, account, begin, end): + if isinstance(account, int) or isinstance(account, str): + account_id = account + else: + account_id = account.id + + query = session.query( + cls.category, + func.sum( + case([(func.sign(cls.value) == -1, cls.value)], else_=0) + ).label("expenses"), + func.sum( + case([(func.sign(cls.value) == 1, cls.value)], else_=0) + ).label("revenues"), + func.sum(cls.value).label("balance") + ).filter( + cls.account_id == account_id + ).filter( + cls.operation_date >= str(begin), + cls.operation_date <= str(end) + ).order_by( + cls.category + ).group_by( + cls.category + ) + + return query