feat(promo): Добавлены промокоды на скидку в процентах
This commit is contained in:
@@ -123,13 +123,15 @@ async def process_promo_code_input(message: types.Message, state: FSMContext,
|
||||
code=hcode(code_input.upper()))
|
||||
reply_markup = get_back_to_main_menu_markup(current_lang, i18n)
|
||||
else:
|
||||
|
||||
# Try as BONUS code first (existing behavior)
|
||||
success, result = await promo_code_service.apply_promo_code(
|
||||
session, user.id, code_input, current_lang)
|
||||
|
||||
if success:
|
||||
# Bonus code success
|
||||
await session.commit()
|
||||
logging.info(
|
||||
f"Promo code '{code_input}' successfully applied for user {user.id}."
|
||||
f"Bonus promo code '{code_input}' successfully applied for user {user.id}."
|
||||
)
|
||||
|
||||
new_end_date = result if isinstance(result, datetime) else None
|
||||
@@ -151,15 +153,35 @@ async def process_promo_code_input(message: types.Message, state: FSMContext,
|
||||
connect_button_url=connect_button_url,
|
||||
)
|
||||
else:
|
||||
await session.rollback()
|
||||
logging.info(
|
||||
f"Promo code '{code_input}' application failed for user {user.id}. Reason: {result}"
|
||||
)
|
||||
response_to_user_text = result
|
||||
reply_markup = get_back_to_main_menu_markup(
|
||||
current_lang, i18n
|
||||
# Bonus code failed, try as DISCOUNT code
|
||||
success_discount, result_discount = await promo_code_service.apply_discount_promo_code(
|
||||
session, user.id, code_input, current_lang
|
||||
)
|
||||
|
||||
if success_discount:
|
||||
# Discount code success
|
||||
await session.commit()
|
||||
logging.info(
|
||||
f"Discount promo code '{code_input}' successfully applied for user {user.id}."
|
||||
)
|
||||
discount_pct = result_discount # Returns percentage
|
||||
response_to_user_text = _(
|
||||
"discount_promo_code_applied_success",
|
||||
code=hcode(code_input.upper()),
|
||||
discount=discount_pct
|
||||
)
|
||||
reply_markup = get_back_to_main_menu_markup(current_lang, i18n)
|
||||
else:
|
||||
# Both failed
|
||||
await session.rollback()
|
||||
logging.info(
|
||||
f"Promo code '{code_input}' application failed for user {user.id}. Reason: {result}"
|
||||
)
|
||||
response_to_user_text = result # Original error message from bonus code attempt
|
||||
reply_markup = get_back_to_main_menu_markup(
|
||||
current_lang, i18n
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
response_to_user_text,
|
||||
reply_markup=reply_markup,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
Helper функция для применения скидок к платежам
|
||||
Используется всеми платежными обработчиками
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Tuple
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from db.dal import active_discount_dal
|
||||
|
||||
|
||||
async def apply_discount_to_payment(
|
||||
session: AsyncSession,
|
||||
user_id: int,
|
||||
original_price: float,
|
||||
promo_code_service=None
|
||||
) -> Tuple[float, Optional[float], Optional[int]]:
|
||||
"""
|
||||
Apply active discount to payment if exists.
|
||||
|
||||
Returns:
|
||||
(final_price, discount_amount, promo_code_id)
|
||||
"""
|
||||
if not promo_code_service:
|
||||
return original_price, None, None
|
||||
|
||||
active_discount = await active_discount_dal.get_active_discount(session, user_id)
|
||||
if not active_discount:
|
||||
return original_price, None, None
|
||||
|
||||
# Calculate discounted price
|
||||
final_price, discount_amount = promo_code_service.calculate_discounted_price(
|
||||
original_price, active_discount.discount_percentage
|
||||
)
|
||||
|
||||
logging.info(
|
||||
f"Applying {active_discount.discount_percentage}% discount to payment for user {user_id}: "
|
||||
f"{original_price} -> {final_price}"
|
||||
)
|
||||
|
||||
return final_price, discount_amount, active_discount.promo_code_id
|
||||
@@ -17,6 +17,7 @@ async def select_subscription_period_callback_handler(
|
||||
settings: Settings,
|
||||
i18n_data: dict,
|
||||
session: AsyncSession,
|
||||
promo_code_service=None, # Injected from dispatcher
|
||||
):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
@@ -49,6 +50,29 @@ async def select_subscription_period_callback_handler(
|
||||
stars_price = stars_price_source.get(months)
|
||||
currency_symbol_val = settings.DEFAULT_CURRENCY_SYMBOL
|
||||
|
||||
# Check for active discount and apply if exists
|
||||
discount_text = ""
|
||||
if promo_code_service and price_rub:
|
||||
active_discount_info = await promo_code_service.get_user_active_discount(
|
||||
session, callback.from_user.id
|
||||
)
|
||||
|
||||
if active_discount_info:
|
||||
discount_pct, promo_code = active_discount_info
|
||||
original_price_rub = price_rub
|
||||
price_rub, discount_amt = promo_code_service.calculate_discounted_price(
|
||||
price_rub, discount_pct
|
||||
)
|
||||
discount_text = get_text(
|
||||
"active_discount_notice",
|
||||
code=promo_code,
|
||||
discount_pct=discount_pct,
|
||||
original_price=original_price_rub,
|
||||
discounted_price=price_rub,
|
||||
discount_amount=discount_amt
|
||||
)
|
||||
# Note: Stars prices typically don't get discounts (can be added if needed)
|
||||
|
||||
if price_rub is None:
|
||||
if traffic_mode and not price_source and stars_price is not None:
|
||||
currency_methods_enabled = any(
|
||||
@@ -83,6 +107,9 @@ async def select_subscription_period_callback_handler(
|
||||
return
|
||||
|
||||
text_content = get_text("choose_payment_method_traffic") if traffic_mode else get_text("choose_payment_method")
|
||||
if discount_text:
|
||||
text_content = f"{discount_text}\n\n{text_content}"
|
||||
|
||||
reply_markup = get_payment_method_keyboard(
|
||||
months,
|
||||
price_rub,
|
||||
|
||||
@@ -13,7 +13,7 @@ from bot.keyboards.inline.user_keyboards import (
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
from bot.services.yookassa_service import YooKassaService
|
||||
from config.settings import Settings
|
||||
from db.dal import payment_dal, user_billing_dal
|
||||
from db.dal import payment_dal, user_billing_dal, active_discount_dal
|
||||
|
||||
router = Router(name="user_subscription_payments_yookassa_router")
|
||||
|
||||
@@ -60,6 +60,7 @@ async def _initiate_yk_payment(
|
||||
settings: Settings,
|
||||
session: AsyncSession,
|
||||
yookassa_service: YooKassaService,
|
||||
promo_code_service, # NEW: Added promo_code_service
|
||||
i18n: Optional[JsonI18n],
|
||||
current_lang: str,
|
||||
get_text,
|
||||
@@ -77,6 +78,24 @@ async def _initiate_yk_payment(
|
||||
if not callback.message:
|
||||
return False
|
||||
|
||||
# NEW: Check for active discount and apply if exists
|
||||
original_price = price_rub
|
||||
discount_amount = None
|
||||
active_promo_code_id = None
|
||||
|
||||
if promo_code_service:
|
||||
active_discount = await active_discount_dal.get_active_discount(session, user_id)
|
||||
if active_discount:
|
||||
final_price, discount_amount = promo_code_service.calculate_discounted_price(
|
||||
price_rub, active_discount.discount_percentage
|
||||
)
|
||||
price_rub = final_price
|
||||
active_promo_code_id = active_discount.promo_code_id
|
||||
logging.info(
|
||||
f"Applying {active_discount.discount_percentage}% discount to YooKassa payment: "
|
||||
f"{original_price} -> {price_rub}"
|
||||
)
|
||||
|
||||
payment_description = (
|
||||
get_text("payment_description_traffic", traffic_gb=_format_value(months))
|
||||
if sale_mode == "traffic"
|
||||
@@ -84,11 +103,14 @@ async def _initiate_yk_payment(
|
||||
)
|
||||
payment_record_data = {
|
||||
"user_id": user_id,
|
||||
"amount": price_rub,
|
||||
"amount": price_rub, # Discounted amount
|
||||
"original_amount": original_price if discount_amount else None, # NEW
|
||||
"discount_applied": discount_amount, # NEW
|
||||
"currency": currency_code_for_yk,
|
||||
"status": "pending_yookassa",
|
||||
"description": payment_description,
|
||||
"subscription_duration_months": int(months),
|
||||
"promo_code_id": active_promo_code_id, # NEW: Link to promo code
|
||||
}
|
||||
|
||||
db_payment_record = None
|
||||
@@ -319,7 +341,7 @@ async def _initiate_yk_payment(
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("pay_yk:"))
|
||||
async def pay_yk_callback_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession):
|
||||
async def pay_yk_callback_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession, promo_code_service=None):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
get_text = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs) if i18n else key
|
||||
@@ -417,6 +439,7 @@ async def pay_yk_callback_handler(callback: types.CallbackQuery, settings: Setti
|
||||
settings=settings,
|
||||
session=session,
|
||||
yookassa_service=yookassa_service,
|
||||
promo_code_service=promo_code_service,
|
||||
i18n=i18n,
|
||||
current_lang=current_lang,
|
||||
get_text=get_text,
|
||||
@@ -435,7 +458,7 @@ async def pay_yk_callback_handler(callback: types.CallbackQuery, settings: Setti
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("pay_yk_new:"))
|
||||
async def pay_yk_new_card_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession):
|
||||
async def pay_yk_new_card_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession, promo_code_service=None):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
get_text = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs) if i18n else key
|
||||
@@ -491,6 +514,7 @@ async def pay_yk_new_card_handler(callback: types.CallbackQuery, settings: Setti
|
||||
settings=settings,
|
||||
session=session,
|
||||
yookassa_service=yookassa_service,
|
||||
promo_code_service=promo_code_service,
|
||||
i18n=i18n,
|
||||
current_lang=current_lang,
|
||||
get_text=get_text,
|
||||
@@ -653,7 +677,7 @@ async def pay_yk_saved_list_handler(callback: types.CallbackQuery, settings: Set
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("pay_yk_use_saved:"))
|
||||
async def pay_yk_use_saved_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession):
|
||||
async def pay_yk_use_saved_handler(callback: types.CallbackQuery, settings: Settings, i18n_data: dict, yookassa_service: YooKassaService, session: AsyncSession, promo_code_service=None):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
get_text = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs) if i18n else key
|
||||
@@ -752,6 +776,7 @@ async def pay_yk_use_saved_handler(callback: types.CallbackQuery, settings: Sett
|
||||
settings=settings,
|
||||
session=session,
|
||||
yookassa_service=yookassa_service,
|
||||
promo_code_service=promo_code_service,
|
||||
i18n=i18n,
|
||||
current_lang=current_lang,
|
||||
get_text=get_text,
|
||||
|
||||
Reference in New Issue
Block a user