Rewrote category endpoint.

This commit is contained in:
Alexis Lahouze 2017-05-25 22:10:14 +02:00
parent b336b38518
commit 5fd9c81451
2 changed files with 23 additions and 9 deletions

View File

@ -134,22 +134,33 @@ class Operation(db.Model):
return query return query
@classmethod @classmethod
def get_categories_for_range(cls, account, begin, end): def query_category_incomes(cls, account, begin=None, end=None):
"""Get category list for a specific time period.""" """Return a query for categories with expenses, revenues and income for
a specific account and a specific time period."""
if isinstance(account, (int, str)): if isinstance(account, (int, str)):
account_id = account account_id = account
else: else:
account_id = account.id account_id = account.id
query = db.session.query( query = db.session.query(
cls.category, cls.category.label('category'),
db.func.coalesce(
db.func.sum( db.func.sum(
db.case([(db.func.sign(cls.value) == -1, cls.value)], else_=0) cls.value
).filter(
db.func.sign(cls.value) == -1
),
0
).label("expenses"), ).label("expenses"),
db.func.coalesce(
db.func.sum( db.func.sum(
db.case([(db.func.sign(cls.value) == 1, cls.value)], else_=0) cls.value
).filter(
db.func.sign(cls.value) == 1
),
0
).label("revenues"), ).label("revenues"),
db.func.sum(cls.value).label("balance") db.func.sum(cls.value).label("income")
).filter( ).filter(
cls.account_id == account_id cls.account_id == account_id
).order_by( ).order_by(

View File

@ -326,8 +326,11 @@ class CategoryResource(Resource):
"""Get account category balances for a specific date range.""" """Get account category balances for a specific date range."""
data = range_parser.parse_args() 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('/<int:account_id>/daily_balances') @ns.route('/<int:account_id>/daily_balances')