feat: implement subscription management and billing enhancements
This commit is contained in:
@@ -169,7 +169,12 @@ async def proceed_to_checkout(
|
||||
amount = calculate_price(ctx)
|
||||
user = await deps.user_repository.get_user_by_id(session, cb.from_user.id)
|
||||
|
||||
if user.balance < amount:
|
||||
credit = await deps.user_service.calculate_plan_credit(
|
||||
session, cb.from_user.id, ctx, deps.rw_sdk
|
||||
)
|
||||
effective_balance = user.balance + credit
|
||||
|
||||
if effective_balance < amount:
|
||||
await cb.message.edit_text(
|
||||
INSUFFICIENT_FUNDS.format(balance=user.balance, amount=amount), reply_markup=deposit_kb
|
||||
)
|
||||
@@ -190,6 +195,15 @@ async def proceed_to_checkout(
|
||||
await cb.message.edit_text(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
if credit > 0:
|
||||
await deps.user_repository.increase_user_balance(
|
||||
session,
|
||||
user.id,
|
||||
credit,
|
||||
tx_type=BalanceTxType.REFUND,
|
||||
description="refund for unused subscription days",
|
||||
)
|
||||
|
||||
deducted_user = await deps.user_repository.decrease_user_balance(
|
||||
session,
|
||||
user.id,
|
||||
|
||||
@@ -8,8 +8,10 @@ from bot.states.deposit import DepositStorage
|
||||
from bot.texts import (
|
||||
CHECKOUT_PAYMENT_CHOICE,
|
||||
DEPOSIT_AMOUNT,
|
||||
DEPOSIT_AMOUNT_BELOW_MINIMAL,
|
||||
DEPOSIT_AMOUNT_FALLBACK,
|
||||
)
|
||||
from config import settings
|
||||
from schemas.billing import BillingContext
|
||||
from schemas.common import GeneralMessageContext
|
||||
|
||||
@@ -22,7 +24,7 @@ async def deposit_init(cb: CallbackQuery, state: FSMContext):
|
||||
|
||||
await cb.message.edit_text(DEPOSIT_AMOUNT, reply_markup=return_to_menu)
|
||||
|
||||
ctx = GeneralMessageContext(cb.message)
|
||||
ctx = GeneralMessageContext(msg=cb.message)
|
||||
await state.set_state(DepositStorage.amount)
|
||||
await state.set_data({"ctx": ctx})
|
||||
|
||||
@@ -40,6 +42,15 @@ async def deposit_amount(msg: Message, state: FSMContext):
|
||||
await state.set_data(data)
|
||||
return
|
||||
|
||||
if int(msg.text) < settings.deposit_threshold:
|
||||
await ctx.msg.edit_text(
|
||||
DEPOSIT_AMOUNT_BELOW_MINIMAL.format(threshold=settings.deposit_threshold),
|
||||
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))
|
||||
|
||||
@@ -4,10 +4,19 @@ from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import CallbackQuery, Message
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from bot.keyboards.client import close_kb, main_menu, return_to_menu
|
||||
from bot.texts import FAQ_TEXT, GENERAL_PROCESSING
|
||||
from bot.keyboards.client import close_kb, main_menu, return_to_menu, subscription_controls
|
||||
from bot.texts import (
|
||||
CALLBACK_FALLBACK,
|
||||
FAQ_TEXT,
|
||||
GENERAL_PROCESSING,
|
||||
GENERAL_SUCCESS,
|
||||
NOTHING_PLACEHOLDER,
|
||||
)
|
||||
from db.models.users import User
|
||||
from misc import utils
|
||||
from misc.utils import build_main_menu_text, format_subscription_link
|
||||
from schemas.di import DependenciesDTO
|
||||
from schemas.subscriptions import InternalSquads, SubscriptionPlan
|
||||
from services.rw import get_user_by_telegram_id
|
||||
|
||||
router = Router()
|
||||
@@ -107,9 +116,72 @@ async def sub_info(
|
||||
|
||||
await cb.message.edit_text(GENERAL_PROCESSING, reply_markup=close_kb)
|
||||
rw_user = await get_user_by_telegram_id(deps.rw_sdk, cb.from_user.id)
|
||||
user = await deps.user_service.update_user_link(session, cb.from_user.id, deps.rw_sdk)
|
||||
user: User | None = await deps.user_service.update_user_link(
|
||||
session, cb.from_user.id, deps.rw_sdk
|
||||
)
|
||||
sub = await deps.subscriptions_repository.get_subscription_by_user_id(session, cb.from_user.id)
|
||||
|
||||
if not user:
|
||||
await cb.answer(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
if not sub:
|
||||
try:
|
||||
dto = SubscriptionPlan(
|
||||
devices=rw_user.hwid_device_limit,
|
||||
whitelists=bool(rw_user.active_squads.count(InternalSquads.WHITELISTS)),
|
||||
discount=0,
|
||||
)
|
||||
sub = await deps.subscriptions_repository.create_subscription(
|
||||
session,
|
||||
user_id=user.id,
|
||||
end_date=rw_user.expire_at,
|
||||
devices=rw_user.hwid_device_limit,
|
||||
duration_days=30,
|
||||
whitelists=dto.whitelists,
|
||||
plan_price_paid=utils.calculate_price(dto),
|
||||
)
|
||||
except Exception:
|
||||
await cb.answer(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
await cb.message.edit_text(
|
||||
deps.user_service.format_subscription_message(rw_user, link=user.subscription_link),
|
||||
reply_markup=return_to_menu,
|
||||
deps.user_service.format_subscription_message(
|
||||
rw_user, link=user.subscription_link, autorenew=sub.autorenew
|
||||
),
|
||||
reply_markup=subscription_controls(sub.autorenew),
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "toggle:autorenewal")
|
||||
async def toggle_autorenewal(
|
||||
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
|
||||
):
|
||||
await state.clear()
|
||||
await cb.answer(NOTHING_PLACEHOLDER + " В разработке.")
|
||||
return
|
||||
|
||||
await cb.message.edit_text(GENERAL_PROCESSING)
|
||||
sub = await deps.subscriptions_repository.get_subscription_by_user_id(session, cb.from_user.id)
|
||||
|
||||
if not sub:
|
||||
await cb.answer(CALLBACK_FALLBACK)
|
||||
return
|
||||
|
||||
new_autorenew = not sub.autorenew
|
||||
sub = await deps.subscriptions_repository.update_subscription_autorenew(
|
||||
session, sub.user_id, new_autorenew
|
||||
)
|
||||
|
||||
rw_user = await get_user_by_telegram_id(deps.rw_sdk, cb.from_user.id)
|
||||
user: User | None = await deps.user_service.update_user_link(
|
||||
session, cb.from_user.id, deps.rw_sdk
|
||||
)
|
||||
|
||||
await cb.answer(GENERAL_SUCCESS)
|
||||
await cb.message.edit_text(
|
||||
deps.user_service.format_subscription_message(
|
||||
rw_user, link=user.subscription_link, autorenew=sub.autorenew
|
||||
),
|
||||
reply_markup=subscription_controls(sub.autorenew),
|
||||
)
|
||||
|
||||
@@ -54,6 +54,20 @@ deposit_kb: InlineKeyboardMarkup = InlineKeyboardBuilder(
|
||||
).as_markup()
|
||||
|
||||
|
||||
def subscription_controls(current_autorenewal_status: bool) -> InlineKeyboardMarkup:
|
||||
autorenewal_text = (
|
||||
"🟢 Включить автопродление"
|
||||
if not current_autorenewal_status
|
||||
else "🔴 Отключить автопродление"
|
||||
)
|
||||
return InlineKeyboardBuilder(
|
||||
[
|
||||
[InlineKeyboardButton(text=autorenewal_text, callback_data="toggle:autorenewal")],
|
||||
[_return_to_menu_btn],
|
||||
]
|
||||
).as_markup()
|
||||
|
||||
|
||||
def _return_btn(data: str = "menu:main", text: str = "⬅️ Назад") -> InlineKeyboardButton:
|
||||
return InlineKeyboardButton(text=text, callback_data=data)
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ logging.basicConfig(level=logging.DEBUG)
|
||||
async def main():
|
||||
dp = Dispatcher()
|
||||
|
||||
pally_client = PallyClient(settings.pally_token)
|
||||
pally_client = PallyClient(settings.pally_token, payer_pays_commission=True)
|
||||
|
||||
user_repository = UserRepository()
|
||||
bills_repository = BillsRepository()
|
||||
|
||||
@@ -58,6 +58,8 @@ STATUS_EXPIRED = "истёк"
|
||||
STATUS_LIMITED = "трафик ограничен"
|
||||
STATUS_UNKNOWN = "неизвестный статус"
|
||||
|
||||
GENERAL_SUCCESS = "✅"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ФОРМАТИРОВАНИЕ ДАННЫХ
|
||||
@@ -114,6 +116,7 @@ FAQ_TEXT = (
|
||||
"<b>вам будет начисляться процент от их оплаченной подписки</b> на баланс."
|
||||
)
|
||||
|
||||
CALLBACK_PROCESSING = "⏳"
|
||||
GENERAL_PROCESSING = "<i>⏳ Подождите...</i>"
|
||||
|
||||
STANDARD_FALLBACK = (
|
||||
@@ -134,6 +137,7 @@ SUBSCRIPTION_INFORMATION = (
|
||||
+ "⏳ <b>Осталось дней:</b> {days_left}\n"
|
||||
+ "📊 <b>Израсходовано трафика:</b> {used_traffic}\n"
|
||||
+ "📱 <b>Количество устройств:</b> {hwid_limit}\n"
|
||||
+ "<b>💸 Автопродление:</b> {autorenew}"
|
||||
)
|
||||
|
||||
NO_SUBSCRIPTION = "⚠️ <b>Подписка не найдена.</b>"
|
||||
@@ -188,6 +192,9 @@ SUCCESSFULLY_CREATED_SUBSCRIPTION = (
|
||||
|
||||
DEPOSIT_AMOUNT = "<b>💸 Укажите сумму пополнения</b>"
|
||||
DEPOSIT_AMOUNT_FALLBACK = "<b>❌ Сумма пополнения указана неверно, повторите попытку.</b>"
|
||||
DEPOSIT_AMOUNT_BELOW_MINIMAL = (
|
||||
"<b>❌ Сумма пополнения ниже минимальной - <code>{threshold}₽</code>.</b>"
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# ПОДДЕРЖКА
|
||||
|
||||
Reference in New Issue
Block a user