diff --git a/bot/handlers/report.py b/bot/handlers/report.py index 5cbadcf..3c92665 100644 --- a/bot/handlers/report.py +++ b/bot/handlers/report.py @@ -109,6 +109,24 @@ async def group_by_day(cb: CallbackQuery, session: Session): await cb.message.answer(msg) +@router.callback_query(Text('by_month')) +async def group_by_month(cb: CallbackQuery, session: Session): + await cb.answer() + + user = user_service.get_user_by_id( + user_id=cb.from_user.id, + session=session, + ) + + rows = report_service.get_report_by_month( + user=user, + session=session, + ) + for msg in chunkineze(rows, chunk_size=50): + if cb.message: + await cb.message.answer(msg) + + @router.callback_query(Text('by_category')) async def group_by_category(cb: CallbackQuery, session: Session): await cb.answer() diff --git a/bot/keyboards.py b/bot/keyboards.py index 6058bc1..4c403bb 100644 --- a/bot/keyboards.py +++ b/bot/keyboards.py @@ -12,6 +12,7 @@ f'Последние {config.last} записей': 'last_n', 'Список расходов за выбранный день': 'custom_day', 'Группировка по дню': 'by_day', + 'Группировка по месяцу': 'by_month', 'Группировка по категории': 'by_category', } diff --git a/bot/migrations/versions/09d3b6f33b87_report_by_month_release.py b/bot/migrations/versions/09d3b6f33b87_report_by_month_release.py new file mode 100644 index 0000000..1118f7c --- /dev/null +++ b/bot/migrations/versions/09d3b6f33b87_report_by_month_release.py @@ -0,0 +1,30 @@ +"""Report by month release + +Revision ID: 09d3b6f33b87 +Revises: 277fe7039415 +Create Date: 2023-12-08 22:48:55.609781 + +""" +from alembic import op + + +# revision identifiers, used by Alembic. +revision = '09d3b6f33b87' +down_revision = '277fe7039415' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + msg = ( + 'Обновление:' + '\n\n' + 'Доступна группировка по месяцу для отчета' + ) + stmt = f"insert into releases(id, message, is_broadcasted) values (7, '{msg}', 0)" + op.execute(stmt) + + +def downgrade() -> None: + stmt = 'delete from releases where id = 7' + op.execute(stmt) diff --git a/bot/services/report_service.py b/bot/services/report_service.py index 1a0eff8..f504c8e 100644 --- a/bot/services/report_service.py +++ b/bot/services/report_service.py @@ -29,6 +29,34 @@ def get_report_by_day( return [f'{row.tuple()[1]} | {row.tuple()[3]} {row.tuple()[2]}' for row in rows] +def get_report_by_month( + user: User, + session: Session, +) -> List[str]: + by_month_year = 'month_year' + stmt = ( + select( + Expense.user_id, + func.strftime('%m-%Y', Expense.cdate_tz).label(by_month_year), + Expense.unit, + func.sum(Expense.price).label('total'), + ) + .where( + Expense.user_id == user.id, + ~Expense.is_replenishment, + ) + .group_by(Expense.user_id, by_month_year, Expense.unit) + .order_by(by_month_year) + .subquery() + ) + + return [ + f'{getattr(r, by_month_year)} | {r.unit} {r.total}' for + r in + session.execute(select(stmt)) + ] + + def get_report_by_category( user: User, session: Session,