feat: add subscription and transaction repositories
- Implemented SubscriptionRepository with methods to get, create, and update subscriptions. - Added BalanceTXRepository for creating and retrieving balance transactions. - Introduced a test script for simulating Pally webhook for local testing.
This commit is contained in:
@@ -2,6 +2,7 @@ from .ads import router as ads_router
|
||||
from .billing import router as billing_router
|
||||
from .buy import router as buy_router
|
||||
from .common import router as common_router
|
||||
from .deposit import router as deposit_router
|
||||
from .menus import router as menus_router
|
||||
from .prehandling import router as prehandling_router
|
||||
from .referals import router as referal_router
|
||||
@@ -11,6 +12,7 @@ routers = [
|
||||
prehandling_router,
|
||||
referal_router,
|
||||
billing_router,
|
||||
deposit_router,
|
||||
menus_router,
|
||||
ads_router,
|
||||
support_router,
|
||||
|
||||
@@ -29,6 +29,7 @@ async def pally_init(
|
||||
await state.clear()
|
||||
|
||||
ctx.provider = BillingProviders.PALLY
|
||||
ctx.amount = int(ctx.amount)
|
||||
|
||||
await cb.message.edit_text(
|
||||
BILL_CREATION.format(amount=ctx.amount, provider=ctx.provider.value.title())
|
||||
|
||||
@@ -4,31 +4,29 @@ import math
|
||||
from aiogram import F, Router
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import CallbackQuery
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from bot.keyboards.client import (
|
||||
devices_selector,
|
||||
duration_selector,
|
||||
payment_gateways,
|
||||
return_to_menu,
|
||||
)
|
||||
from bot.states.buy import BillingStorage, SubscriptionStorage
|
||||
from bot.keyboards.client import deposit_kb, devices_selector, duration_selector, return_to_menu
|
||||
from bot.states.buy import SubscriptionStorage
|
||||
from bot.texts import (
|
||||
CALLBACK_FALLBACK,
|
||||
CHECKOUT_PAYMENT_CHOICE,
|
||||
CONTEXT_REINITIATED,
|
||||
INSUFFICIENT_FUNDS,
|
||||
NOTHING_PLACEHOLDER,
|
||||
STANDARD_FALLBACK,
|
||||
SUBSCRIPTION_DEVICE_SELECTOR,
|
||||
SUBSCRIPTION_DURATION_SELECTOR,
|
||||
SUCCESSFULLY_CREATED_SUBSCRIPTION,
|
||||
)
|
||||
from config import settings
|
||||
from db.models.transactions import BalanceTxType
|
||||
from misc.utils import (
|
||||
calculate_price,
|
||||
convert_duration_to_int,
|
||||
convert_int_to_duration,
|
||||
get_discount,
|
||||
)
|
||||
from schemas.billing import BillingContext
|
||||
from schemas.di import DependenciesDTO
|
||||
from schemas.subscriptions import SubscriptionPlan
|
||||
|
||||
router = Router()
|
||||
@@ -157,7 +155,9 @@ async def select_duration(cb: CallbackQuery, state: FSMContext):
|
||||
|
||||
|
||||
@router.callback_query(SubscriptionStorage.duration, F.data == "confirm")
|
||||
async def proceed_to_checkout(cb: CallbackQuery, state: FSMContext):
|
||||
async def proceed_to_checkout(
|
||||
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
|
||||
):
|
||||
data = await state.get_data()
|
||||
await state.clear()
|
||||
|
||||
@@ -166,11 +166,43 @@ async def proceed_to_checkout(cb: CallbackQuery, state: FSMContext):
|
||||
await cb.message.edit_text(STANDARD_FALLBACK, reply_markup=return_to_menu)
|
||||
return
|
||||
|
||||
await cb.message.edit_text(
|
||||
CHECKOUT_PAYMENT_CHOICE,
|
||||
reply_markup=payment_gateways,
|
||||
) # FIXME: temp solution that's incredibly stupid
|
||||
amount = calculate_price(ctx)
|
||||
user = await deps.user_repository.get_user_by_id(session, cb.from_user.id)
|
||||
|
||||
await state.set_state(BillingStorage.pending)
|
||||
billing_context = BillingContext(amount=calculate_price(ctx))
|
||||
await state.set_data({"ctx": billing_context})
|
||||
if user.balance < amount:
|
||||
await cb.message.edit_text(
|
||||
INSUFFICIENT_FUNDS.format(balance=user.balance, amount=amount), reply_markup=deposit_kb
|
||||
)
|
||||
return
|
||||
|
||||
if not user:
|
||||
await cb.message.edit_text(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
try:
|
||||
await deps.user_service.buy_subscription(session, ctx, deps.rw_sdk, cb.from_user)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"buy_subscription caught an exception on user_id=%s, amount=%s. balance was NOT affected, transaction is rejected.",
|
||||
user.id,
|
||||
amount,
|
||||
)
|
||||
await cb.message.edit_text(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
deducted_user = await deps.user_repository.decrease_user_balance(
|
||||
session,
|
||||
user.id,
|
||||
amount,
|
||||
BalanceTxType.PURCHASE,
|
||||
description=f"subscription purchase: devices={ctx.devices}, duration={ctx.duration}, whitelists={ctx.whitelists}",
|
||||
)
|
||||
if not deducted_user:
|
||||
logger.critical(
|
||||
"RECONCILIATION NEEDED: subscription created for user_id=%s "
|
||||
"but balance deduction FAILED. amount=%s.",
|
||||
cb.from_user.id,
|
||||
amount,
|
||||
)
|
||||
|
||||
await cb.message.edit_text(SUCCESSFULLY_CREATED_SUBSCRIPTION, reply_markup=return_to_menu)
|
||||
|
||||
46
bot/handlers/deposit.py
Normal file
46
bot/handlers/deposit.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from aiogram import F, Router
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import CallbackQuery, Message
|
||||
|
||||
from bot.keyboards.client import payment_gateways, return_to_menu
|
||||
from bot.states.buy import BillingStorage
|
||||
from bot.states.deposit import DepositStorage
|
||||
from bot.texts import (
|
||||
CHECKOUT_PAYMENT_CHOICE,
|
||||
DEPOSIT_AMOUNT,
|
||||
DEPOSIT_AMOUNT_FALLBACK,
|
||||
)
|
||||
from schemas.billing import BillingContext
|
||||
from schemas.common import GeneralMessageContext
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "deposit")
|
||||
async def deposit_init(cb: CallbackQuery, state: FSMContext):
|
||||
await state.clear()
|
||||
|
||||
await cb.message.edit_text(DEPOSIT_AMOUNT, reply_markup=return_to_menu)
|
||||
|
||||
ctx = GeneralMessageContext(cb.message)
|
||||
await state.set_state(DepositStorage.amount)
|
||||
await state.set_data({"ctx": ctx})
|
||||
|
||||
|
||||
@router.message(DepositStorage.amount)
|
||||
async def deposit_amount(msg: Message, state: FSMContext):
|
||||
data = await state.get_data()
|
||||
await state.clear()
|
||||
await msg.delete()
|
||||
|
||||
ctx: GeneralMessageContext | None = data.get("ctx")
|
||||
if not isinstance(ctx, GeneralMessageContext) or not msg.text.isdigit():
|
||||
await msg.answer(DEPOSIT_AMOUNT_FALLBACK, reply_markup=return_to_menu)
|
||||
await state.set_state(DepositStorage.amount)
|
||||
await state.set_data(data)
|
||||
return
|
||||
|
||||
await ctx.msg.edit_text(CHECKOUT_PAYMENT_CHOICE, reply_markup=payment_gateways)
|
||||
await state.set_state(BillingStorage.pending)
|
||||
billing_context = BillingContext(amount=int(msg.text))
|
||||
await state.set_data({"ctx": billing_context})
|
||||
@@ -34,7 +34,9 @@ async def fetch_referal(
|
||||
)
|
||||
|
||||
await msg.answer(
|
||||
build_main_menu_text(format_subscription_link(user.subscription_link)),
|
||||
build_main_menu_text(
|
||||
format_subscription_link(user.subscription_link), balance=user.balance
|
||||
),
|
||||
reply_markup=main_menu,
|
||||
)
|
||||
|
||||
@@ -51,7 +53,9 @@ async def standard_start(
|
||||
user = await deps.user_service.add_user(session, user_id=msg.from_user.id, rw_sdk=deps.rw_sdk)
|
||||
|
||||
await msg.answer(
|
||||
build_main_menu_text(format_subscription_link(user.subscription_link)),
|
||||
build_main_menu_text(
|
||||
format_subscription_link(user.subscription_link), balance=user.balance
|
||||
),
|
||||
reply_markup=main_menu,
|
||||
)
|
||||
|
||||
@@ -64,7 +68,9 @@ async def main_menu_cb(
|
||||
|
||||
user = await deps.user_repository.get_user_by_id(session, cb.from_user.id)
|
||||
await cb.message.edit_text(
|
||||
build_main_menu_text(format_subscription_link(user.subscription_link)),
|
||||
build_main_menu_text(
|
||||
format_subscription_link(user.subscription_link), balance=user.balance
|
||||
),
|
||||
reply_markup=main_menu,
|
||||
)
|
||||
|
||||
@@ -79,7 +85,9 @@ async def update_link(
|
||||
user = await deps.user_service.update_user_link(session, cb.from_user.id, deps.rw_sdk)
|
||||
await cb.answer("✅")
|
||||
await cb.message.edit_text(
|
||||
build_main_menu_text(format_subscription_link(user.subscription_link)),
|
||||
build_main_menu_text(
|
||||
format_subscription_link(user.subscription_link), balance=user.balance
|
||||
),
|
||||
reply_markup=main_menu,
|
||||
)
|
||||
|
||||
|
||||
@@ -9,14 +9,17 @@ main_menu = InlineKeyboardBuilder(
|
||||
[
|
||||
[InlineKeyboardButton(text="📊 Подписка", callback_data="sub_info")],
|
||||
[
|
||||
InlineKeyboardButton(text="⚙️ Купить", callback_data="buy"),
|
||||
InlineKeyboardButton(text="⁉️ FAQ", callback_data="faq"),
|
||||
InlineKeyboardButton(text="🛒 Купить", callback_data="buy"),
|
||||
InlineKeyboardButton(text="💸 Пополнить", callback_data="deposit"),
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton(text="📢 Наш Канал", url="https://t.me/maleniavpn"),
|
||||
InlineKeyboardButton(text="🎧 Тех. Поддержка", url="https://t.me/maleniasupportbot"),
|
||||
],
|
||||
[InlineKeyboardButton(text="🔗 Обновить ссылку", callback_data="update_link")],
|
||||
[
|
||||
InlineKeyboardButton(text="🔗 Обновить ссылку", callback_data="update_link"),
|
||||
InlineKeyboardButton(text="⁉️ FAQ", callback_data="faq"),
|
||||
],
|
||||
[InlineKeyboardButton(text="👤 Реферальная система", callback_data="referal")],
|
||||
]
|
||||
).as_markup()
|
||||
@@ -46,6 +49,10 @@ support_url_kb: InlineKeyboardMarkup = InlineKeyboardBuilder(
|
||||
]
|
||||
).as_markup()
|
||||
|
||||
deposit_kb: InlineKeyboardMarkup = InlineKeyboardBuilder(
|
||||
[[InlineKeyboardButton(text="💸 Пополнить", callback_data="deposit")], [_return_to_menu_btn]]
|
||||
).as_markup()
|
||||
|
||||
|
||||
def _return_btn(data: str = "menu:main", text: str = "⬅️ Назад") -> InlineKeyboardButton:
|
||||
return InlineKeyboardButton(text=text, callback_data=data)
|
||||
|
||||
@@ -12,6 +12,7 @@ from config import settings
|
||||
from db.session import async_session
|
||||
from misc.pally import PallyClient
|
||||
from repositories.bills import BillsRepository
|
||||
from repositories.subscriptions import SubscriptionRepository
|
||||
from repositories.users import UserRepository
|
||||
from schemas.di import DependenciesDTO
|
||||
from services.billing_service import BillingService
|
||||
@@ -26,9 +27,10 @@ async def main():
|
||||
pally_client = PallyClient(settings.pally_token)
|
||||
|
||||
user_repository = UserRepository()
|
||||
user_service = UserService(user_repository)
|
||||
|
||||
bills_repository = BillsRepository()
|
||||
subscriptions_repository = SubscriptionRepository()
|
||||
|
||||
user_service = UserService(user_repository, subscription_repository=subscriptions_repository)
|
||||
billing_service = BillingService(
|
||||
user_repository=user_repository, bills_repository=bills_repository
|
||||
)
|
||||
@@ -45,6 +47,7 @@ async def main():
|
||||
pally_client=pally_client,
|
||||
bills_repository=bills_repository,
|
||||
billing_service=billing_service,
|
||||
subscriptions_repository=subscriptions_repository,
|
||||
)
|
||||
dp.update.middleware.register(DIMiddleware(deps, async_session))
|
||||
|
||||
|
||||
5
bot/states/deposit.py
Normal file
5
bot/states/deposit.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
|
||||
|
||||
class DepositStorage(StatesGroup):
|
||||
amount = State()
|
||||
12
bot/texts.py
12
bot/texts.py
@@ -94,7 +94,8 @@ NOTHING_PLACEHOLDER = "∅"
|
||||
MAIN_MENU = (
|
||||
str(MALENIA_LOGO)
|
||||
+ " <b>Malenia — <i>{quote}</i></b>\n\n"
|
||||
+ f"<i>{MALENIA_COINS} Личный кабинет</i>\n"
|
||||
+ f"<i>{MALENIA_HEART} Личный кабинет</i>\n"
|
||||
+ f"<b>{MALENIA_COINS} Ваш баланс:</b> <code>{{balance}}₽</code>\n"
|
||||
+ f"<b>{MALENIA_LINK} Ссылка на подписку: <code>{{link}}</code></b>"
|
||||
)
|
||||
|
||||
@@ -162,7 +163,7 @@ SUBSCRIPTION_DURATION_SELECTOR = (
|
||||
|
||||
WHITELISTS_ALREADY_ON = "Белые списки уже активны."
|
||||
|
||||
CHECKOUT_PAYMENT_CHOICE = "Пока что без автоплатежа. Нажмите кнопку ниже и обратитесь в поддержку для оплаты и активации подписки."
|
||||
CHECKOUT_PAYMENT_CHOICE = "<b>💳 Пополнение баланса:</b>\n\n<i>❓ Выберите способ оплаты:</i>"
|
||||
|
||||
# ============================================================
|
||||
# BILLING
|
||||
@@ -180,6 +181,13 @@ BILL_CREATION = _BILL_TEMPLATE + _DIVIDER + GENERAL_PROCESSING
|
||||
|
||||
BILL_CREATED = _BILL_TEMPLATE + _DIVIDER + _BILL_LINK
|
||||
|
||||
INSUFFICIENT_FUNDS = "<b>⚠️ Недостаточно средств для проведения операции.</b>\n\n💰 Текущий баланс: {balance}₽\n💸 Требуется: {amount}₽"
|
||||
SUCCESSFULLY_CREATED_SUBSCRIPTION = (
|
||||
"<b>💚 Ваша подписка успешно оплачена!</b> Ссылка на добавления доступна в главном меню."
|
||||
)
|
||||
|
||||
DEPOSIT_AMOUNT = "<b>💸 Укажите сумму пополнения</b>"
|
||||
DEPOSIT_AMOUNT_FALLBACK = "<b>❌ Сумма пополнения указана неверно, повторите попытку.</b>"
|
||||
|
||||
# ============================================================
|
||||
# ПОДДЕРЖКА
|
||||
|
||||
Reference in New Issue
Block a user