Skip to content

Commit

Permalink
Fix stats on coffee.html
Browse files Browse the repository at this point in the history
  • Loading branch information
hackenbergstefan committed Aug 18, 2024
1 parent bb5ee54 commit dc90107
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
15 changes: 11 additions & 4 deletions coffeebuddy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ def db_weekday(column) -> str:
return sqlalchemy.func.strftime("%w", column)


def db_date_format(column):
if flask.current_app.db.engine.name == "postgresql":
return sqlalchemy.func.to_char(column, "YYYY-MM-DD")
else:
return sqlalchemy.func.strftime("%Y-%m-%d", column)


def weekday(number):
"""
Helper to return the name of the weekday for given day number.
Expand Down Expand Up @@ -263,15 +270,15 @@ def drinks_last_weeks(
zip(
*db.session.execute(
db.select(
db.func.Date(Drink.timestamp).label("day"),
db_date_format(db.func.Date(Drink.timestamp)),
db.func.count(db.func.Date(Drink.timestamp)),
)
.where(
(Drink.userid == self.id)
& (db.func.Date(Drink.timestamp) >= since)
)
.group_by("day")
.order_by("day")
.group_by(db.func.Date(Drink.timestamp))
.order_by(db.func.Date(Drink.timestamp))
).all()
)
)
Expand Down Expand Up @@ -310,7 +317,7 @@ def drinks_last_weeks_all(since=timedelta(weeks=12)) -> Tuple[List[str], List[in

def drinks_avg_today(self) -> float:
db = flask.current_app.db
today_weekday = str(date.today().weekday())
today_weekday = str(date.today().isoweekday() % 7)

data = db.session.scalars(
db.select(db.func.count("*"))
Expand Down
31 changes: 31 additions & 0 deletions tests/test_database.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import datetime, timedelta

import sqlalchemy.exc

from . import TestCoffeebuddy
Expand Down Expand Up @@ -159,6 +161,35 @@ def test_by_tag_none_fails(self):
self.assertIsNone(User.by_tag(None))
self.assertIsNone(User.by_tag(b""))

def test_drinks_last_weeks(self):
from coffeebuddy.model import Drink

user1, _ = self.add_default_user()
user1.drinks.append(Drink(price=1))
self.db.session.commit()
self.assertEqual(
user1.drinks_last_weeks(group_by="day"),
((datetime.now().strftime("%Y-%m-%d"),), (1,)),
)

def test_drinks_avg_today(self):
from coffeebuddy.model import Drink

user1, _ = self.add_default_user()
user1.drinks.append(Drink(price=1))
self.db.session.commit()
self.assertEqual(user1.drinks_avg_today(), 1.0)
user1.drinks.extend(
(
Drink(price=1, timestamp=datetime.now() - timedelta(weeks=1)),
Drink(price=1, timestamp=datetime.now() - timedelta(weeks=1)),
Drink(price=1, timestamp=datetime.now() - timedelta(weeks=2)),
Drink(price=1, timestamp=datetime.now() - timedelta(weeks=3)),
)
)
self.db.session.commit()
self.assertEqual(user1.drinks_avg_today(), 1.25)


class TestModelDrink(TestCoffeebuddy):
def test_add_drink(self):
Expand Down

0 comments on commit dc90107

Please sign in to comment.