[Plugin] balance: Fixed controller

This commit is contained in:
Ferdinand Thiessen 2020-11-02 03:29:29 +01:00
parent d07aa977b5
commit d1fcbcf68f
2 changed files with 18 additions and 16 deletions

View File

@ -6,6 +6,7 @@ class ModelSerializeMixin:
"""Mixin class used for models to serialize them automatically """Mixin class used for models to serialize them automatically
Ignores private and protected members as well as members marked as not to publish (name ends with _) Ignores private and protected members as well as members marked as not to publish (name ends with _)
""" """
def serialize(self): def serialize(self):
"""Serialize class to dict """Serialize class to dict
Returns: Returns:

View File

@ -1,16 +1,13 @@
from flaschengeist.models.user import User
from sqlalchemy import func from sqlalchemy import func
from datetime import datetime from datetime import datetime, timezone
from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequest
from flaschengeist import logger
from flaschengeist.database import db from flaschengeist.database import db
from flaschengeist.models.user import User
from .models import Transaction from .models import Transaction
from . import permissions from . import permissions
__attribute_limit = "balance_limit" __attribute_limit = "balance_limit"
@ -24,24 +21,28 @@ def get_limit(user: User) -> float:
return user.get_attribute(__attribute_limit, default=None) return user.get_attribute(__attribute_limit, default=None)
def get(user, start: datetime, end: datetime): def get(user, start: datetime = None, end: datetime = None):
if not start:
start = datetime.fromtimestamp(0, tz=timezone.utc)
if not end:
end = datetime.now(tz=timezone.utc)
credit = ( credit = (
db.session.query(func.sum(Transaction.amount)) db.session.query(func.sum(Transaction.amount))
.filter(Transaction.receiver == user) .filter(Transaction.receiver_ == user)
.filter(start <= Transaction.time) .filter(start <= Transaction.time)
.filter(Transaction.time <= end) .filter(Transaction.time <= end)
.scalar() .scalar()
) or 0 ) or 0
logger.debug(credit)
if credit is None:
credit = 0
debit = ( debit = (
db.session.query(func.sum(Transaction.amount)) db.session.query(func.sum(Transaction.amount))
.filter(Transaction.sender == user and start <= Transaction.time <= end) .filter(Transaction.sender_ == user)
.all()[0][0] .filter(start <= Transaction.time)
) .filter(Transaction.time <= end)
if debit is None: .scalar()
debit = 0 ) or 0
return credit, debit, credit - debit return credit, debit, credit - debit
@ -65,7 +66,7 @@ def send(sender: User, receiver, amount: float, author: User):
): ):
raise BadRequest("Limit exceeded") raise BadRequest("Limit exceeded")
transaction = Transaction(sender=sender, receiver=receiver, amount=amount, author=author) transaction = Transaction(sender_=sender, receiver_=receiver, amount=amount, author_=author)
db.session.add(transaction) db.session.add(transaction)
db.session.commit() db.session.commit()