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
@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(

View File

@ -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('/<int:account_id>/daily_balances')