Add classmethod to get categories and their expenses and revenues from operations.

This commit is contained in:
Alexis Lahouze 2015-06-15 13:03:16 +02:00
parent d52c387912
commit cc79b39cbb
2 changed files with 31 additions and 1 deletions

View File

@ -15,7 +15,8 @@
along with Accountant. If not, see <http://www.gnu.org/licenses/>.
"""
from sqlalchemy import distinct, func, cast, extract
from sqlalchemy import distinct, func, case, cast, extract
from accountant import db

View File

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