From 133f789c6493388cc7428441ed1aa3c14580a5f1 Mon Sep 17 00:00:00 2001 From: Mattia Mascarello Date: Thu, 16 May 2024 11:30:42 +0200 Subject: [PATCH] refactor: sort birthdays by remaining time until next birthday This commit refactors the `list_birthday` function in `main.py` to sort the birthdays by the remaining time until the next birthday. It introduces a new helper function `sort_close` that calculates the remaining time until the next birthday for each birthday in the list. The birthdays are then sorted based on this calculated value. --- main.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index efd0c89..937498e 100644 --- a/main.py +++ b/main.py @@ -255,13 +255,21 @@ async def end(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await start(update, context) return ConversationHandler.END +def sort_close(b: Birthday) -> int: + now = datetime.datetime.now() + datetime_bd = datetime.datetime(now.year, b.birth.month, b.birth.day) + if datetime_bd < now: + datetime_bd = datetime.datetime(now.year + 1, b.birth.month, b.birth.day) + return (datetime_bd - now).days async def list_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE): db_user_ping(update) """List all the birthdays in the database""" global session - birthdays = session.query(Birthday).filter(Birthday.user_id == update.message.from_user.id).order_by( - Birthday.last_name).all() + today = datetime.datetime.now().date() + birthdays = session.query(Birthday).filter(Birthday.user_id == update.message.from_user.id).all() + # now order the birthdays by the remaining time until the next birthday + birthdays = sorted(birthdays, key=sort_close) reply_keyboard = [[ InlineKeyboardButton("🏠 Home", callback_data="home") # go back to the main menu ]]