Fix account status and balance query when no operation in timerange.

This commit is contained in:
Alexis Lahouze 2015-07-10 14:27:07 +02:00
parent b31e6528ca
commit 0e32f5f696

View File

@ -56,46 +56,66 @@ class Account(db.Model):
else:
account_id = account.id
current = begin if end is None else end
end = end if end else begin
balance_query = session.query(
Operation.account_id,
func.sum(
case(
[(func.sign(Operation.value) == -1, Operation.value)],
else_=0
)
).label("expenses"),
func.sum(
case(
[(func.sign(Operation.value) == 1, Operation.value)],
else_=0
)
).label("revenues"),
func.sum(Operation.value).label("balance")
).filter(
Operation.operation_date >= str(begin),
Operation.operation_date <= str(end)
).group_by(
Operation.account_id
).subquery()
status_query = session.query(
cls.id,
func.sum(Operation.value).label("future"),
func.sum(
case(
[(Operation.pointed, Operation.value,)],
else_=0
)
).label("pointed"),
func.sum(
case(
[(Operation.operation_date <= str(end), Operation.value,)],
else_=0
)
).label("current"),
).group_by(
cls.id
).subquery()
query = session.query(
cls,
func.sum(Operation.value).label("future"),
func.sum(case([(Operation.pointed,
Operation.value,)],
else_=0)).label("pointed"),
func.sum(case([(Operation.operation_date <= str(current),
Operation.value,)],
else_=0)).label("current")
).group_by(cls.id)
if end:
subquery = session.query(
Operation.account_id,
func.sum(case([(func.sign(Operation.value) == -1,
Operation.value)],
else_=0)).label("expenses"),
func.sum(case([(func.sign(Operation.value) == 1,
Operation.value)],
else_=0)).label("revenues"),
func.sum(Operation.value).label("balance")
).filter(
Operation.operation_date >= begin,
Operation.operation_date <= end
).group_by(
Operation.account_id
).subquery()
base_subquery = query.subquery()
query = session.query(
base_subquery, subquery
).select_from(base_subquery, subquery).filter(
base_subquery.c.id == subquery.c.account_id,
base_subquery.c.id == account_id,
)
else:
query = query.filter(cls.id == account_id)
cls.id,
cls.name,
cls.authorized_overdraft,
func.coalesce(status_query.c.current, 0).label('current'),
func.coalesce(status_query.c.pointed, 0).label('pointed'),
func.coalesce(status_query.c.future, 0).label('future'),
func.coalesce(balance_query.c.expenses, 0).label('expenses'),
func.coalesce(balance_query.c.revenues, 0).label('revenues'),
func.coalesce(balance_query.c.balance, 0).label('balance'),
).outerjoin(
status_query, status_query.c.id == cls.id
).outerjoin(
balance_query, balance_query.c.account_id == cls.id
).filter(
cls.id == account_id
)
return query.one()