diff --git a/coffeebuddy/model.py b/coffeebuddy/model.py index e2659a2..92906ce 100644 --- a/coffeebuddy/model.py +++ b/coffeebuddy/model.py @@ -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. @@ -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() ) ) @@ -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("*")) diff --git a/tests/test_database.py b/tests/test_database.py index 7431119..fa96378 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -1,3 +1,5 @@ +from datetime import datetime, timedelta + import sqlalchemy.exc from . import TestCoffeebuddy @@ -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):