98 lines
2.8 KiB
Python
98 lines
2.8 KiB
Python
"""Module containing account related models."""
|
|
|
|
# vim: set tw=80 ts=4 sw=4 sts=4:
|
|
|
|
# pylint: disable=no-member,too-few-public-methods
|
|
from . import db
|
|
|
|
from .operations import Operation
|
|
|
|
|
|
class Account(db.Model):
|
|
"""Model class to handle accounts."""
|
|
# pylint: disable=invalid-name
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
name = db.Column(db.String(200), nullable=False)
|
|
authorized_overdraft = db.Column(db.Integer, nullable=True, default=0)
|
|
|
|
def __init__(self, name, authorized_overdraft):
|
|
self.name = name
|
|
self.authorized_overdraft = authorized_overdraft
|
|
|
|
@classmethod
|
|
def query(cls):
|
|
"""Return a query for this class method."""
|
|
return db.session.query(
|
|
cls
|
|
).order_by(
|
|
cls.name
|
|
)
|
|
|
|
def solds(self):
|
|
"""Return the balances of this account."""
|
|
return self.balances()
|
|
|
|
def balances(self):
|
|
"""Return the balances of this account."""
|
|
return db.session.query(
|
|
db.func.sum(Operation.value).label("future"),
|
|
db.func.sum(
|
|
db.case(
|
|
[(Operation.pointed,
|
|
Operation.value)],
|
|
else_=0
|
|
)
|
|
).label("pointed"),
|
|
db.func.sum(
|
|
db.case(
|
|
[(Operation.operation_date <= db.func.current_date(),
|
|
Operation.value)],
|
|
else_=0
|
|
)
|
|
).label("current"),
|
|
).filter(
|
|
Operation.account_id == self.id
|
|
).one()
|
|
|
|
def balance(self, begin, end):
|
|
"""Return the flow for a specific time period."""
|
|
return self.flow(begin, end)
|
|
|
|
def flow(self, begin, end):
|
|
"""Return the flow for a specific time period."""
|
|
query = db.session.query(
|
|
db.func.sum(
|
|
db.case(
|
|
[(db.func.sign(Operation.value) == -1, Operation.value)],
|
|
else_=0
|
|
)
|
|
).label("expenses"),
|
|
db.func.sum(
|
|
db.case(
|
|
[(db.func.sign(Operation.value) == 1, Operation.value)],
|
|
else_=0
|
|
)
|
|
).label("revenues"),
|
|
db.func.sum(Operation.value).label("balance")
|
|
).filter(
|
|
Operation.account_id == self.id,
|
|
)
|
|
|
|
if begin:
|
|
query = query.filter(Operation.operation_date >= str(begin))
|
|
|
|
if end:
|
|
query = query.filter(Operation.operation_date <= str(end))
|
|
|
|
return query.one()
|
|
|
|
@db.validates('authorized_overdraft')
|
|
# pylint: disable=no-self-use
|
|
def validate_authorized_overdraft(self, key, authorized_overdraft):
|
|
"""Validator for authorized_overdraft : must be negative."""
|
|
del key
|
|
|
|
assert authorized_overdraft <= 0
|
|
|
|
return authorized_overdraft
|