# - *- coding: utf- 8 - *-
from datetime import datetime
from typing import Union
import pytz
from aiogram import Bot
from aiogram.types import LinkPreviewOptions
from aiogram.utils.markdown import hide_link
from tgbot.data.config import BOT_TIMEZONE
from tgbot.database import (
Categoryx,
Positionx,
Itemx,
Purchasesx,
Refillx,
Settingsx,
Userx,
ModelPurchases,
ModelRefill,
ModelUser,
)
from tgbot.keyboards.inline_admin import profile_edit_finl
from tgbot.keyboards.inline_admin_products import (
position_edit_open_finl,
category_edit_open_finl,
item_delete_finl,
)
from tgbot.keyboards.inline_user import user_profile_finl
from tgbot.keyboards.inline_user_products import products_open_finl
from tgbot.services.api_hosting_text import HostingAPI
from tgbot.utils.const_functions import ded, get_unix, convert_day, convert_date
from tgbot.utils.misc.bot_models import ARS
################################################################################
################################# ПОЛЬЗОВАТЕЛЬ #################################
# Открытие профиля пользователем
async def open_profile_user(bot: Bot, user_id: Union[int, str]):
get_purchases = await Purchasesx().gets(user_id=user_id)
get_user = await Userx().get_required(user_id=user_id)
how_days = int(get_unix() - get_user.user_unix) // 60 // 60 // 24
count_items = sum([purchase.purchase_count for purchase in get_purchases])
await bot.send_message(
chat_id=user_id,
text=ded(f"""
👤 Ваш профиль
➖➖➖➖➖➖➖➖➖➖
🆔 ID: {get_user.user_id}
💰 Баланс: {get_user.user_balance}₽
🎁 Куплено товаров: {count_items}шт
🕰 Регистрация: {convert_date(get_user.user_unix, False, False)} ({convert_day(how_days)})
"""),
reply_markup=user_profile_finl(),
)
# Открытие позиции пользователем
async def position_open_user(bot: Bot, user_id: int, position_id: int, remover: int):
get_items = await Itemx().gets(position_id=position_id)
get_position = await Positionx().get_required(position_id=position_id)
get_category = await Categoryx().get_required(category_id=get_position.category_id)
if get_position.position_desc != "None":
text_desc = f"▪️ Описание: {get_position.position_desc}"
else:
text_desc = ""
await bot.send_message(
chat_id=user_id,
text=ded(f"""
🎁 Покупка товара
➖➖➖➖➖➖➖➖➖➖
▪️ Название: {get_position.position_name}
▪️ Категория: {get_category.category_name}
▪️ Стоимость: {get_position.position_price}₽
▪️ Количество: {len(get_items)}шт
{text_desc}
"""),
link_preview_options=LinkPreviewOptions(show_above_text=True),
reply_markup=products_open_finl(position_id, get_position.category_id, remover),
)
################################################################################
#################################### АДМИН #####################################
# Открытие профиля админом
async def open_profile_admin(bot: Bot, user_id: int, get_user: ModelUser):
get_purchases = await Purchasesx().gets(user_id=get_user.user_id)
how_days = int(get_unix() - get_user.user_unix) // 60 // 60 // 24
count_items = sum([purchase.purchase_count for purchase in get_purchases])
await bot.send_message(
chat_id=user_id,
text=ded(f"""
👤 Профиль пользователя: {get_user.user_name}
➖➖➖➖➖➖➖➖➖➖
▪️ ID: {get_user.user_id}
▪️ Логин: @{get_user.user_login}
▪️ Имя: {get_user.user_name}
▪️ Регистрация: {convert_date(get_user.user_unix, False, False)} ({convert_day(how_days)})
▪️ Баланс: {get_user.user_balance}₽
▪️ Всего выдано: {get_user.user_give}₽
▪️ Всего пополнено: {get_user.user_refill}₽
▪️ Куплено товаров: {count_items}шт
"""),
reply_markup=profile_edit_finl(get_user.user_id),
)
# Открытие пополнения админом
async def refill_open_admin(bot: Bot, user_id: int, get_refill: ModelRefill):
get_user = await Userx().get_required(user_id=get_refill.user_id)
if get_refill.refill_method in ["Form", "Nickname", "Number", "QIWI"]:
pay_method = "QIWI 🥝"
elif get_refill.refill_method == "Cryptobot":
pay_method = "CryptoBot 🔷"
else:
pay_method = f"{get_refill.refill_method}"
await bot.send_message(
chat_id=user_id,
text=ded(f"""
🧾 Чек: #{get_refill.refill_receipt}
➖➖➖➖➖➖➖➖➖➖
▪️ Пользователь: {get_user.user_name} | {get_user.user_id}
▪️ Сумма пополнения: {get_refill.refill_amount}₽
▪️ Способ пополнения: {pay_method}
▪️ Комментарий: {get_refill.refill_comment}
▪️ Дата пополнения: {convert_date(get_refill.refill_unix)}
"""),
)
# Открытие покупки админом
async def purchase_open_admin(
bot: Bot, arSession: ARS, user_id: int, get_purchase: ModelPurchases
):
get_user = await Userx().get_required(user_id=get_purchase.user_id)
link_items = await (
await HostingAPI.connect(
bot=bot,
arSession=arSession,
)
).upload_text(get_purchase.purchase_data)
await bot.send_message(
chat_id=user_id,
text=ded(f"""
🧾 Чек: #{get_purchase.purchase_receipt}
➖➖➖➖➖➖➖➖➖➖
▪️ Пользователь: {get_user.user_name} | {get_user.user_id}
▪️ Название товара: {get_purchase.purchase_position_name}
▪️ Куплено товаров: {get_purchase.purchase_count}шт
▪️ Цена одного товара: {get_purchase.purchase_price_one}₽
▪️ Сумма покупки: {get_purchase.purchase_price}₽
▪️ Баланс до покупки: {get_purchase.user_balance_before}₽
▪️ Баланс после покупки: {get_purchase.user_balance_after}₽
▪️ Товары: кликабельно
▪️ Дата покупки: {convert_date(get_purchase.purchase_unix)}
"""),
disable_web_page_preview=True,
)
# Открытие категории админом
async def category_open_admin(bot: Bot, user_id: int, category_id: int, remover: int):
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
0,
0,
0,
0,
)
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
0,
0,
0,
0,
)
get_items = await Itemx().gets(category_id=category_id)
get_category = await Categoryx().get_required(category_id=category_id)
get_positions = await Positionx().gets(category_id=category_id)
get_purchases = await Purchasesx().gets(purchase_category_id=category_id)
get_settings = await Settingsx().get()
for purchase in get_purchases:
profit_amount_all += purchase.purchase_price
profit_count_all += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_day >= 0:
profit_amount_day += purchase.purchase_price
profit_count_day += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_week >= 0:
profit_amount_week += purchase.purchase_price
profit_count_week += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_month >= 0:
profit_amount_month += purchase.purchase_price
profit_count_month += purchase.purchase_count
await bot.send_message(
chat_id=user_id,
text=ded(f"""
🗃️ Редактирование категории
➖➖➖➖➖➖➖➖➖➖
▪️ Категория: {get_category.category_name}
▪️ Кол-во позиций: {len(get_positions)}шт
▪️ Кол-во товаров: {len(get_items)}шт
▪️ Дата создания: {convert_date(get_category.category_unix)}шт
💸 Продаж за День: {profit_count_day}шт - {round(profit_amount_day, 2)}₽
💸 Продаж за Неделю: {profit_count_week}шт - {round(profit_amount_week, 2)}₽
💸 Продаж за Месяц: {profit_count_month}шт - {round(profit_amount_month, 2)}₽
💸 Продаж за Всё время: {profit_count_all}шт - {round(profit_amount_all, 2)}₽
"""),
reply_markup=await category_edit_open_finl(bot, category_id, remover),
)
# Открытие позиции админом
async def position_open_admin(bot: Bot, position_id: int, user_id: int):
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
0,
0,
0,
0,
)
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
0,
0,
0,
0,
)
get_items = await Itemx().gets(position_id=position_id)
get_position = await Positionx().get_required(position_id=position_id)
get_category = await Categoryx().get_required(category_id=get_position.category_id)
get_settings = await Settingsx().get()
get_purchases = await Purchasesx().gets(purchase_position_id=position_id)
# Наличие описания
if get_position.position_desc != "None":
position_desc = f"{get_position.position_desc}"
else:
position_desc = "Отсутствует ❌"
# Статистика позиции
for purchase in get_purchases:
profit_amount_all += purchase.purchase_price
profit_count_all += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_day >= 0:
profit_amount_day += purchase.purchase_price
profit_count_day += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_week >= 0:
profit_amount_week += purchase.purchase_price
profit_count_week += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_month >= 0:
profit_amount_month += purchase.purchase_price
profit_count_month += purchase.purchase_count
await bot.send_message(
chat_id=user_id,
text=ded(f"""
📁 Редактирование позиции
➖➖➖➖➖➖➖➖➖➖
▪️ Категория: {get_category.category_name}
▪️ Позиция: {get_position.position_name}
▪️ Стоимость: {get_position.position_price}₽
▪️ Количество: {len(get_items)}шт
▪️ Дата создания: {convert_date(get_category.category_unix)}
▪️ Описание: {position_desc}
💸 Продаж за День: {profit_count_day}шт - {round(profit_amount_day, 2)}₽
💸 Продаж за Неделю: {profit_count_week}шт - {round(profit_amount_week, 2)}₽
💸 Продаж за Месяц: {profit_count_month}шт - {round(profit_amount_month, 2)}₽
💸 Продаж за Всё время: {profit_count_all}шт - {round(profit_amount_all, 2)}₽
"""),
link_preview_options=LinkPreviewOptions(show_above_text=True),
reply_markup=await position_edit_open_finl(bot, position_id, 0),
)
# Открытие товара админом
async def item_open_admin(bot: Bot, item_id: int, user_id: int):
get_item = await Itemx().get_required(item_id=item_id)
get_position = await Positionx().get_required(position_id=get_item.position_id)
get_category = await Categoryx().get_required(category_id=get_item.category_id)
await bot.send_message(
chat_id=user_id,
text=ded(f"""
🎁️ Редактирование товара
➖➖➖➖➖➖➖➖➖➖
▪️ Категория: {get_category.category_name}
▪️ Позиция: {get_position.position_name}
▪️ Дата добавления: {convert_date(get_item.item_unix)}
▪️ Товар: {get_item.item_data}
"""),
reply_markup=item_delete_finl(get_item.item_id, get_item.position_id),
)
################################################################################
################################################################################
# Статистика бота
async def get_statistics() -> str:
refill_amount_all, refill_amount_day, refill_amount_week, refill_amount_month = (
0,
0,
0,
0,
)
refill_count_all, refill_count_day, refill_count_week, refill_count_month = (
0,
0,
0,
0,
)
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
0,
0,
0,
0,
)
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
0,
0,
0,
0,
)
(
users_all,
users_day,
users_week,
users_month,
users_money_have,
users_money_give,
) = (0, 0, 0, 0, 0, 0)
refill_cryptobot_count, refill_cryptobot_amount = 0, 0
refill_stars_count, refill_stars_amount = 0, 0
get_categories = await Categoryx().get_all()
get_positions = await Positionx().get_all()
get_purchases = await Purchasesx().get_all()
get_refill = await Refillx().get_all()
get_items = await Itemx().get_all()
get_users = await Userx().get_all()
get_settings = await Settingsx().get()
# Покупки
for purchase in get_purchases:
profit_amount_all += purchase.purchase_price
profit_count_all += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_day >= 0:
profit_amount_day += purchase.purchase_price
profit_count_day += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_week >= 0:
profit_amount_week += purchase.purchase_price
profit_count_week += purchase.purchase_count
if purchase.purchase_unix - get_settings.misc_profit_month >= 0:
profit_amount_month += purchase.purchase_price
profit_count_month += purchase.purchase_count
# Пополнения
for refill in get_refill:
refill_amount_all += refill.refill_amount
refill_count_all += 1
if refill.refill_method == "Cryptobot":
refill_cryptobot_count += 1
refill_cryptobot_amount += refill.refill_amount
elif refill.refill_method == "Stars":
refill_stars_count += 1
refill_stars_amount += refill.refill_amount
if refill.refill_unix - get_settings.misc_profit_day >= 0:
refill_amount_day += refill.refill_amount
refill_count_day += 1
if refill.refill_unix - get_settings.misc_profit_week >= 0:
refill_amount_week += refill.refill_amount
refill_count_week += 1
if refill.refill_unix - get_settings.misc_profit_month >= 0:
refill_amount_month += refill.refill_amount
refill_count_month += 1
# Пользователи и средства
for user in get_users:
users_money_have += user.user_balance
users_money_give += user.user_give
users_all += 1
if user.user_unix - get_settings.misc_profit_day >= 0:
users_day += 1
if user.user_unix - get_settings.misc_profit_week >= 0:
users_week += 1
if user.user_unix - get_settings.misc_profit_month >= 0:
users_month += 1
# Даты обновления статистики
all_days = [
"Понедельник",
"Вторник",
"Среда",
"Четверг",
"Пятница",
"Суббота",
"Воскресенье",
]
all_months = [
"Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",
"Ноябрь",
"Декабрь",
]
now_day = datetime.now().day
now_week = datetime.now().weekday()
now_month = datetime.now().month
now_year = datetime.now().year
unix_day = int(
datetime.strptime(
f"{now_day}.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S"
).timestamp()
)
unix_week = unix_day - (now_week * 86400)
week_day = int(
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%d")
)
week_month = int(
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%m")
)
week_week = int(
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).weekday()
)
return ded(f"""
📊 СТАТИСТИКА БОТА
➖➖➖➖➖➖➖➖➖➖
👤 Пользователи
┣ Юзеров за День: {users_day}
┣ Юзеров за Неделю: {users_week}
┣ Юзеров за Месяц: {users_month}
┗ Юзеров за Всё время: {users_all}
💰 Средства
┣‒ Продажи (кол-во, сумма)
┣ За День: {profit_count_day}шт - {round(profit_amount_day, 2)}₽
┣ За Неделю: {profit_count_week}шт - {round(profit_amount_week, 2)}₽
┣ За Месяц: {profit_count_month}шт - {round(profit_amount_month, 2)}₽
┣ За Всё время: {profit_count_all}шт - {round(profit_amount_all, 2)}₽
┃
┣‒ Пополнения (кол-во, сумма)
┣ За День: {refill_count_day}шт - {round(refill_amount_day, 2)}₽
┣ За Неделю: {refill_count_week}шт - {round(refill_amount_week, 2)}₽
┣ За Месяц: {refill_count_month}шт - {round(refill_amount_month, 2)}₽
┣ За Всё время: {refill_count_all}шт - {round(refill_amount_all, 2)}₽
┃
┣‒ Платежные системы (всего)
┣ CryptoBot: {refill_cryptobot_count}шт - {round(refill_cryptobot_amount, 2)}₽
┣ TG Stars: {refill_stars_count}шт - {round(refill_stars_amount, 2)}₽
┃
┣‒ Остальные
┣ Средств выдано: {round(users_money_give, 2)}₽
┗ Средств в системе: {round(users_money_have, 2)}₽
🎁 Товары
┣ Товаров: {len(get_items)}шт
┣ Позиций: {len(get_positions)}шт
┗ Категорий: {len(get_categories)}шт
🕰 Даты статистики
┣ Дневная: {now_day} {all_months[now_month - 1].title()}
┣ Недельная: {week_day} {all_months[week_month - 1].title()}, {all_days[week_week]}
┗ Месячная: 1 {all_months[now_month - 1].title()}, {now_year}г
""")