shopbot/bot/services/stats.py
2024-12-25 04:30:33 +03:00

93 lines
3.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import logging
from datetime import datetime, timedelta
from aiogram_dialog import DialogManager
from sqlalchemy import func, select
from sqlalchemy.exc import SQLAlchemyError
from shopbot.bot.database.db import async_session
from shopbot.bot.database.models import Account, UserModel
def _get_start_of_day():
return datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
async def get_admin_statistics(dialog_manager: DialogManager, **kwargs):
today_start = _get_start_of_day()
week_start = today_start - timedelta(days=7)
month_start = today_start - timedelta(days=30)
try:
async with async_session() as session:
async with session.begin():
total_sold_query = select(func.count(Account.id)).where(
Account.is_sold == True # noqa: E712
)
currently_for_sale_query = select(func.count(Account.id)).where(
Account.is_sold == False # noqa: E712
)
total_sales_query = select(func.sum(Account.price)).where(
Account.is_sold == True # noqa: E712
)
highest_sale_query = select(func.max(Account.price)).where(
Account.is_sold == True # noqa: E712
)
average_sale_query = select(func.avg(Account.price)).where(
Account.is_sold == True # noqa: E712
)
total_users_query = select(func.count(UserModel.id))
profit_today_query = select(func.sum(Account.price)).where(
Account.date_purchase >= today_start
)
profit_week_query = select(func.sum(Account.price)).where(
Account.date_purchase >= week_start
)
profit_month_query = select(func.sum(Account.price)).where(
Account.date_purchase >= month_start
)
(
total_sold,
currently_for_sale,
total_sales,
highest_sale,
average_sale,
total_users,
profit_today,
profit_week,
profit_month,
) = await asyncio.gather(
session.scalar(total_sold_query),
session.scalar(currently_for_sale_query),
session.scalar(total_sales_query),
session.scalar(highest_sale_query),
session.scalar(average_sale_query),
session.scalar(total_users_query),
session.scalar(profit_today_query),
session.scalar(profit_week_query),
session.scalar(profit_month_query),
)
return {
"total_sold": total_sold or 0,
"currently_for_sale": currently_for_sale or 0,
"total_sales": total_sales or 0.0,
"highest_sale": highest_sale or 0.0,
"average_sale": average_sale or 0.0,
"total_users": total_users or 0,
"profit_today": profit_today or 0.0,
"profit_week": profit_week or 0.0,
"profit_month": profit_month or 0.0,
"current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
except SQLAlchemyError as e:
logging.error(f"Database error: {e}", exc_info=True)
return {"error": "Произошла ошибка при работе с базой данных."}
except Exception as e:
logging.error(f"An unexpected error occurred: {e}", exc_info=True)
return {"error": "Произошла непредвиденная ошибка."}