feat(promo): Добавлены промокоды на скидку в процентах
This commit is contained in:
@@ -28,25 +28,82 @@ async def create_promo_prompt_handler(callback: types.CallbackQuery,
|
||||
return
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
|
||||
# Step 1: Ask for promo code
|
||||
# Step 0: Ask for promo type (bonus_days or discount)
|
||||
prompt_text = _(
|
||||
"admin_promo_step1_code"
|
||||
"admin_promo_step0_type"
|
||||
)
|
||||
|
||||
# Create keyboard for type selection
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=_("admin_promo_type_bonus_days"),
|
||||
callback_data="promo_type_select:bonus_days"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=_("admin_promo_type_discount"),
|
||||
callback_data="promo_type_select:discount"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=_("admin_back_to_panel"),
|
||||
callback_data="admin_action:main"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
await callback.message.edit_text(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML")
|
||||
except Exception as e:
|
||||
logging.warning(
|
||||
f"Could not edit message for promo prompt: {e}. Sending new.")
|
||||
f"Could not edit message for promo type prompt: {e}. Sending new.")
|
||||
await callback.message.answer(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML")
|
||||
await callback.answer()
|
||||
await state.set_state(AdminStates.waiting_for_promo_code)
|
||||
await state.set_state(AdminStates.waiting_for_promo_type_selection)
|
||||
|
||||
|
||||
# Step 0: Process type selection
|
||||
@router.callback_query(F.data.startswith("promo_type_select:"), StateFilter(AdminStates.waiting_for_promo_type_selection))
|
||||
async def process_promo_type_selection(callback: types.CallbackQuery,
|
||||
state: FSMContext,
|
||||
i18n_data: dict,
|
||||
settings: Settings):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
if not i18n or not callback.message:
|
||||
await callback.answer("Error processing type selection.", show_alert=True)
|
||||
return
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
|
||||
try:
|
||||
promo_type = callback.data.split(":")[-1] # "bonus_days" or "discount"
|
||||
await state.update_data(promo_type=promo_type)
|
||||
|
||||
# Step 1: Ask for promo code
|
||||
prompt_text = _(
|
||||
"admin_promo_step1_code"
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
await callback.answer()
|
||||
await state.set_state(AdminStates.waiting_for_promo_code)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing promo type selection: {e}")
|
||||
await callback.message.answer(_("error_occurred_try_again"))
|
||||
await callback.answer()
|
||||
|
||||
|
||||
# Step 1: Process promo code
|
||||
@@ -80,19 +137,31 @@ async def process_promo_code_handler(message: types.Message,
|
||||
return
|
||||
|
||||
await state.update_data(promo_code=code_str)
|
||||
|
||||
# Step 2: Ask for bonus days
|
||||
prompt_text = _(
|
||||
"admin_promo_step2_bonus_days",
|
||||
code=code_str
|
||||
)
|
||||
|
||||
|
||||
# Get promo type from state
|
||||
data = await state.get_data()
|
||||
promo_type = data.get("promo_type", "bonus_days")
|
||||
|
||||
# Step 2: Ask for bonus days OR discount percentage based on type
|
||||
if promo_type == "discount":
|
||||
prompt_text = _(
|
||||
"admin_promo_step2_discount_percentage",
|
||||
code=code_str
|
||||
)
|
||||
next_state = AdminStates.waiting_for_promo_discount_percentage
|
||||
else:
|
||||
prompt_text = _(
|
||||
"admin_promo_step2_bonus_days",
|
||||
code=code_str
|
||||
)
|
||||
next_state = AdminStates.waiting_for_promo_bonus_days
|
||||
|
||||
await message.answer(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
await state.set_state(AdminStates.waiting_for_promo_bonus_days)
|
||||
await state.set_state(next_state)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing promo code: {e}")
|
||||
@@ -119,9 +188,9 @@ async def process_promo_bonus_days_handler(message: types.Message,
|
||||
"admin_promo_invalid_bonus_days"
|
||||
))
|
||||
return
|
||||
|
||||
|
||||
await state.update_data(bonus_days=bonus_days)
|
||||
|
||||
|
||||
# Step 3: Ask for max activations
|
||||
data = await state.get_data()
|
||||
prompt_text = _(
|
||||
@@ -129,14 +198,14 @@ async def process_promo_bonus_days_handler(message: types.Message,
|
||||
code=data.get("promo_code"),
|
||||
bonus_days=bonus_days
|
||||
)
|
||||
|
||||
|
||||
await message.answer(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
await state.set_state(AdminStates.waiting_for_promo_max_activations)
|
||||
|
||||
|
||||
except ValueError:
|
||||
await message.answer(_(
|
||||
"admin_promo_invalid_number"
|
||||
@@ -146,6 +215,53 @@ async def process_promo_bonus_days_handler(message: types.Message,
|
||||
await message.answer(_("error_occurred_try_again"))
|
||||
|
||||
|
||||
# Step 2: Process discount percentage
|
||||
@router.message(AdminStates.waiting_for_promo_discount_percentage, F.text)
|
||||
async def process_promo_discount_percentage_handler(message: types.Message,
|
||||
state: FSMContext,
|
||||
i18n_data: dict,
|
||||
settings: Settings):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
if not i18n:
|
||||
await message.reply("Language service error.")
|
||||
return
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
|
||||
try:
|
||||
discount_percentage = int(message.text.strip())
|
||||
if not (1 <= discount_percentage <= 100):
|
||||
await message.answer(
|
||||
"❌ Discount percentage must be between 1 and 100."
|
||||
)
|
||||
return
|
||||
|
||||
await state.update_data(discount_percentage=discount_percentage)
|
||||
|
||||
# Step 3: Ask for max activations
|
||||
data = await state.get_data()
|
||||
prompt_text = _(
|
||||
"admin_promo_step3_max_activations",
|
||||
code=data.get("promo_code"),
|
||||
bonus_days=f"{discount_percentage}%" # Display as percentage in place of bonus_days
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
prompt_text,
|
||||
reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
await state.set_state(AdminStates.waiting_for_promo_max_activations)
|
||||
|
||||
except ValueError:
|
||||
await message.answer(_(
|
||||
"admin_promo_invalid_number"
|
||||
))
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing discount percentage: {e}")
|
||||
await message.answer(_("error_occurred_try_again"))
|
||||
|
||||
|
||||
# Step 3: Process max activations
|
||||
@router.message(AdminStates.waiting_for_promo_max_activations, F.text)
|
||||
async def process_promo_max_activations_handler(message: types.Message,
|
||||
@@ -310,37 +426,53 @@ async def create_promo_code_final(callback_or_message,
|
||||
|
||||
try:
|
||||
data = await state.get_data()
|
||||
|
||||
promo_type = data.get("promo_type", "bonus_days")
|
||||
|
||||
# Prepare promo code data
|
||||
promo_data = {
|
||||
"code": data["promo_code"],
|
||||
"bonus_days": data["bonus_days"],
|
||||
"promo_type": promo_type,
|
||||
"max_activations": data["max_activations"],
|
||||
"current_activations": 0,
|
||||
"is_active": True,
|
||||
"created_by_admin_id": callback_or_message.from_user.id,
|
||||
"created_at": datetime.now(timezone.utc)
|
||||
}
|
||||
|
||||
|
||||
# Set type-specific fields
|
||||
if promo_type == "discount":
|
||||
promo_data["discount_percentage"] = data["discount_percentage"]
|
||||
promo_data["bonus_days"] = None
|
||||
else:
|
||||
promo_data["bonus_days"] = data["bonus_days"]
|
||||
promo_data["discount_percentage"] = None
|
||||
|
||||
# Set validity
|
||||
if data.get("validity_days"):
|
||||
promo_data["valid_until"] = datetime.now(timezone.utc) + timedelta(days=data["validity_days"])
|
||||
else:
|
||||
promo_data["valid_until"] = None
|
||||
|
||||
|
||||
# Create promo code
|
||||
created_promo = await promo_code_dal.create_promo_code(session, promo_data)
|
||||
await session.commit()
|
||||
|
||||
|
||||
# Log successful creation
|
||||
logging.info(f"Promo code '{data['promo_code']}' created with ID {created_promo.promo_code_id}")
|
||||
|
||||
logging.info(f"Promo code '{data['promo_code']}' ({promo_type}) created with ID {created_promo.promo_code_id}")
|
||||
|
||||
# Success message
|
||||
valid_until_str = _("admin_promo_unlimited") if not data.get("validity_days") else f"{data['validity_days']} дней"
|
||||
valid_until_str = _("admin_promo_unlimited") if not data.get("validity_days") else f"{data['validity_days']} days"
|
||||
|
||||
# Format success message based on type
|
||||
if promo_type == "discount":
|
||||
value_display = f"{data['discount_percentage']}%"
|
||||
else:
|
||||
value_display = f"{data['bonus_days']} days"
|
||||
|
||||
success_text = _(
|
||||
"admin_promo_created_success",
|
||||
code=data["promo_code"],
|
||||
bonus_days=data["bonus_days"],
|
||||
bonus_days=value_display, # Reusing bonus_days placeholder for display
|
||||
max_activations=data["max_activations"],
|
||||
valid_until_str=valid_until_str
|
||||
)
|
||||
@@ -385,8 +517,10 @@ async def create_promo_code_final(callback_or_message,
|
||||
@router.callback_query(
|
||||
F.data == "admin_action:main",
|
||||
StateFilter(
|
||||
AdminStates.waiting_for_promo_type_selection,
|
||||
AdminStates.waiting_for_promo_code,
|
||||
AdminStates.waiting_for_promo_bonus_days,
|
||||
AdminStates.waiting_for_promo_discount_percentage,
|
||||
AdminStates.waiting_for_promo_max_activations,
|
||||
AdminStates.waiting_for_promo_validity_days,
|
||||
),
|
||||
|
||||
@@ -47,9 +47,19 @@ async def get_promo_detail_text_and_keyboard(promo_id: int, session: AsyncSessio
|
||||
|
||||
created = promo.created_at.strftime("%d.%m.%Y %H:%M") if promo.created_at else "N/A"
|
||||
|
||||
# Determine promo type and value to display
|
||||
promo_type = getattr(promo, "promo_type", "bonus_days")
|
||||
if promo_type == "discount":
|
||||
type_name = _("admin_promo_type_discount")
|
||||
value_line = _("admin_promo_card_discount_percentage", percentage=promo.discount_percentage)
|
||||
else:
|
||||
type_name = _("admin_promo_type_bonus_days")
|
||||
value_line = _("admin_promo_card_bonus_days", days=promo.bonus_days)
|
||||
|
||||
text = "\n".join([
|
||||
_("admin_promo_card_title", code=promo.code),
|
||||
_("admin_promo_card_bonus_days", days=promo.bonus_days),
|
||||
_("admin_promo_card_type", type=type_name),
|
||||
value_line,
|
||||
_("admin_promo_card_activations", current=promo.current_activations, max=promo.max_activations),
|
||||
_("admin_promo_card_validity", validity=validity),
|
||||
_("admin_promo_card_status", status=status),
|
||||
@@ -76,12 +86,22 @@ async def view_promo_codes_handler(callback: types.CallbackQuery, i18n_data: dic
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
|
||||
promo_models = await promo_code_dal.get_all_active_promo_codes(session, limit=20, offset=0)
|
||||
text = f"{_('admin_active_promos_list_header')}\n\n{_('admin_no_active_promos')}" if not promo_models else "\n".join(
|
||||
[_("admin_active_promos_list_header"), ""] + [
|
||||
f"{get_promo_status_emoji_and_text(p, i18n, current_lang)[0]} <code>{p.code}</code> | 🎁 {p.bonus_days}д | 📊 {p.current_activations}/{p.max_activations} | ⏰ {p.valid_until.strftime('%d.%m.%Y') if p.valid_until else _('admin_promo_valid_indefinitely')}"
|
||||
for p in promo_models
|
||||
]
|
||||
)
|
||||
if not promo_models:
|
||||
text = f"{_('admin_active_promos_list_header')}\n\n{_('admin_no_active_promos')}"
|
||||
else:
|
||||
promo_lines = [_("admin_active_promos_list_header"), ""]
|
||||
for p in promo_models:
|
||||
status_emoji = get_promo_status_emoji_and_text(p, i18n, current_lang)[0]
|
||||
promo_type = getattr(p, "promo_type", "bonus_days")
|
||||
if promo_type == "discount":
|
||||
value_display = f"💰 {p.discount_percentage}%"
|
||||
else:
|
||||
value_display = f"🎁 {p.bonus_days}д"
|
||||
validity_display = p.valid_until.strftime('%d.%m.%Y') if p.valid_until else _('admin_promo_valid_indefinitely')
|
||||
promo_lines.append(
|
||||
f"{status_emoji} <code>{p.code}</code> | {value_display} | 📊 {p.current_activations}/{p.max_activations} | ⏰ {validity_display}"
|
||||
)
|
||||
text = "\n".join(promo_lines)
|
||||
|
||||
await callback.message.edit_text(text, reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n), parse_mode="HTML")
|
||||
await callback.answer()
|
||||
@@ -300,7 +320,9 @@ async def promo_export_all_handler(callback: types.CallbackQuery, i18n_data: dic
|
||||
# CSV headers (forced to English)
|
||||
writer.writerow([
|
||||
i18n.gettext(export_lang, "admin_promo_csv_code"),
|
||||
"Type",
|
||||
i18n.gettext(export_lang, "admin_promo_csv_bonus_days"),
|
||||
"Discount %",
|
||||
i18n.gettext(export_lang, "admin_promo_csv_max_activations"),
|
||||
i18n.gettext(export_lang, "admin_promo_csv_current_activations"),
|
||||
i18n.gettext(export_lang, "admin_promo_csv_status"),
|
||||
@@ -309,15 +331,22 @@ async def promo_export_all_handler(callback: types.CallbackQuery, i18n_data: dic
|
||||
i18n.gettext(export_lang, "admin_promo_csv_created_at"),
|
||||
i18n.gettext(export_lang, "admin_promo_csv_created_by_admin_id"),
|
||||
])
|
||||
|
||||
|
||||
for promo in all_promos:
|
||||
# Определяем статус
|
||||
status_emoji, status_text = get_promo_status_emoji_and_text(promo, i18n, export_lang)
|
||||
|
||||
|
||||
# Determine promo type and values
|
||||
promo_type = getattr(promo, "promo_type", "bonus_days")
|
||||
bonus_days_val = promo.bonus_days if promo_type == "bonus_days" else "N/A"
|
||||
discount_val = promo.discount_percentage if promo_type == "discount" else "N/A"
|
||||
|
||||
# Формируем данные для CSV
|
||||
row = [
|
||||
promo.code,
|
||||
promo.bonus_days,
|
||||
promo_type,
|
||||
bonus_days_val,
|
||||
discount_val,
|
||||
promo.max_activations,
|
||||
promo.current_activations,
|
||||
status_text,
|
||||
@@ -374,13 +403,26 @@ async def promo_edit_select_handler(callback: types.CallbackQuery, i18n_data: di
|
||||
return
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
promo_id = int(callback.data.split(":")[1])
|
||||
|
||||
|
||||
# Get promo to check type
|
||||
promo = await promo_code_dal.get_promo_code_by_id(session, promo_id)
|
||||
if not promo:
|
||||
await callback.answer(_("admin_promo_not_found"), show_alert=True)
|
||||
return
|
||||
|
||||
promo_type = getattr(promo, "promo_type", "bonus_days")
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text=_("admin_promo_edit_bonus_days"), callback_data=f"promo_edit_field:bonus_days:{promo_id}"))
|
||||
# Show appropriate edit option based on type
|
||||
if promo_type == "discount":
|
||||
builder.row(InlineKeyboardButton(text="💰 Edit Discount %", callback_data=f"promo_edit_field:discount_percentage:{promo_id}"))
|
||||
else:
|
||||
builder.row(InlineKeyboardButton(text=_("admin_promo_edit_bonus_days"), callback_data=f"promo_edit_field:bonus_days:{promo_id}"))
|
||||
|
||||
builder.row(InlineKeyboardButton(text=_("admin_promo_edit_max_activations"), callback_data=f"promo_edit_field:max_activations:{promo_id}"))
|
||||
builder.row(InlineKeyboardButton(text=_("admin_promo_edit_validity"), callback_data=f"promo_edit_field:valid_until:{promo_id}"))
|
||||
builder.row(InlineKeyboardButton(text=_("admin_promo_back_to_detail_button"), callback_data=f"promo_detail:{promo_id}"))
|
||||
|
||||
|
||||
await callback.message.edit_text(_("admin_promo_edit_select_field"), reply_markup=builder.as_markup())
|
||||
await callback.answer()
|
||||
|
||||
@@ -394,14 +436,22 @@ async def promo_edit_field_handler(callback: types.CallbackQuery, state: FSMCont
|
||||
|
||||
action, field, promo_id_str = callback.data.split(":")
|
||||
await state.update_data(promo_id=int(promo_id_str), field_to_edit=field)
|
||||
|
||||
|
||||
prompts = {
|
||||
"bonus_days": "admin_promo_prompt_bonus_days",
|
||||
"discount_percentage": "admin_promo_prompt_discount_percentage",
|
||||
"max_activations": "admin_promo_prompt_max_activations",
|
||||
"valid_until": "admin_promo_prompt_validity_days"
|
||||
}
|
||||
|
||||
prompt_key = prompts.get(field, "error_occurred_try_again")
|
||||
if field == "discount_percentage":
|
||||
prompt_text = "Enter the new discount percentage (1-100):"
|
||||
else:
|
||||
prompt_text = _(prompt_key)
|
||||
|
||||
await state.set_state(AdminStates.waiting_for_promo_edit_details)
|
||||
await callback.message.edit_text(_(prompts.get(field, "error_occurred_try_again")))
|
||||
await callback.message.edit_text(prompt_text)
|
||||
await callback.answer()
|
||||
|
||||
@router.message(StateFilter(AdminStates.waiting_for_promo_edit_details))
|
||||
@@ -418,9 +468,15 @@ async def process_promo_edit_details(message: types.Message, state: FSMContext,
|
||||
try:
|
||||
value = message.text
|
||||
update_data = {}
|
||||
|
||||
|
||||
if field == "bonus_days":
|
||||
update_data["bonus_days"] = int(value)
|
||||
elif field == "discount_percentage":
|
||||
discount_pct = int(value)
|
||||
if not (1 <= discount_pct <= 100):
|
||||
await message.answer("❌ Discount percentage must be between 1 and 100.")
|
||||
return
|
||||
update_data["discount_percentage"] = discount_pct
|
||||
elif field == "max_activations":
|
||||
update_data["max_activations"] = int(value)
|
||||
elif field == "valid_until":
|
||||
@@ -433,7 +489,7 @@ async def process_promo_edit_details(message: types.Message, state: FSMContext,
|
||||
if await promo_code_dal.update_promo_code(session, promo_id, update_data):
|
||||
await session.commit()
|
||||
await message.answer(_("admin_promo_edit_success"))
|
||||
|
||||
|
||||
# Reset state and show updated details
|
||||
await state.clear()
|
||||
text, keyboard = await get_promo_detail_text_and_keyboard(promo_id, session, i18n, current_lang)
|
||||
|
||||
@@ -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