Add hook system for tariff group management

This commit is contained in:
Capybara-z
2025-10-04 23:18:27 +03:00
parent 5da236ce5d
commit 9feeb0e1d5
3 changed files with 108 additions and 2 deletions
+42
View File
@@ -166,6 +166,25 @@ async def handle_key_creation(
else:
await state.update_data(discount_info=None)
try:
hook_results = await run_hooks(
"purchase_tariff_group_override",
chat_id=tg_id,
admin=False,
session=session,
original_group=group_code
)
for hook_result in hook_results:
if hook_result.get("override_group"):
group_code = hook_result["override_group"]
logger.info(f"[PURCHASE] Тарифная группа переопределена хуком: {group_code}")
if hook_result.get("discount_info"):
await state.update_data(discount_info=hook_result["discount_info"])
break
except Exception as e:
logger.warning(f"[PURCHASE] Ошибка при применении хуков переопределения группы: {e}")
tariffs_data = await get_tariffs(session, group_code=group_code, with_subgroup_weights=True)
tariffs = [t for t in tariffs_data["tariffs"] if t.get("is_active")]
subgroup_weights = tariffs_data["subgroup_weights"]
@@ -371,6 +390,29 @@ async def select_tariff_plan(callback_query: CallbackQuery, session: Any, state:
await callback_query.answer()
return
try:
hook_results = await run_hooks(
"check_discount_validity",
chat_id=tg_id,
admin=False,
session=session,
tariff_group=tariff.get("group_code")
)
for hook_result in hook_results:
if not hook_result.get("valid", True):
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text=MAIN_MENU, callback_data="profile"))
await edit_or_send_message(
target_message=callback_query.message,
text=hook_result.get("message", "❌ Скидка недоступна. Пожалуйста, выберите тариф заново."),
reply_markup=builder.as_markup(),
)
await callback_query.answer()
return
except Exception as e:
logger.warning(f"[PURCHASE] Ошибка при проверке скидок через хуки: {e}")
duration_days = tariff["duration_days"]
price_rub = tariff["price_rub"]
+49 -1
View File
@@ -95,7 +95,23 @@ async def process_callback_renew_key(callback_query: CallbackQuery, state: FSMCo
if tariff_id:
if await check_tariff_exists(session, tariff_id):
current_tariff = await get_tariff_by_id(session, tariff_id)
if current_tariff["group_code"] not in ["discounts", "discounts_max", "gifts", "trial"]:
forbidden_groups = ["discounts", "discounts_max", "gifts", "trial"]
try:
hook_results = await run_hooks(
"renewal_forbidden_groups",
chat_id=tg_id,
admin=False,
session=session
)
for hook_result in hook_results:
additional_groups = hook_result.get("additional_groups", [])
forbidden_groups.extend(additional_groups)
except Exception as e:
logger.warning(f"[RENEW] Ошибка при получении дополнительных групп: {e}")
if current_tariff["group_code"] not in forbidden_groups:
group_code = current_tariff["group_code"]
discount_info = await check_hot_lead_discount(session, tg_id)
@@ -103,6 +119,22 @@ async def process_callback_renew_key(callback_query: CallbackQuery, state: FSMCo
if discount_info.get("available"):
group_code = discount_info["tariff_group"]
try:
hook_results = await run_hooks(
"purchase_tariff_group_override",
chat_id=tg_id,
admin=False,
session=session,
original_group=group_code
)
for hook_result in hook_results:
if hook_result.get("override_group"):
group_code = hook_result["override_group"]
logger.info(f"[RENEW] Тарифная группа переопределена хуком для продления: {group_code}")
break
except Exception as e:
logger.warning(f"[RENEW] Ошибка при применении хуков переопределения группы: {e}")
tariffs_data = await get_tariffs(session, group_code=group_code, with_subgroup_weights=True)
tariffs = [t for t in tariffs_data["tariffs"] if t.get("is_active")]
subgroup_weights = tariffs_data["subgroup_weights"]
@@ -234,6 +266,22 @@ async def show_tariffs_in_renew_subgroup(callback: CallbackQuery, state: FSMCont
if discount_info.get("available"):
group_code = discount_info["tariff_group"]
try:
hook_results = await run_hooks(
"purchase_tariff_group_override",
chat_id=tg_id,
admin=False,
session=session,
original_group=group_code
)
for hook_result in hook_results:
if hook_result.get("override_group"):
group_code = hook_result["override_group"]
logger.info(f"[RENEW_SUBGROUP] Тарифная группа переопределена хуком: {group_code}")
break
except Exception as e:
logger.warning(f"[RENEW_SUBGROUP] Ошибка при применении хуков переопределения группы: {e}")
subgroup = await find_subgroup_by_hash(session, subgroup_hash, group_code)
if not subgroup:
await callback.message.answer("❌ Подгруппа не найдена.")
@@ -510,7 +510,23 @@ async def process_auto_renew_or_notify(
else:
if await check_tariff_exists(conn, tariff_id):
current_tariff = await get_tariff_by_id(conn, tariff_id)
if current_tariff["group_code"] in ["discounts", "discounts_max", "gifts", "trial"]:
forbidden_groups = ["discounts", "discounts_max", "gifts", "trial"]
try:
hook_results = await run_hooks(
"renewal_forbidden_groups",
chat_id=tg_id,
admin=False,
session=conn
)
for hook_result in hook_results:
additional_groups = hook_result.get("additional_groups", [])
forbidden_groups.extend(additional_groups)
except Exception as e:
logger.warning(f"[AUTO_RENEW] Ошибка при получении дополнительных групп: {e}")
if current_tariff["group_code"] in forbidden_groups:
cluster_tariffs = [t for t in tariffs if t["is_active"] and balance >= t["price_rub"]]
if cluster_tariffs:
cluster_tariffs_31 = [t for t in cluster_tariffs if t["duration_days"] <= 31]