diff --git a/accountant/models/operations.py b/accountant/models/operations.py index 5489698..0608bbf 100644 --- a/accountant/models/operations.py +++ b/accountant/models/operations.py @@ -134,22 +134,33 @@ class Operation(db.Model): return query @classmethod - def get_categories_for_range(cls, account, begin, end): - """Get category list for a specific time period.""" + def query_category_incomes(cls, account, begin=None, end=None): + """Return a query for categories with expenses, revenues and income for + a specific account and a specific time period.""" if isinstance(account, (int, str)): account_id = account else: account_id = account.id query = db.session.query( - cls.category, - db.func.sum( - db.case([(db.func.sign(cls.value) == -1, cls.value)], else_=0) + cls.category.label('category'), + db.func.coalesce( + db.func.sum( + cls.value + ).filter( + db.func.sign(cls.value) == -1 + ), + 0 ).label("expenses"), - db.func.sum( - db.case([(db.func.sign(cls.value) == 1, cls.value)], else_=0) + db.func.coalesce( + db.func.sum( + cls.value + ).filter( + db.func.sign(cls.value) == 1 + ), + 0 ).label("revenues"), - db.func.sum(cls.value).label("balance") + db.func.sum(cls.value).label("income") ).filter( cls.account_id == account_id ).order_by( diff --git a/accountant/views/accounts.py b/accountant/views/accounts.py index 093e3df..2719fe9 100644 --- a/accountant/views/accounts.py +++ b/accountant/views/accounts.py @@ -326,8 +326,11 @@ class CategoryResource(Resource): """Get account category balances for a specific date range.""" data = range_parser.parse_args() + # FIXME Alexis Lahouze 2017-05-23 check data. - return Operation.get_categories_for_range(account_id, **data).all() + return list(result_as_dicts( + Operation.query_category_incomes(account_id, **data) + )), 200 @ns.route('//daily_balances')