Compare commits

...

58 Commits

Author SHA1 Message Date
Egor 6d4430c639 Merge pull request #2753 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.33.0
2026-03-18 02:02:09 +03:00
github-actions[bot] 911df7a05c chore(main): release 3.33.0 2026-03-17 23:01:41 +00:00
Egor f106ce8216 Merge pull request #2752 from BEDOLAGA-DEV/dev
Dev
2026-03-18 02:00:59 +03:00
Fringg dcff6947dd style: ruff format 2026-03-18 01:59:12 +03:00
Fringg 4966e39eb9 fix: скрыть плашку верификации email при выключенной верификации
- Добавлен verification_enabled в ответ /cabinet/branding/email-auth
- Фронтенд использует его для скрытия баннера и бейджа
2026-03-18 01:52:54 +03:00
Fringg 4abb8cb1a3 fix: исправлены проблемы RioPay интеграции после ревью
- Модель: user_id nullable=True + ondelete='SET NULL' (не применилось ранее)
- order_id для гостей: 'rpguest_xxx' вместо 'rpNone_xxx'
- Миграция: добавлено пересоздание FK с ON DELETE SET NULL
- get_latest_payment_by_method: добавлен RioPayPayment в model_map
2026-03-18 00:18:15 +03:00
Fringg 04f4e6bf6e feat: добавлена поддержка RioPay для лендингов и подарков
- Добавлен RioPay в create_guest_payment (landing/gift покупки)
- user_id в RioPayPayment теперь nullable (для гостевых платежей)
- Добавлен guest purchase flow в _finalize_riopay_payment
- Миграция 0039: riopay_payments.user_id nullable
2026-03-18 00:10:51 +03:00
Fringg 3d1fbc70f8 feat: добавлена поддержка RioPay в кабинете
- Добавлен RioPay в create_topup endpoint (cabinet balance)
- Добавлен маппинг статусов RioPay в _get_status_info
- Добавлена поддержка ручной проверки RioPay платежей
- Добавлена автопроверка RioPay в payment_verification_service
- Добавлены success_url/fail_url параметры в create_riopay_payment mixin
2026-03-18 00:05:07 +03:00
Fringg 3089c1704b fix: исправлен расчёт конверсии в статистике продаж
- Добавлен fallback через has_had_paid_subscription для подсчёта конверсий
- Исправлен знаменатель: total_trial_starters = new_trials + conversions
- Ограничение conversion_rate до 100% максимум
- Исправлен .is_(True) вместо == True в subscription_conversion.py
2026-03-17 23:46:15 +03:00
Fringg 20eff6170f fix: add back button to payment amount validation errors
All min/max amount error messages in payment handlers now include
a back button keyboard, so users aren't stuck without navigation.
Fixed 30 message.answer() calls across 12 payment handler files.
2026-03-17 23:34:05 +03:00
Fringg 038c34e52a fix: swap Caddy auth headers — api_key to Authorization, caddy_token to X-Api-Key
Caddy Security expects the caddy token in X-Api-Key and the Remnawave
API key in Authorization: Bearer. The headers were swapped, causing
401 errors for users with Caddy auth type.
2026-03-17 23:28:44 +03:00
Fringg 77f1a764d5 fix: merge phantom users into active accounts on /start
When a user purchases on a landing page by username and Bot.get_chat()
fails, a phantom user (telegram_id=NULL) is created. If that user
already has an active bot account, the phantom was never merged,
creating duplicate user records.

Now cmd_start checks for phantom users matching the active user's
username and merges them: transfers GuestPurchase records, balance,
and subscription (if active user has none). Phantom is soft-deleted
(status=DELETED, username=NULL) to preserve payment/transaction audit
trail and avoid CASCADE FK issues.
2026-03-17 23:06:02 +03:00
Fringg 641da949a9 fix: enforce promo group authorization on country/server selection
Previously, users could retain access to servers removed from their
promo group by re-submitting already-connected UUIDs in country
selection requests. The validation allowed any UUID present in
current connected_squads, bypassing promo group checks.

Now all selected server UUIDs must be in the user's allowed promo
group set. Unauthorized servers are rejected (cabinet/bot) or
filtered out (miniapp). Fixes authorization bypass across all 3
surfaces: cabinet, Telegram bot, and miniapp.
2026-03-17 22:30:57 +03:00
Fringg 3f0b24c1ec fix: add sync_squads=True to admin tariff change handler
Missed in the previous fix — admin tariff change at
handlers/admin/users.py sets connected_squads from tariff but
did not pass sync_squads=True to update_remnawave_user.
2026-03-17 22:25:01 +03:00
Fringg c34fdd10a0 fix: sync squads to Remnawave panel on tariff purchase/switch
When sync_squads parameter was introduced (4aaf0ddd) to prevent FK
violations from stale squad UUIDs, all update_remnawave_user calls
defaulted to sync_squads=False. This broke squad synchronization for
purchase/tariff-change flows where squads are freshly assigned and
must be sent to the panel.

Adds sync_squads=True to all purchase, tariff switch, and country
selection call sites across cabinet, bot handlers, miniapp, and
auto-purchase service.
2026-03-17 22:17:35 +03:00
Fringg 72b5305b87 fix: review findings — db.commit, isinstance guard, constants, ACTIVE check
- Explicit db.commit() for cabinet_last_login before _store_refresh_token
- isinstance(callback.message, types.Message) guard in process_webauth_confirm
- Check UserStatus.ACTIVE (not just DELETED) in bot callback handler
- isinstance guard in consume_web_auth_token for type safety
- Named constants: WEB_AUTH_LINKED_TTL, WEB_AUTH_TOKEN_MIN_LENGTH
- Use str.removeprefix() instead of hardcoded slice
- Move link_web_auth_token import to module level
2026-03-17 21:56:52 +03:00
Fringg 099391eb5f fix: deep link auth security and reliability fixes
- Atomic GETDEL in link_web_auth_token to prevent TOCTOU race
- Session fixation protection: inline keyboard confirmation before linking
- Poll rate limit 30→60/min to support 2.5s polling interval
- Fix double commit in poll endpoint (cabinet_last_login before _store_refresh_token)
- Replace magic string 'active' with UserStatus.ACTIVE.value
- Add response_model=AuthResponse to poll endpoint
- Validate bot_username is set (503 if empty)
- Move web_auth imports to module level
2026-03-17 21:46:09 +03:00
Fringg 322d457652 feat: deep link авторизация в кабинете при блокировке oauth.telegram.org
Когда скрипт Telegram Login Widget не загружается (заблокирован),
фронтенд автоматически переключается на deep link авторизацию:
- POST /cabinet/auth/deeplink/request — генерирует одноразовый токен
- Пользователь открывает t.me/bot?start=webauth_TOKEN
- Бот связывает токен с Telegram-аккаунтом
- POST /cabinet/auth/deeplink/poll — фронтенд получает JWT токены

Новый сервис: app/services/web_auth_service.py (Redis, TTL 5 мин)
2026-03-17 21:29:18 +03:00
Egor 5b722c5210 Merge pull request #2746 from smediainfo/pr/kassa-ai-sbp-card
feat: add SBP and Card sub-options for KassaAI payment method
2026-03-17 20:29:03 +03:00
Egor a80a85c2a4 Merge pull request #2748 from smediainfo/fix/missing-greenlet-purchase
fix: MissingGreenlet crash after subscription purchase in cabinet
2026-03-17 20:27:40 +03:00
Egor f84885cc8a Merge pull request #2747 from smediainfo/pr/fix-external-squad-sync
fix: защита внешних сквадов от удаления при синхронизации серверов
2026-03-17 20:26:58 +03:00
Egor 12898b7eab Merge pull request #2751 from SayonaraQ/fix/extend-period-nameerror
Fix/extend period nameerror
2026-03-17 20:25:51 +03:00
Codex Bot 20a6fa1bcf fix(subscription): remove stale extend promo state fields causing NameError 2026-03-17 17:55:14 +03:00
c0mrade 94199413c2 fix: миграция Tribute webhook с deprecated user_id на trb_user_id
- Убран fallback на deprecated поле user_id (удаляется 14 апреля 2026)
- Добавлен парсинг trb_user_id во всех ветках обработки webhook
- trb_user_id прокинут в результат и логи всех хендлеров
2026-03-17 12:43:04 +03:00
Fringg 826accba51 fix: MissingGreenlet при изменении количества устройств на CLASSIC подписках
lock_user_for_pricing не загружал User.subscription eagerly,
что вызывало lazy load в async контексте при обращении к db_user.subscription
в execute_change_devices.
2026-03-16 11:25:33 +03:00
sMedia.tech 1cc687ac15 fix: MissingGreenlet crash after subscription purchase in cabinet
`_subscription_to_response()` is a sync function that accesses
lazy-loaded relationship attributes (e.g. `subscription.tariff`).
When `send_subscription_purchase_notification()` is called before
building the response, `_record_subscription_event()` internally
calls `create_subscription_event()` which does `db.commit()`.
This expires all ORM objects in the session.

When the sync `_subscription_to_response()` then tries to access
`subscription.tariff`, SQLAlchemy cannot perform the lazy load
outside of an async greenlet context, raising:

  MissingGreenlet: greenlet_spawn has not been called;
  can't call await_only() here.

The fix adds `await db.refresh(subscription)` (and `user` where
accessed) after the admin notification block and before
`_subscription_to_response()` in three purchase endpoints:
- `submit_purchase` (classic mode)
- `purchase_tariff` (tariffs mode)
- `switch_tariff`

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 09:16:53 +03:00
sMedia.tech e4bb0430fb refactor: deduplicate KassaAI handlers with config dict and shared helpers
Extract _KASSA_AI_METHOD_CONFIG dict, _check_topup_restriction() helper,
and generic _start_kassa_ai_sub_topup / _process_kassa_ai_sub_quick_amount
implementations. Public handlers become thin wrappers.

608 → 429 lines (-30%), eliminates 5 copies of restriction check block
and 3 pairs of nearly-identical start/quick-amount handlers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 08:53:34 +03:00
root 603b9a1f46 fix: sub-method enabled check, guest payment provider, silent FSM return 2026-03-16 04:40:36 +00:00
root 557af5994d style: ruff format kassa_ai files 2026-03-16 04:31:04 +00:00
root 808818ca2b style: ruff format server_squad.py 2026-03-16 04:30:32 +00:00
root b563796091 fix: protect external squads from deletion during server sync 2026-03-16 04:27:59 +00:00
sMedia.tech 6a3e9d92b5 style: ruff format kassa_ai_service.py 2026-03-16 04:12:41 +00:00
root cda2392411 refactor: move KASSA_AI_SUB_METHODS to service layer, add early enabled checks
- Move KASSA_AI_SUB_METHODS from handler to kassa_ai_service.py (fixes service→handler import violation)
- Remove KASSA_AI_PAYMENT_METHODS set (was defined but unused)
- Import KASSA_AI_SUB_METHODS in payment_service.py from service layer
- Add is_kassa_ai_sbp/card_enabled() checks at start of entry handler functions
2026-03-16 04:12:41 +00:00
root 04419fdff7 feat: add SBP and Card sub-options to kassa_ai payment method
- kassa_ai shows single admin entry with СБП/Карта sub-option checkboxes
- SBP routes to payment_system_id=44, Card to payment_system_id=36
- Bot: added kassa_ai_sbp/card handlers and FSM flow (mirrors freekassa pattern)
- Cabinet: KASSA_AI_OPTION_MAP reads payment_option to select correct ps_id
- Config: KASSA_AI_SBP_ENABLED / KASSA_AI_CARD_ENABLED env vars + helpers
- Guest payments: kassa_ai_sbp/card supported in landing page checkout
- payment_method_config_service: kassa_ai has available_sub_options=[sbp,card]
2026-03-16 04:12:41 +00:00
Egor 713146dd6b Merge pull request #2745 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.4
2026-03-16 04:14:18 +03:00
github-actions[bot] 7d41ab44be chore(main): release 3.32.4 2026-03-16 01:13:22 +00:00
Egor 98f6f93487 Merge pull request #2744 from BEDOLAGA-DEV/dev
Dev
2026-03-16 04:12:59 +03:00
Egor 3752b7b067 Merge pull request #2743 from BEDOLAGA-DEV/main
w
2026-03-16 04:10:54 +03:00
Fringg 2f33e55144 fix: режим «Контакт и тикеты» возвращает support_type='both' вместо 'tickets' 2026-03-16 04:09:21 +03:00
Fringg c0b282a189 fix: уведомление об истечении подписки теперь учитывает autopay_enabled пользователя
- Статус автоплатежа в уведомлении основан на subscription.autopay_enabled, а не на глобальном ENABLE_AUTOPAY
- Продление с баланса (_process_autopayments) работает всегда при autopay_enabled=True
- Рекуррентные карточные платежи по-прежнему за гейтом ENABLE_AUTOPAY + YOOKASSA_RECURRENT_ENABLED
2026-03-16 04:04:01 +03:00
Fringg e1bcb1ba91 fix: реферальный бонус инвайтера — сумма вместо максимума, защита флага первого пополнения
- referral_service: inviter_bonus = fixed + commission вместо max(fixed, commission)
- 13 платёжных провайдеров: has_made_first_topup ставится только для нереферальных юзеров
- riopay: критический фикс — флаг ставился до вызова referral_service
- Обновлены уведомления с разбивкой бонуса
- Исправлен и дополнен тест referral_service
2026-03-16 03:57:50 +03:00
Fringg 3d68db0a51 fix: не пересылать externalSquadUuid в рутинных обновлениях RemnaWave
Стейловый externalSquadUuid (c6c0a338-062d-4d3a-826d-7015a24d681c) из тарифа
не существует в таблице ExternalSquads панели → FK violation → A039.
Теперь externalSquadUuid отправляется только при sync_squads=True (создание подписки).
2026-03-16 03:47:13 +03:00
Fringg 8d7f0eea0f fix: лог полного payload при ошибке PATCH /api/users для диагностики A039 2026-03-16 03:44:45 +03:00
Fringg 4aaf0ddd25 fix: не пересылать activeInternalSquads в рутинных обновлениях RemnaWave (A039)
Стейловые UUID сквадов в connected_squads вызывали FK violation в RemnaWave → A039.
- update_remnawave_user: добавлен параметр sync_squads (default=False)
- Сквады шлются только при явном sync_squads=True (promo_offer, countries)
- monitoring_service: убрана пересылка сквадов в рутинном sync
- Расширен лог PATCH payload для диагностики
2026-03-16 03:41:56 +03:00
Fringg db2f0c93f2 fix: расширен лог PATCH /api/users payload для диагностики A039 2026-03-16 03:35:06 +03:00
Fringg 3f8e8993b2 fix: сохранение user_id до rollback чтобы избежать MissingGreenlet при lazy load 2026-03-16 03:28:12 +03:00
Fringg e453521098 fix: устранена отправка externalSquadUuid=null в RemnaWave API (A039) и исправлен reduce_devices
- reduce_devices: убрано молчаливое проглатывание ошибки RemnaWave, теперь при неудаче делается rollback и возвращается HTTP 502
- Убрана отправка external_squad_uuid=None в 8 местах: subscription_service, monitoring_service, remnawave_service, admin/users, cabinet/admin_users
2026-03-16 03:25:24 +03:00
Fringg 8d3cd50098 refactor: централизация всех расчётов цен в PricingEngine
- Мигрирован confirm_purchase() на calculate_classic_new_subscription_price()
- Мигрирован compute_simple_subscription_price на делегацию в PricingEngine
- Мигрирован handle_custom_confirm на calculate_tariff_purchase_price()
- Мигрированы daily confirm handlers (confirm_daily_tariff_purchase,
  confirm_daily_tariff_switch, confirm_instant_switch daily path)
- Мигрирован gift.py на calculate_tariff_purchase_price()
- Мигрированы FSM cache prices (select_period, select_devices, toggle_country)
- Добавлен lock_user_for_pricing в admin_buy_tariff_execute (TOCTOU fix)
- Добавлен lock + recompute в _auto_add_devices и _auto_add_traffic
- Исправлено двойное применение promo-offer в simple_subscription (критический баг)
- Унифицирован daily price display (group+offer) на всех 6 поверхностях
- PricingEngine.get_addon_discount_percent: добавлен promo_group= kwarg
- PricingEngine._calculate_switch_to/from_daily: добавлен promo-offer discount
- Удалён мёртвый код из common.py (_get_addon_discount_percent_for_user)
- Miniapp period_discounts: исправлен доступ через get_discount_percent()
2026-03-16 03:10:22 +03:00
Fringg f80912e444 fix: убрана отправка externalSquadUuid=null в RemnaWave API и исправлен ложный лог синхронизации рулетки
- Не отправляем externalSquadUuid: null — RemnaWave отвечал 500 (A039)
- Проверяем результат update_remnawave_user вместо ложного " синхронизировано"
2026-03-15 17:34:31 +03:00
Egor 484d2f7e34 Merge pull request #2740 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.3
2026-03-15 01:24:46 +03:00
github-actions[bot] 842fb697e6 chore(main): release 3.32.3 2026-03-14 22:24:27 +00:00
Egor 3ac3a92e26 Merge pull request #2739 from BEDOLAGA-DEV/dev
Dev
2026-03-15 01:24:05 +03:00
Fringg 7648707ca2 fix: campaign registration, revenue calculation, backup restore, autopay errors, referral links
- fix campaign registration not recorded when CHANNEL_IS_REQUIRED_SUB + SKIP_RULES_ACCEPT enabled (missing _apply_campaign_bonus_if_needed in required_sub_channel_check fast path)
- fix revenue calculation counting bonus-funded subscription payments as income (now deposits only via REAL_PAYMENT_METHODS)
- fix backup restore PendingRollbackError cascade on unique constraint violations (savepoint wrapping in _restore_table_records and _restore_users_without_referrals)
- fix AttributeError on message.text.strip() when users send media in referral code handlers
- suppress 'message is not modified' TelegramBadRequest in autopay toggle
- add bot_referral_link to referral API response with URL encoding
2026-03-15 01:13:50 +03:00
Egor 7e466ef464 Merge pull request #2736 from Legacyyy777/main
fix: implement case-insensitive email checks in authentication and user retrieval
2026-03-14 22:30:56 +03:00
Egor 28321df4d2 Merge pull request #2738 from SayonaraQ/pr/topup-cart-fix
fix(payment): prioritize saved cart after topup over expired auto-extend
2026-03-14 22:27:56 +03:00
Fringg 6adf70b2da fix: refresh CLASSIC_PERIOD_PRICES when admin changes PRICE_*_DAYS or SALES_MODE
CLASSIC_PERIOD_PRICES was built once at import time and never updated,
causing classic mode to always show hardcoded defaults instead of
admin-configured prices.
2026-03-14 22:24:08 +03:00
SayonaraQ 2d204275da Fix race payment cart 2026-03-14 20:11:47 +03:00
Legacyyy777 ebee8348ca fix: implement case-insensitive email checks in authentication and user retrieval
Updated email queries in authentication routes and user CRUD operations to be case-insensitive. This change ensures that email comparisons ignore case, improving user experience and preventing potential registration/login issues with differently cased emails.
2026-03-14 04:39:11 +05:00
96 changed files with 4017 additions and 2696 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "3.32.2"
".": "3.33.0"
}
+72
View File
@@ -1,5 +1,77 @@
# Changelog
## [3.33.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.32.4...v3.33.0) (2026-03-17)
### New Features
* add SBP and Card sub-options for KassaAI payment method ([5b722c5](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5b722c521036befcbbaf6192215f651c2ec9c4fb))
* add SBP and Card sub-options to kassa_ai payment method ([04419fd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/04419fdff7dc244eb2c9553ea1501e2de454010b))
* deep link авторизация в кабинете при блокировке oauth.telegram.org ([322d457](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/322d45765220c854e36ae0b4b862a96d36ae3be8))
* добавлена поддержка RioPay в кабинете ([3d1fbc7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3d1fbc70f8add81d4a3561d63dcd46f385bcc6f1))
* добавлена поддержка RioPay для лендингов и подарков ([04f4e6b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/04f4e6bf6e9031ef8512a07ab36355111c524319))
### Bug Fixes
* add back button to payment amount validation errors ([20eff61](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/20eff6170fb752051022a14fa9d927d59ff1d602))
* add sync_squads=True to admin tariff change handler ([3f0b24c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3f0b24c1ec82ebfb6fdbc801ed6b493ea09c9a2f))
* deep link auth security and reliability fixes ([099391e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/099391eb5f24319703f12ae2cb72d93b26164d99))
* enforce promo group authorization on country/server selection ([641da94](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/641da949a907ade7b870e1a5385fdb71f9e524af))
* merge phantom users into active accounts on /start ([77f1a76](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/77f1a764d59d68236899ec59c884907d3666d3dd))
* MissingGreenlet crash after subscription purchase in cabinet ([a80a85c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a80a85c2a489f397efb4ffb5bd77655420a49adb))
* MissingGreenlet crash after subscription purchase in cabinet ([1cc687a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1cc687ac15ecdf12928e5ce448514c09b6628f65))
* MissingGreenlet при изменении количества устройств на CLASSIC подписках ([826accb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/826accba519f23a687fcc3d387f727fd31d2a88c))
* protect external squads from deletion during server sync ([b563796](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b563796091e83edcc8dfbd6222648b5346f39a9c))
* review findings — db.commit, isinstance guard, constants, ACTIVE check ([72b5305](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/72b5305b870ae9ecdb2672549b9c153dd8b3f7bc))
* sub-method enabled check, guest payment provider, silent FSM return ([603b9a1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/603b9a1f4610a5b288d6fba78c98474c439529aa))
* **subscription:** remove stale extend promo state fields causing NameError ([20a6fa1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/20a6fa1bcf362455623f43838f4ffaaf98b33e76))
* swap Caddy auth headers — api_key to Authorization, caddy_token to X-Api-Key ([038c34e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/038c34e52a863d0c5c6993ea785587ba7e0bc61d))
* sync squads to Remnawave panel on tariff purchase/switch ([c34fdd1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c34fdd10a0a22a85a4e29cbf44da2ac5d4a643b3))
* защита внешних сквадов от удаления при синхронизации серверов ([f84885c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f84885cc8aa0c9a70f916076e987284f1f9c3479))
* исправлен расчёт конверсии в статистике продаж ([3089c17](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3089c1704b54323b4c2a151d40a5b395a427c658))
* исправлены проблемы RioPay интеграции после ревью ([4abb8cb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4abb8cb1a3f21089697199261bcc37e6f6a5c623))
* миграция Tribute webhook с deprecated user_id на trb_user_id ([9419941](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/94199413c283167edd829b337cf9bec0a5414a54))
* скрыть плашку верификации email при выключенной верификации ([4966e39](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4966e39eb9b92967ef92c92ae434ca6cdea80c84))
### Refactoring
* deduplicate KassaAI handlers with config dict and shared helpers ([e4bb043](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e4bb0430fb9cc4f55013767ceda6d1c214bd80a6))
* move KASSA_AI_SUB_METHODS to service layer, add early enabled checks ([cda2392](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cda239241122ae1dd02a252b3eadc47453c0c48b))
## [3.32.4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.32.3...v3.32.4) (2026-03-16)
### Bug Fixes
* лог полного payload при ошибке PATCH /api/users для диагностики A039 ([8d7f0ee](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8d7f0eea0fecd9e66bf199bd2c288e073f1354c0))
* не пересылать activeInternalSquads в рутинных обновлениях RemnaWave (A039) ([4aaf0dd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4aaf0ddd25527ec23fa6a479ac3826d6b6266761))
* не пересылать externalSquadUuid в рутинных обновлениях RemnaWave ([3d68db0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3d68db0a51fac55640d44be784c832875ca2da17))
* расширен лог PATCH /api/users payload для диагностики A039 ([db2f0c9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/db2f0c93f2974410e744411fb9111c6de1f0f0be))
* режим «Контакт и тикеты» возвращает support_type='both' вместо 'tickets' ([2f33e55](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2f33e5514469f2686c4b35e2105f4188a41d4145))
* реферальный бонус инвайтера — сумма вместо максимума, защита флага первого пополнения ([e1bcb1b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e1bcb1ba910ef3a79dec5fa974ae8e6c09494aa7))
* сохранение user_id до rollback чтобы избежать MissingGreenlet при lazy load ([3f8e899](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3f8e8993b2949b5a5e04b1d8a468ef7dc1170e08))
* убрана отправка externalSquadUuid=null в RemnaWave API и исправлен ложный лог синхронизации рулетки ([f80912e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f80912e444ab5706c809e689ca5ed2a38da118d0))
* уведомление об истечении подписки теперь учитывает autopay_enabled пользователя ([c0b282a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c0b282a189a2b761c68fc70886edd91d9c807ff6))
* устранена отправка externalSquadUuid=null в RemnaWave API (A039) и исправлен reduce_devices ([e453521](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e4535210982351413cb82483000fe441e7b7300a))
### Refactoring
* централизация всех расчётов цен в PricingEngine ([8d3cd50](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8d3cd500980f4f640cb1ba493150f1f20e8bd58c))
## [3.32.3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.32.2...v3.32.3) (2026-03-14)
### Bug Fixes
* campaign registration, revenue calculation, backup restore, autopay errors, referral links ([7648707](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7648707ca26d6cd2703b50b0fe8c4697e6155784))
* implement case-insensitive email checks in authentication and user retrieval ([7e466ef](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7e466ef464ce918d885bd6297d1e605a633fd43e))
* implement case-insensitive email checks in authentication and user retrieval ([ebee834](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ebee8348ca338b9be5f044537e5e2b4740dc6441))
* **payment:** prioritize saved cart after topup over expired auto-extend ([28321df](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/28321df4d274269536efebcf3da870f2e7d07d90))
* refresh CLASSIC_PERIOD_PRICES when admin changes PRICE_*_DAYS or SALES_MODE ([6adf70b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/6adf70b2da6e2250cc8e909dbb497b355302e72f))
## [3.32.2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.32.1...v3.32.2) (2026-03-13)
+1 -1
View File
@@ -19,7 +19,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
FROM python:3.13-slim
ARG VERSION="v3.32.2" # x-release-please-version
ARG VERSION="v3.33.0" # x-release-please-version
ARG BUILD_DATE
ARG VCS_REF
+44 -6
View File
@@ -170,6 +170,7 @@ async def get_sales_summary(
new_trials = row.new_trials or 0
# Trial-to-paid conversion in period
# Method 1: SubscriptionConversion records (only created by some purchase flows)
conversions_result = await db.execute(
select(func.count(SubscriptionConversion.id)).where(
and_(
@@ -178,9 +179,29 @@ async def get_sales_summary(
)
)
)
conversions = conversions_result.scalar() or 0
# Cap at 100%: conversions from previous periods can exceed current new_trials
conversion_rate = min(round((conversions / new_trials * 100), 1), 100.0) if new_trials > 0 else 0.0
conversion_records = conversions_result.scalar() or 0
# Method 2: Users registered in period who have paid (catches all purchase flows)
converted_users_result = await db.execute(
select(func.count(User.id)).where(
and_(
User.created_at >= period_start,
User.created_at <= period_end,
User.has_had_paid_subscription.is_(True),
)
)
)
converted_users = converted_users_result.scalar() or 0
# Use the higher count to catch conversions from all purchase flows
conversions = max(conversion_records, converted_users)
# new_trials only counts REMAINING trials (is_trial=True), but converted users
# had is_trial flipped to False. Add conversions back to get total trial starters.
total_trial_starters = new_trials + conversions
conversion_rate = (
min(round((conversions / total_trial_starters * 100), 1), 100.0) if total_trial_starters > 0 else 0.0
)
# Renewals count
renewals_subquery = (
@@ -290,6 +311,7 @@ async def get_trials_stats(
)
total_trials = total_result.scalar() or 0
# Conversion: SubscriptionConversion records + fallback to has_had_paid_subscription
conversions_result = await db.execute(
select(func.count(SubscriptionConversion.id)).where(
and_(
@@ -298,9 +320,25 @@ async def get_trials_stats(
)
)
)
conversions = conversions_result.scalar() or 0
# Cap at 100%: conversions from previous periods can exceed current period trials
conversion_rate = min(round((conversions / total_trials * 100), 1), 100.0) if total_trials > 0 else 0.0
conversion_records = conversions_result.scalar() or 0
converted_users_result = await db.execute(
select(func.count(User.id)).where(
and_(
User.created_at >= period_start,
User.created_at <= period_end,
User.has_had_paid_subscription.is_(True),
)
)
)
converted_users = converted_users_result.scalar() or 0
conversions = max(conversion_records, converted_users)
# total_trials only counts remaining is_trial=True; add conversions for total starters
total_trial_starters = total_trials + conversions
conversion_rate = (
min(round((conversions / total_trial_starters * 100), 1), 100.0) if total_trial_starters > 0 else 0.0
)
avg_duration_result = await db.execute(
select(func.avg(SubscriptionConversion.trial_duration_days)).where(
+4 -6
View File
@@ -318,11 +318,10 @@ async def _sync_subscription_to_panel(
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
# Внешний сквад: синхронизируем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
try:
updated_panel_user = await api.update_user(**update_kwargs)
@@ -2777,11 +2776,10 @@ async def sync_user_to_panel(
update_kwargs['hwid_device_limit'] = hwid_limit
changes['device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
# Внешний сквад: синхронизируем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
try:
await api.update_user(**update_kwargs)
+145 -14
View File
@@ -6,7 +6,7 @@ from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy import select
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
@@ -28,10 +28,16 @@ from app.database.crud.user import (
set_email_change_pending,
verify_and_apply_email_change,
)
from app.database.models import CabinetRefreshToken, User
from app.database.models import CabinetRefreshToken, User, UserStatus
from app.services.campaign_service import AdvertisingCampaignService
from app.services.disposable_email_service import disposable_email_service
from app.services.referral_service import process_referral_registration
from app.services.web_auth_service import (
WEB_AUTH_TOKEN_TTL,
consume_web_auth_token,
create_web_auth_token,
poll_web_auth_token,
)
from app.utils.cache import RateLimitCache, TokenReplayCache
from app.utils.timezone import panel_datetime_to_utc
@@ -61,6 +67,8 @@ from ..schemas.auth import (
AuthResponse,
AutoLoginRequest,
CampaignBonusInfo,
DeepLinkPollRequest,
DeepLinkTokenResponse,
EmailChangeRequest,
EmailChangeResponse,
EmailChangeVerifyRequest,
@@ -461,7 +469,7 @@ async def auth_telegram(
if updated:
logger.info('User profile updated from initData', user_id=user.id)
if user.status != 'active':
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='User account is not active',
@@ -544,7 +552,7 @@ async def auth_telegram_widget(
)
logger.info('User created successfully: id=, telegram_id', user_id=user.id, telegram_id=user.telegram_id)
if user.status != 'active':
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='User account is not active',
@@ -673,7 +681,7 @@ async def auth_telegram_oidc(
)
logger.info('User created successfully', user_id=user.id, telegram_id=user.telegram_id)
if user.status != 'active':
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='User account is not active',
@@ -721,8 +729,9 @@ async def register_email(
detail='Disposable email addresses are not allowed',
)
# Check if email already exists
existing_user = await db.execute(select(User).where(User.email == request.email))
# Check if email already exists (case-insensitive)
email_lower = (request.email or '').strip().lower()
existing_user = await db.execute(select(User).where(func.lower(User.email) == email_lower))
if existing_user.scalar_one_or_none():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -837,8 +846,9 @@ async def register_email_standalone(
detail='Disposable email addresses are not allowed',
)
# Проверить что email не занят
existing = await db.execute(select(User).where(User.email == request.email))
# Проверить что email не занят (без учёта регистра)
email_lower = (request.email or '').strip().lower()
existing = await db.execute(select(User).where(func.lower(User.email) == email_lower))
if existing.scalar_one_or_none():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -1096,8 +1106,9 @@ async def login_email(
# Check if this is a test email login
is_test_email = settings.is_test_email(request.email)
# Find user by email
result = await db.execute(select(User).where(User.email == request.email))
# Find user by email (case-insensitive)
email_lower = (request.email or '').strip().lower()
result = await db.execute(select(User).where(func.lower(User.email) == email_lower))
user = result.scalar_one_or_none()
if not user:
@@ -1140,7 +1151,7 @@ async def login_email(
detail='Please verify your email first',
)
if user.status != 'active':
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='User account is not active',
@@ -1289,7 +1300,7 @@ async def auto_login(
detail='User not found',
)
if user.status != 'active':
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Account is deactivated',
@@ -1317,7 +1328,8 @@ async def forgot_password(
detail='Too many requests',
headers={'Retry-After': '60'},
)
result = await db.execute(select(User).where(User.email == request.email))
email_lower = (request.email or '').strip().lower()
result = await db.execute(select(User).where(func.lower(User.email) == email_lower))
user = result.scalar_one_or_none()
# Always return success to prevent email enumeration
@@ -1670,3 +1682,122 @@ async def get_email_change_status(
'new_email': user.email_change_new,
'expires_at': user.email_change_expires.isoformat() if user.email_change_expires else None,
}
# --- Deep link auth (fallback when oauth.telegram.org is blocked) ---
@router.post('/deeplink/request', response_model=DeepLinkTokenResponse)
async def request_deep_link_token(
raw_request: Request,
):
"""Generate a one-time deep link auth token.
Frontend shows t.me/{bot}?start=webauth_{token} to the user.
No auth required (user is not logged in yet).
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'deeplink_request', limit=10, window=60, fail_closed=True):
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail='Too many requests',
headers={'Retry-After': '60'},
)
try:
token = await create_web_auth_token()
except RuntimeError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail='Service temporarily unavailable',
)
bot_username = settings.get_bot_username()
if not bot_username:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail='Bot not configured',
)
return DeepLinkTokenResponse(
token=token,
bot_username=bot_username,
expires_in=WEB_AUTH_TOKEN_TTL,
)
@router.post('/deeplink/poll', response_model=AuthResponse)
async def poll_deep_link_token(
request: DeepLinkPollRequest,
raw_request: Request,
db: AsyncSession = Depends(get_cabinet_db),
):
"""Poll for deep link auth completion.
Returns 202 if still pending, AuthResponse if completed, 410 if expired.
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'deeplink_poll', limit=60, window=60, fail_closed=True):
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail='Too many requests',
headers={'Retry-After': '60'},
)
data = await poll_web_auth_token(request.token)
if data is None:
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail='Token expired or not found',
)
if data.get('status') == 'pending':
raise HTTPException(
status_code=status.HTTP_202_ACCEPTED,
detail='Waiting for confirmation',
)
if data.get('status') != 'linked':
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail='Invalid token state',
)
# Token is linked - consume it atomically
consumed = await consume_web_auth_token(request.token)
if not consumed:
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail='Token already consumed',
)
user_id = consumed.get('user_id')
if not user_id:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Invalid token data',
)
user = await get_user_by_id(db, int(user_id))
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='User not found',
)
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Account is deactivated',
)
user.cabinet_last_login = datetime.now(UTC)
await db.commit()
response = await _create_auth_response(user, db)
await _store_refresh_token(db, user.id, response.refresh_token, device_info='deep_link')
logger.info('Deep link auth successful', user_id=user.id, telegram_id=user.telegram_id)
return response
+54 -1
View File
@@ -701,6 +701,11 @@ async def create_topup(
detail='KassaAI payment method is unavailable',
)
# Use payment_option to select sbp or card
KASSA_AI_OPTION_MAP = {'sbp': 44, 'card': 36}
option = (request.payment_option or '').strip().lower()
ps_id = KASSA_AI_OPTION_MAP.get(option) # None = use env default
payment_service = PaymentService()
result = await payment_service.create_kassa_ai_payment(
db=db,
@@ -709,6 +714,7 @@ async def create_topup(
description=settings.get_balance_payment_description(request.amount_kopeks),
email=getattr(user, 'email', None),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
payment_system_id=ps_id,
)
if result and result.get('payment_url'):
@@ -720,6 +726,33 @@ async def create_topup(
detail='Failed to create KassaAI payment',
)
elif request.payment_method == 'riopay':
if not settings.is_riopay_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='RioPay payment method is unavailable',
)
payment_service = PaymentService()
result = await payment_service.create_riopay_payment(
db=db,
user_id=user.id,
amount_kopeks=request.amount_kopeks,
description=settings.get_balance_payment_description(request.amount_kopeks),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
success_url=cabinet_success_url,
fail_url=cabinet_failed_url,
)
if result and result.get('payment_url'):
payment_url = result.get('payment_url')
payment_id = str(result.get('local_payment_id') or result.get('riopay_order_id') or 'pending')
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create RioPay payment',
)
elif request.payment_method == 'tribute':
if not settings.TRIBUTE_ENABLED or not settings.TRIBUTE_DONATE_LINK:
raise HTTPException(
@@ -871,6 +904,17 @@ def _get_status_info(record: PendingPayment) -> tuple[str, str]:
}
return mapping.get(status, ('', 'Неизвестно'))
if record.method == PaymentMethod.RIOPAY:
mapping = {
'pending': ('', 'Ожидает оплаты'),
'success': ('', 'Оплачено'),
'failed': ('', 'Ошибка'),
'canceled': ('', 'Отменено'),
'expired': ('', 'Истёк'),
'amount_mismatch': ('⚠️', 'Несовпадение суммы'),
}
return mapping.get(status, ('', 'Неизвестно'))
return '', 'Неизвестно'
@@ -901,6 +945,8 @@ def _is_checkable(record: PendingPayment) -> bool:
return status in {'pending', 'created', 'processing'}
if record.method == PaymentMethod.KASSA_AI:
return status in {'pending', 'created', 'processing'}
if record.method == PaymentMethod.RIOPAY:
return status in {'pending'}
return False
@@ -924,7 +970,12 @@ def _get_payment_url(record: PendingPayment) -> str | None:
)
elif record.method == PaymentMethod.PLATEGA:
payment_url = getattr(payment, 'redirect_url', None) or payment_url
elif record.method in (PaymentMethod.CLOUDPAYMENTS, PaymentMethod.FREEKASSA, PaymentMethod.KASSA_AI):
elif record.method in (
PaymentMethod.CLOUDPAYMENTS,
PaymentMethod.FREEKASSA,
PaymentMethod.KASSA_AI,
PaymentMethod.RIOPAY,
):
payment_url = getattr(payment, 'payment_url', None) or payment_url
return payment_url
@@ -1013,6 +1064,7 @@ async def get_latest_payment_by_method(
MulenPayPayment,
Pal24Payment,
PlategaPayment,
RioPayPayment,
WataPayment,
YooKassaPayment,
)
@@ -1028,6 +1080,7 @@ async def get_latest_payment_by_method(
PaymentMethod.CLOUDPAYMENTS: CloudPaymentsPayment,
PaymentMethod.FREEKASSA: FreekassaPayment,
PaymentMethod.KASSA_AI: KassaAiPayment,
PaymentMethod.RIOPAY: RioPayPayment,
}
model = model_map.get(payment_method)
+13 -3
View File
@@ -244,6 +244,7 @@ class EmailAuthEnabledResponse(BaseModel):
"""Email auth enabled setting."""
enabled: bool = True
verification_enabled: bool = True
class EmailAuthEnabledUpdate(BaseModel):
@@ -838,10 +839,16 @@ async def get_email_auth_enabled(
if email_auth_value is not None:
enabled = email_auth_value.lower() == 'true'
return EmailAuthEnabledResponse(enabled=enabled)
return EmailAuthEnabledResponse(
enabled=enabled,
verification_enabled=settings.is_cabinet_email_verification_enabled(),
)
# Default: check config setting
return EmailAuthEnabledResponse(enabled=settings.is_cabinet_email_auth_enabled())
return EmailAuthEnabledResponse(
enabled=settings.is_cabinet_email_auth_enabled(),
verification_enabled=settings.is_cabinet_email_verification_enabled(),
)
@router.patch('/email-auth', response_model=EmailAuthEnabledResponse)
@@ -855,7 +862,10 @@ async def update_email_auth_enabled(
logger.info('Admin set email auth enabled', telegram_id=admin.telegram_id, enabled=payload.enabled)
return EmailAuthEnabledResponse(enabled=payload.enabled)
return EmailAuthEnabledResponse(
enabled=payload.enabled,
verification_enabled=settings.is_cabinet_email_verification_enabled(),
)
# ============ Telegram Widget Config Routes ============
+22 -36
View File
@@ -22,7 +22,6 @@ from app.database.models import (
Tariff,
TransactionType,
User,
UserPromoGroup,
)
from app.services.guest_purchase_service import (
GuestPurchaseError,
@@ -112,15 +111,17 @@ async def get_gift_config(
price = base_price
# Apply promo group discount
from app.services.pricing_engine import PricingEngine
promo_group_discount = 0
if promo_group:
promo_group_discount = promo_group.get_discount_percent('period', days)
if promo_group_discount > 0:
price = int(price * (100 - promo_group_discount) / 100)
price = PricingEngine.apply_discount(price, promo_group_discount)
# Apply active promo offer discount (stacks on top)
if promo_offer_discount_percent > 0:
price = price - price * promo_offer_discount_percent // 100
price = PricingEngine.apply_discount(price, promo_offer_discount_percent)
# Ensure minimum price of 1 kopek after all discounts
price = max(1, price)
@@ -249,43 +250,28 @@ async def create_gift_purchase(
detail='Tariff not found or inactive',
)
price_kopeks = tariff.get_price_for_period(body.period_days)
if price_kopeks is None:
# Validate that period has a configured price before locking
if tariff.get_price_for_period(body.period_days) is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Price is not configured for this period',
)
# Lock user row to prevent concurrent promo offer double-spend
locked_result = await db.execute(
select(User)
.options(
selectinload(User.user_promo_groups).selectinload(UserPromoGroup.promo_group),
selectinload(User.promo_group),
)
.where(User.id == user.id)
.with_for_update()
.execution_options(populate_existing=True)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
from app.services.pricing_engine import pricing_engine
pricing_result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
body.period_days,
device_limit=tariff.device_limit,
user=user,
)
user = locked_result.scalar_one()
# Apply promo group discount
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
if promo_group is None:
promo_group = getattr(user, 'promo_group', None)
if promo_group:
discount_percent = promo_group.get_discount_percent('period', body.period_days)
if discount_percent > 0:
price_kopeks = int(price_kopeks * (100 - discount_percent) / 100)
# Apply active promo offer discount (stacks)
promo_offer_discount_percent = get_user_active_promo_discount_percent(user)
if promo_offer_discount_percent > 0:
price_kopeks = price_kopeks - price_kopeks * promo_offer_discount_percent // 100
# Ensure minimum price of 1 kopek after all discounts
price_kopeks = max(1, price_kopeks)
price_kopeks = max(1, pricing_result.final_total)
consume_promo = pricing_result.promo_offer_discount > 0
# Determine buyer contact info
if user.email:
@@ -420,7 +406,7 @@ async def create_gift_purchase(
)
# Consume promo offer discount before committing gateway purchase
if promo_offer_discount_percent > 0 and getattr(user, 'promo_offer_discount_percent', 0):
if consume_promo and getattr(user, 'promo_offer_discount_percent', 0):
user.promo_offer_discount_percent = 0
user.promo_offer_discount_source = None
user.promo_offer_discount_expires_at = None
@@ -485,7 +471,7 @@ async def create_gift_purchase(
price_kopeks,
description=f'Gift: {tariff.name} ({body.period_days}d)',
create_transaction=False,
consume_promo_offer=promo_offer_discount_percent > 0,
consume_promo_offer=consume_promo,
)
if not balance_ok:
await db.rollback()
+2 -2
View File
@@ -91,7 +91,7 @@ class SupportConfigResponse(BaseModel):
"""Support/tickets configuration for miniapp."""
tickets_enabled: bool
support_type: str # "tickets", "profile", "url"
support_type: str # "tickets", "profile", "url", "both"
support_url: str | None = None
support_username: str | None = None
@@ -299,7 +299,7 @@ async def get_support_config():
support_type = 'profile'
else: # both
tickets_enabled = True
support_type = 'tickets'
support_type = 'both'
return SupportConfigResponse(
tickets_enabled=tickets_enabled,
+3 -1
View File
@@ -342,7 +342,9 @@ async def _load_landing_tariffs(
effective_discount = tariff_override if tariff_override is not None else discount.percent
original_price_kopeks = price
original_price_label = settings.format_price(price)
price = max(1, price - (price * effective_discount // 100))
from app.services.pricing_engine import PricingEngine
price = max(1, PricingEngine.apply_discount(price, effective_discount))
periods.append(
LandingTariffPeriod(
+9 -1
View File
@@ -91,12 +91,20 @@ async def get_referral_info(
referral_entitlement = max(0, total_earnings - withdrawn - pending)
available_balance = min(user.balance_kopeks, referral_entitlement)
# Build referral link
# Build referral links
referral_link = settings.get_referral_link(user.referral_code) if user.referral_code else ''
bot_username = settings.get_bot_username()
bot_referral_link = ''
if user.referral_code and bot_username:
from urllib.parse import quote
safe_code = quote(user.referral_code, safe='')
bot_referral_link = f'https://t.me/{bot_username}?start={safe_code}'
return ReferralInfoResponse(
referral_code=user.referral_code or '',
referral_link=referral_link,
bot_referral_link=bot_referral_link,
total_referrals=total_referrals,
active_referrals=active_referrals,
total_earnings_kopeks=total_earnings,
+221 -337
View File
@@ -42,7 +42,6 @@ from app.services.system_settings_service import bot_configuration_service
from app.services.user_cart_service import user_cart_service
from app.utils.cache import RateLimitCache, cache, cache_key
from app.utils.pricing_utils import format_period_description
from app.utils.promo_offer import get_user_active_promo_discount_percent
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.subscription import (
@@ -68,29 +67,14 @@ router = APIRouter(prefix='/subscription', tags=['Cabinet Subscription'])
def _get_addon_discount_percent(
user: User,
user: User | None,
category: str,
period_days: int | None = None,
period_days_hint: int | None = None,
) -> int:
"""Get addon discount percent for user from promo group.
"""Get addon discount percent for user — delegates to PricingEngine."""
from app.services.pricing_engine import PricingEngine
Mirrors logic from app/handlers/subscription/common.py:_get_addon_discount_percent_for_user
"""
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
if promo_group is None:
return 0
if not getattr(promo_group, 'apply_discounts_to_addons', True):
return 0
try:
return user.get_promo_discount(category, period_days)
except AttributeError:
return 0
return PricingEngine.get_addon_discount_percent(user, category, period_days_hint)
def _apply_addon_discount(
@@ -117,27 +101,12 @@ def _apply_addon_discount(
}
def _get_period_discount_percent(user: User, period_days: int | None = None) -> int:
"""Get period discount percent for tariff switch calculations."""
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
if promo_group is None:
return 0
try:
return user.get_promo_discount('period', period_days)
except AttributeError:
return 0
def _subscription_to_response(
subscription: Subscription,
servers: list[ServerInfo] | None = None,
tariff_name: str | None = None,
traffic_purchases: list[dict[str, Any]] | None = None,
user: User | None = None,
) -> SubscriptionData:
"""Convert Subscription model to response."""
now = datetime.now(UTC)
@@ -200,6 +169,18 @@ def _subscription_to_response(
traffic_reset_mode = None
if tariff_id and hasattr(subscription, 'tariff') and subscription.tariff:
daily_price_kopeks = getattr(subscription.tariff, 'daily_price_kopeks', None)
# Применяем скидку промогруппы + promo-offer для отображения
if daily_price_kopeks and daily_price_kopeks > 0 and user:
from app.services.pricing_engine import PricingEngine
from app.utils.promo_offer import get_user_active_promo_discount_percent
_promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
_group_pct = _promo_group.get_discount_percent('period', 1) if _promo_group else 0
_offer_pct = get_user_active_promo_discount_percent(user)
if _group_pct > 0 or _offer_pct > 0:
daily_price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
daily_price_kopeks, _group_pct, _offer_pct
)
if not tariff_name: # Only set if not passed as parameter
tariff_name = getattr(subscription.tariff, 'name', None)
traffic_reset_mode = (
@@ -321,7 +302,9 @@ async def get_subscription(
}
)
subscription_data = _subscription_to_response(fresh_user.subscription, servers, tariff_name, traffic_purchases_data)
subscription_data = _subscription_to_response(
fresh_user.subscription, servers, tariff_name, traffic_purchases_data, user=fresh_user
)
return SubscriptionStatusResponse(has_subscription=True, subscription=subscription_data)
@@ -401,6 +384,11 @@ async def renew_subscription(
detail='Selected renewal period is not available',
)
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Unified pricing via PricingEngine
pricing = await pricing_engine.calculate_renewal_price(
db,
@@ -724,6 +712,11 @@ async def purchase_traffic(
subscription.end_date,
)
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply discount from promo group using proper method
period_hint_days = days_charged if days_charged > 0 else 30
discount_result = _apply_addon_discount(user, 'traffic', prorated_price, period_hint_days)
@@ -923,6 +916,11 @@ async def purchase_devices_legacy(
base_total_price = device_price * request.devices
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply discount from promo group
discount_result = _apply_addon_discount(user, 'devices', base_total_price, 30)
total_price = discount_result['discounted']
@@ -1363,7 +1361,7 @@ async def activate_trial(
except Exception as e:
logger.error('Failed to send trial activation notification', error=e)
return _subscription_to_response(subscription)
return _subscription_to_response(subscription, user=user)
# ============ Full Purchase Flow (like MiniApp) ============
@@ -1427,17 +1425,29 @@ async def _build_tariff_response(
# Стоимость доп. устройств за этот период
extra_devices_cost = extra_devices_count * extra_device_price_per_month * months
# Apply promo group discount for this period (на базовую цену тарифа)
# Apply per-category promo group discounts
original_price = base_tariff_price + extra_devices_cost
discount_percent = 0
discount_amount = 0
final_price = original_price
if promo_group:
discount_percent = promo_group.get_discount_percent('period', period_days)
if discount_percent > 0:
discount_amount = original_price * discount_percent // 100
final_price = original_price - discount_amount
period_pct = promo_group.get_discount_percent('period', period_days)
devices_pct = promo_group.get_discount_percent('devices', period_days)
discounted_base = (
pricing_engine.apply_discount(base_tariff_price, period_pct)
if period_pct > 0
else base_tariff_price
)
discounted_devices = (
pricing_engine.apply_discount(extra_devices_cost, devices_pct)
if devices_pct > 0
else extra_devices_cost
)
final_price = discounted_base + discounted_devices
discount_amount = original_price - final_price
discount_percent = max(period_pct, devices_pct)
else:
discount_percent = 0
final_price = original_price
per_month = final_price // months if months > 0 else final_price
original_per_month = original_price // months if months > 0 else original_price
@@ -1474,16 +1484,21 @@ async def _build_tariff_response(
traffic_label = '♾️ Безлимит' if tariff.traffic_limit_gb == 0 else f'{tariff.traffic_limit_gb} ГБ'
# Apply discount to daily price if applicable
# Apply discount to daily price if applicable (group + promo-offer)
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
original_daily_price = daily_price
daily_discount_percent = 0
if promo_group and daily_price > 0:
# For daily tariffs, use period discount with period_days=1
daily_discount_percent = promo_group.get_discount_percent('period', 1)
if daily_discount_percent > 0:
discount_amount = daily_price * daily_discount_percent // 100
daily_price = daily_price - discount_amount
if daily_price > 0:
from app.services.pricing_engine import PricingEngine
from app.utils.promo_offer import get_user_active_promo_discount_percent
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if daily_group_pct > 0 or daily_offer_pct > 0:
daily_price, _, _ = PricingEngine.apply_stacked_discounts(daily_price, daily_group_pct, daily_offer_pct)
# Комбинированный процент для отображения
remaining = (100 - daily_group_pct) * (100 - daily_offer_pct)
daily_discount_percent = 100 - remaining // 100
# Apply discount to custom price_per_day if applicable
price_per_day = tariff.price_per_day_kopeks
@@ -1492,18 +1507,16 @@ async def _build_tariff_response(
if promo_group and price_per_day > 0:
custom_days_discount_percent = promo_group.get_discount_percent('period', 30) # Use 30-day rate as base
if custom_days_discount_percent > 0:
discount_amount = price_per_day * custom_days_discount_percent // 100
price_per_day = price_per_day - discount_amount
price_per_day = pricing_engine.apply_discount(price_per_day, custom_days_discount_percent)
# Apply discount to device price if applicable
device_price = tariff.device_price_kopeks if tariff.device_price_kopeks is not None else 0
original_device_price = device_price
device_discount_percent = 0
if promo_group and device_price > 0:
device_discount_percent = promo_group.get_discount_percent('devices')
device_discount_percent = promo_group.get_discount_percent('devices', 30)
if device_discount_percent > 0:
discount_amount = device_price * device_discount_percent // 100
device_price = device_price - discount_amount
device_price = pricing_engine.apply_discount(device_price, device_discount_percent)
# Показываем реальное количество устройств (с докупленными) для текущего тарифа
actual_device_limit = tariff.device_limit
@@ -1703,6 +1716,9 @@ async def submit_purchase(
)
try:
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
context = await purchase_service.build_options(db, user)
# Convert request to dict for parsing
@@ -1771,10 +1787,13 @@ async def submit_purchase(
except Exception as e:
logger.error('Failed to send admin notification for subscription purchase', error=e)
# Refresh expired objects after db.commit() in _record_subscription_event
await db.refresh(subscription)
return {
'success': True,
'message': result['message'],
'subscription': _subscription_to_response(subscription),
'subscription': _subscription_to_response(subscription, user=user),
'was_trial_conversion': result.get('was_trial_conversion', False),
}
@@ -1854,6 +1873,11 @@ async def purchase_tariff(
detail='Tariff not found or inactive',
)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Check tariff availability for user's promo group and get promo group for discounts
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
promo_group_id = promo_group.id if promo_group else None
@@ -1865,105 +1889,43 @@ async def purchase_tariff(
# Handle daily tariffs specially
is_daily_tariff = getattr(tariff, 'is_daily', False)
discount_percent = 0
original_price = 0
if is_daily_tariff:
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
if daily_price <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Daily tariff has invalid price',
)
original_price = daily_price
# Apply promo group discount for daily tariff
if promo_group:
discount_percent = promo_group.get_discount_percent('period', 1)
if discount_percent > 0:
discount_amount = daily_price * discount_percent // 100
daily_price = daily_price - discount_amount
# For daily tariffs, charge first day and set period to 1 day
price_kopeks = daily_price
period_days = 1
else:
period_days = request.period_days
# Get price for period (support custom days)
price_kopeks = tariff.get_price_for_period(period_days)
if price_kopeks is None:
# Check for custom days
if tariff.can_purchase_custom_days():
price_kopeks = tariff.get_price_for_custom_days(period_days)
if price_kopeks is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Period must be between {tariff.min_days} and {tariff.max_days} days',
)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid period for this tariff',
)
original_price = price_kopeks
# Apply promo group discount for period
if promo_group and price_kopeks > 0:
discount_percent = promo_group.get_discount_percent('period', period_days)
if discount_percent > 0:
discount_amount = price_kopeks * discount_percent // 100
price_kopeks = price_kopeks - discount_amount
# Calculate traffic limit and price
# Determine traffic limit (custom traffic support)
traffic_limit_gb = tariff.traffic_limit_gb
traffic_price_kopeks = 0
custom_traffic_gb = None
if request.traffic_gb is not None and tariff.can_purchase_custom_traffic():
# Custom traffic requested
traffic_price_kopeks = tariff.get_price_for_custom_traffic(request.traffic_gb)
if traffic_price_kopeks is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Traffic must be between {tariff.min_traffic_gb} and {tariff.max_traffic_gb} GB',
)
# Apply traffic discount if promo group has it
if promo_group and traffic_price_kopeks > 0:
traffic_discount_percent = promo_group.get_discount_percent('traffic', period_days)
if traffic_discount_percent > 0:
traffic_discount = traffic_price_kopeks * traffic_discount_percent // 100
traffic_price_kopeks = traffic_price_kopeks - traffic_discount
custom_traffic_gb = request.traffic_gb
traffic_limit_gb = request.traffic_gb
price_kopeks += traffic_price_kopeks
# Проверяем, есть ли докупленные устройства при продлении того же тарифа
# Determine device_limit for renewal pricing
existing_subscription = await get_subscription_by_user_id(db, user.id)
extra_devices = 0
device_limit = None
effective_device_limit = tariff.device_limit
if existing_subscription and existing_subscription.tariff_id == tariff.id:
extra_devices = max(0, (existing_subscription.device_limit or 0) - (tariff.device_limit or 0))
if extra_devices > 0:
device_limit = existing_subscription.device_limit
if (existing_subscription.device_limit or 0) > (tariff.device_limit or 0):
effective_device_limit = existing_subscription.device_limit
if not is_daily_tariff:
from app.utils.pricing_utils import calculate_months_from_days
device_price_per_month = (
tariff.device_price_kopeks
if tariff.device_price_kopeks is not None
else settings.PRICE_PER_DEVICE
)
months = calculate_months_from_days(period_days)
extra_devices_cost = extra_devices * device_price_per_month * months
# Применяем скидку промогруппы на устройства
if promo_group and extra_devices_cost > 0:
devices_discount_pct = promo_group.get_discount_percent('devices', period_days)
if devices_discount_pct > 0:
extra_devices_cost = extra_devices_cost - (extra_devices_cost * devices_discount_pct // 100)
price_kopeks += extra_devices_cost
# Apply promo offer discount (temporary discount from promo offers)
price_before_promo_offer = price_kopeks
promo_offer_discount_percent = get_user_active_promo_discount_percent(user)
promo_offer_discount_value = 0
if promo_offer_discount_percent > 0:
promo_offer_discount_value = price_kopeks * promo_offer_discount_percent // 100
price_kopeks = price_kopeks - promo_offer_discount_value
# Calculate price via PricingEngine (single source of truth)
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period_days,
device_limit=device_limit,
custom_traffic_gb=custom_traffic_gb,
user=user,
)
price_kopeks = result.final_total
original_price = result.original_total
bd = result.breakdown
group_pcts = bd.get('group_discount_pct', {})
discount_percent = group_pcts.get('period', 0)
promo_offer_discount_percent = bd.get('offer_discount_pct', 0)
promo_offer_discount_value = result.promo_offer_discount
price_before_promo_offer = price_kopeks + promo_offer_discount_value
# Check balance
if user.balance_kopeks < price_kopeks:
@@ -2109,6 +2071,7 @@ async def purchase_tariff(
subscription,
reset_traffic=True,
reset_reason='покупка тарифа (cabinet)',
sync_squads=True,
)
else:
await service.create_remnawave_user(
@@ -2137,11 +2100,12 @@ async def purchase_tariff(
logger.error('Error saving tariff cart (cabinet)', error=e)
await db.refresh(user)
await db.refresh(subscription)
response = {
'success': True,
'message': f"Тариф '{tariff.name}' успешно активирован",
'subscription': _subscription_to_response(subscription),
'subscription': _subscription_to_response(subscription, user=user),
'tariff_id': tariff.id,
'tariff_name': tariff.name,
'charged_amount': price_kopeks,
@@ -2319,6 +2283,11 @@ async def purchase_devices(
base_price_prorated = int(base_price_per_month * days_left / total_days)
base_price_prorated = max(100, base_price_prorated) # Minimum 1 ruble
# Lock user BEFORE discount computation to prevent TOCTOU on promo group
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply discount from promo group
period_hint_days = days_left
discount_result = _apply_addon_discount(user, 'devices', base_price_prorated, period_hint_days)
@@ -2977,8 +2946,7 @@ async def get_available_countries(
await db.refresh(user, ['subscription'])
promo_group_id = user.promo_group_id
# Exclude trial-only servers from available servers for purchase
available_servers = await get_available_server_squads(db, promo_group_id=promo_group_id, exclude_trial_only=True)
available_servers = await get_available_server_squads(db, promo_group_id=promo_group_id)
connected_squads = []
days_left = 0
@@ -2989,11 +2957,10 @@ async def get_available_countries(
delta = user.subscription.end_date - datetime.now(UTC)
days_left = max(0, delta.days)
# Get discount from promo group
servers_discount_percent = 0
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
if promo_group:
servers_discount_percent = promo_group.get_discount_percent('servers', None)
# Get discount from promo group via PricingEngine (respects apply_discounts_to_addons flag)
from app.services.pricing_engine import PricingEngine
servers_discount_percent = PricingEngine.get_addon_discount_percent(user, 'servers', None)
countries = []
for server in available_servers:
@@ -3076,13 +3043,12 @@ async def update_countries(
current_countries = user.subscription.connected_squads or []
promo_group_id = user.promo_group_id
# Exclude trial-only servers from available servers for purchase
available_servers = await get_available_server_squads(db, promo_group_id=promo_group_id, exclude_trial_only=True)
available_servers = await get_available_server_squads(db, promo_group_id=promo_group_id)
allowed_country_ids = {server.squad_uuid for server in available_servers}
# Validate selected countries
for country_uuid in selected_countries:
if country_uuid not in allowed_country_ids and country_uuid not in current_countries:
if country_uuid not in allowed_country_ids:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Country {country_uuid} is not available',
@@ -3097,15 +3063,19 @@ async def update_countries(
'connected_squads': current_countries,
}
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Calculate cost for added servers
total_cost = 0
added_names = []
removed_names = []
servers_discount_percent = 0
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
if promo_group:
servers_discount_percent = promo_group.get_discount_percent('servers', None)
from app.services.pricing_engine import PricingEngine
servers_discount_percent = PricingEngine.get_addon_discount_percent(user, 'servers', None)
added_server_prices = []
@@ -3175,7 +3145,7 @@ async def update_countries(
try:
subscription_service = SubscriptionService()
if getattr(user, 'remnawave_uuid', None):
await subscription_service.update_remnawave_user(db, user.subscription)
await subscription_service.update_remnawave_user(db, user.subscription, sync_squads=True)
else:
await subscription_service.create_remnawave_user(db, user.subscription)
except Exception as e:
@@ -3796,21 +3766,32 @@ async def reduce_devices(
logger.error('Error checking/removing devices', error=e)
old_device_limit = current_device_limit
user_id = user.id # save before potential rollback (expires ORM objects)
# Update subscription
# Update subscription in memory (will be committed by update_remnawave_user on success)
subscription.device_limit = new_device_limit
subscription.updated_at = datetime.now(UTC)
await db.commit()
# Update RemnaWave
try:
subscription_service = SubscriptionService()
await subscription_service.update_remnawave_user(db, subscription)
except Exception as e:
logger.error('Error updating RemnaWave user', error=e)
# Update RemnaWave — commits on success, returns None on failure
subscription_service = SubscriptionService()
result = await subscription_service.update_remnawave_user(db, subscription)
if result is None:
# RemnaWave update failed — rollback local changes
await db.rollback()
logger.error(
'Failed to update RemnaWave after device limit reduction',
user_id=user_id,
old_device_limit=old_device_limit,
new_device_limit=new_device_limit,
)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail='Не удалось обновить VPN-панель. Попробуйте позже.',
)
logger.info(
f'User {user.id} reduced device limit from {old_device_limit} to {new_device_limit}'
f'User {user_id} reduced device limit from {old_device_limit} to {new_device_limit}'
+ (f' (removed {devices_removed_count} devices)' if devices_removed_count > 0 else '')
)
@@ -3903,82 +3884,18 @@ async def preview_tariff_switch(
delta = user.subscription.end_date - datetime.now(UTC)
remaining_days = max(0, delta.days)
# Calculate switch cost
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
new_is_daily = getattr(new_tariff, 'is_daily', False)
switching_to_daily = not current_is_daily and new_is_daily
switching_from_daily = current_is_daily and not new_is_daily
def get_monthly_price(tariff) -> int:
"""Get 30-day price from tariff, or calculate from closest period."""
if not tariff or not tariff.period_prices:
return 0
# Try to get 30-day price directly
if '30' in tariff.period_prices:
return tariff.period_prices['30']
# Find closest period and calculate monthly equivalent
min_period = None
min_price = 0
for period_str, price in tariff.period_prices.items():
period_days = int(period_str)
if min_period is None or period_days < min_period:
min_period = period_days
min_price = price
if min_period and min_period > 0:
return int(min_price * 30 / min_period)
return 0
# Get period discount percent for cost calculation
period_discount_percent = _get_period_discount_percent(user, remaining_days if remaining_days > 0 else 30)
base_upgrade_cost = 0
discount_value = 0
if switching_to_daily:
# Switching TO daily - pay first day price
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
base_upgrade_cost = daily_price
# Apply discount to daily price
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
is_upgrade = upgrade_cost > 0
elif switching_from_daily:
# Switching FROM daily TO periodic - full payment for new tariff
min_period_price = 0
if new_tariff.period_prices:
min_period_price = min(new_tariff.period_prices.values())
base_upgrade_cost = min_period_price
# Apply discount
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
is_upgrade = upgrade_cost > 0
else:
# Calculate proportional cost difference using monthly prices
current_monthly = get_monthly_price(current_tariff)
new_monthly = get_monthly_price(new_tariff)
price_diff = new_monthly - current_monthly
if price_diff > 0:
# Upgrade - pay proportional difference
base_upgrade_cost = int(price_diff * remaining_days / 30)
# Apply discount to upgrade cost
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
is_upgrade = True
else:
# Downgrade or same - free
upgrade_cost = 0
base_upgrade_cost = 0
is_upgrade = False
# Calculate switch cost (PricingEngine handles all cases: periodic↔periodic, daily→periodic, periodic→daily)
switch_result = pricing_engine.calculate_tariff_switch_cost(
current_tariff,
new_tariff,
remaining_days,
user=user,
)
upgrade_cost = switch_result.upgrade_cost
is_upgrade = switch_result.is_upgrade
base_upgrade_cost = switch_result.raw_cost
discount_value = switch_result.discount_value
period_discount_percent = switch_result.effective_discount_pct
balance = user.balance_kopeks or 0
has_enough = balance >= upgrade_cost
@@ -4090,88 +4007,41 @@ async def switch_tariff(
detail='Tariff not available',
)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Calculate remaining days
remaining_days = 0
if user.subscription.end_date and user.subscription.end_date > datetime.now(UTC):
delta = user.subscription.end_date - datetime.now(UTC)
if subscription.end_date and subscription.end_date > datetime.now(UTC):
delta = subscription.end_date - datetime.now(UTC)
remaining_days = max(0, delta.days)
# Calculate cost
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
# Calculate cost (PricingEngine handles all cases: periodic↔periodic, daily→periodic, periodic→daily)
switch_result = pricing_engine.calculate_tariff_switch_cost(
current_tariff,
new_tariff,
remaining_days,
user=user,
)
upgrade_cost = switch_result.upgrade_cost
base_upgrade_cost = switch_result.raw_cost
discount_value = switch_result.discount_value
period_discount_percent = switch_result.effective_discount_pct
new_period_days = switch_result.new_period_days
# Validate daily price for switching TO daily
new_is_daily = getattr(new_tariff, 'is_daily', False)
switching_from_daily = current_is_daily and not new_is_daily
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
switching_to_daily = not current_is_daily and new_is_daily
switching_from_daily = current_is_daily and not new_is_daily
# Get period discount percent for cost calculation
period_discount_percent = _get_period_discount_percent(user, remaining_days if remaining_days > 0 else 30)
base_upgrade_cost = 0
discount_value = 0
if switching_to_daily:
# Switching TO daily tariff - charge first day price
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
if daily_price <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Daily tariff has invalid price',
)
base_upgrade_cost = daily_price
# Apply discount
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
new_period_days = 1 # Daily tariff starts with 1 day
elif switching_from_daily:
# Switch FROM daily to regular tariff - pay for minimum period
min_period_days = 30
min_period_price = 0
if new_tariff.period_prices:
min_period_days = min(int(k) for k in new_tariff.period_prices.keys())
min_period_price = new_tariff.period_prices.get(str(min_period_days), 0)
base_upgrade_cost = min_period_price
# Apply discount
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
new_period_days = min_period_days
else:
# Regular tariff switch - calculate proportional cost difference using monthly prices
def get_monthly_price(tariff) -> int:
if not tariff or not tariff.period_prices:
return 0
if '30' in tariff.period_prices:
return tariff.period_prices['30']
min_period = None
min_price = 0
for period_str, price in tariff.period_prices.items():
period_days = int(period_str)
if min_period is None or period_days < min_period:
min_period = period_days
min_price = price
if min_period and min_period > 0:
return int(min_price * 30 / min_period)
return 0
current_monthly = get_monthly_price(current_tariff)
new_monthly = get_monthly_price(new_tariff)
price_diff = new_monthly - current_monthly
if price_diff > 0:
base_upgrade_cost = int(price_diff * remaining_days / 30)
# Apply discount
if period_discount_percent > 0 and base_upgrade_cost > 0:
discount_value = int(base_upgrade_cost * period_discount_percent / 100)
upgrade_cost = base_upgrade_cost - discount_value
else:
upgrade_cost = base_upgrade_cost
else:
upgrade_cost = 0
base_upgrade_cost = 0
new_period_days = 0
if switching_to_daily and (getattr(new_tariff, 'daily_price_kopeks', 0) or 0) <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Daily tariff has invalid price',
)
# Charge if upgrade
if upgrade_cost > 0:
@@ -4202,6 +4072,7 @@ async def switch_tariff(
user,
upgrade_cost,
description,
consume_promo_offer=switch_result.offer_discount_pct > 0,
mark_as_paid_subscription=True,
commit=False,
)
@@ -4304,6 +4175,7 @@ async def switch_tariff(
subscription,
reset_traffic=should_reset_traffic,
reset_reason='смена тарифа',
sync_squads=True,
)
else:
await subscription_service.create_remnawave_user(
@@ -4355,11 +4227,15 @@ async def switch_tariff(
except Exception as e:
logger.error('Failed to send admin notification for tariff switch', error=e)
# Refresh expired objects after db.commit() in _record_subscription_event
await db.refresh(subscription)
await db.refresh(user)
response = {
'success': True,
'message': f"Switched from '{old_tariff_name}' to '{new_tariff.name}'"
+ (' (devices reset)' if devices_reset else ''),
'subscription': _subscription_to_response(subscription),
'subscription': _subscription_to_response(subscription, user=user),
'old_tariff_name': old_tariff_name,
'new_tariff_id': new_tariff.id,
'new_tariff_name': new_tariff.name,
@@ -4426,7 +4302,21 @@ async def toggle_subscription_pause(
new_paused_state = not is_currently_paused
user.subscription.is_daily_paused = new_paused_state
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
# Lock user BEFORE discount computation to prevent TOCTOU on promo group
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply group discount to daily price (consistent with DailySubscriptionService and miniapp resume)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
# If resuming, check balance and charge
if not new_paused_state:
@@ -4568,22 +4458,16 @@ async def switch_traffic_package(
# Upgrade - charge difference
price_diff = new_price - current_price
# Apply promo discount
traffic_discount_percent = 0
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
if promo_group:
apply_to_addons = getattr(promo_group, 'apply_discounts_to_addons', True)
if apply_to_addons:
traffic_discount_percent = max(
0, min(100, int(getattr(promo_group, 'traffic_discount_percent', 0) or 0))
)
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
if traffic_discount_percent > 0:
price_diff = int(price_diff * (100 - traffic_discount_percent) / 100)
user = await lock_user_for_pricing(db, user.id)
# Apply promo discount via PricingEngine
price_diff, _discount_val, traffic_discount_percent = pricing_engine.calculate_traffic_discount(
price_diff,
user,
)
# Prorated calculation
final_price, days_charged = calculate_prorated_price(price_diff, user.subscription.end_date)
+14
View File
@@ -187,3 +187,17 @@ class EmailChangeResponse(BaseModel):
message: str = Field(..., description='Success message')
new_email: str = Field(..., description='New email address pending verification')
expires_in_minutes: int = Field(..., description='Code expiration time in minutes')
class DeepLinkTokenResponse(BaseModel):
"""Response with deep link auth token."""
token: str = Field(..., description='One-time auth token')
bot_username: str = Field(..., description='Bot username for deep link')
expires_in: int = Field(..., description='Token TTL in seconds')
class DeepLinkPollRequest(BaseModel):
"""Request to poll deep link auth status."""
token: str = Field(..., min_length=16, max_length=128, description='Deep link auth token')
+1
View File
@@ -10,6 +10,7 @@ class ReferralInfoResponse(BaseModel):
referral_code: str
referral_link: str
bot_referral_link: str = ''
total_referrals: int
active_referrals: int
total_earnings_kopeks: int
+25
View File
@@ -535,6 +535,11 @@ class Settings(BaseSettings):
KASSA_AI_WEBHOOK_PORT: int = 8089
# Способ оплаты: 44 = СБП (QR код), 36 = Карты РФ, 43 = SberPay
KASSA_AI_PAYMENT_SYSTEM_ID: int = 44
# Раздельные методы оплаты KassaAI (отображаются как отдельные кнопки)
KASSA_AI_SBP_ENABLED: bool = False # СБП — payment_system_id=44
KASSA_AI_SBP_DISPLAY_NAME: str = 'СБП (KassaAI)'
KASSA_AI_CARD_ENABLED: bool = False # Карты РФ — payment_system_id=36
KASSA_AI_CARD_DISPLAY_NAME: str = 'Карта (KassaAI)'
# RioPay (api.riopay.online) v2.0.1
RIOPAY_ENABLED: bool = False
@@ -1850,6 +1855,26 @@ class Settings(BaseSettings):
def get_riopay_display_name_html(self) -> str:
return html.escape(self.get_riopay_display_name())
def is_kassa_ai_sbp_enabled(self) -> bool:
return self.KASSA_AI_SBP_ENABLED and self.is_kassa_ai_enabled()
def get_kassa_ai_sbp_display_name(self) -> str:
name = (self.KASSA_AI_SBP_DISPLAY_NAME or '').strip()
return name if name else 'СБП (KassaAI)'
def get_kassa_ai_sbp_display_name_html(self) -> str:
return html.escape(self.get_kassa_ai_sbp_display_name())
def is_kassa_ai_card_enabled(self) -> bool:
return self.KASSA_AI_CARD_ENABLED and self.is_kassa_ai_enabled()
def get_kassa_ai_card_display_name(self) -> str:
name = (self.KASSA_AI_CARD_DISPLAY_NAME or '').strip()
return name if name else 'Карта (KassaAI)'
def get_kassa_ai_card_display_name_html(self) -> str:
return html.escape(self.get_kassa_ai_card_display_name())
def is_payment_verification_auto_check_enabled(self) -> bool:
return self.PAYMENT_VERIFICATION_AUTO_CHECK_ENABLED
+2 -1
View File
@@ -366,7 +366,8 @@ async def get_campaign_statistics(
first_payment_amount_by_user[user_id] = amount_value
first_payment_time_by_user[user_id] = created_at
total_revenue = deposits_total + subscription_payments_total
# Revenue = only real deposits (exclude bonus-funded subscription spending)
total_revenue = deposits_total
paid_user_ids = set(paid_users_from_transactions)
paid_user_ids.update(conversion_user_ids)
+1 -1
View File
@@ -15,7 +15,7 @@ logger = structlog.get_logger(__name__)
async def create_riopay_payment(
db: AsyncSession,
*,
user_id: int,
user_id: int | None,
order_id: str,
amount_kopeks: int,
currency: str = 'RUB',
+17 -3
View File
@@ -141,8 +141,12 @@ async def get_available_server_squads(
.order_by(ServerSquad.sort_order, ServerSquad.display_name)
)
if exclude_trial_only:
query = query.where(ServerSquad.is_trial_eligible.is_(False))
# НЕ фильтруем по is_trial_eligible — это поле означает "доступен для триала",
# а НЕ "только для триала". Сквад может быть одновременно триальным и платным.
# Фильтр exclude_trial_only убирал единственный доступный сквад, из-за чего
# пользователи без триала получали пустой connected_squads при покупке.
# Параметр exclude_trial_only сохранён для обратной совместимости, но не используется.
# TODO: если нужна логика "только для триала", добавить отдельное поле is_trial_only
if promo_group_id is not None:
query = query.join(ServerSquad.allowed_promo_groups).where(PromoGroup.id == promo_group_id)
@@ -313,7 +317,17 @@ async def sync_with_remnawave(db: AsyncSession, remnawave_squads: list[dict]) ->
)
created += 1
removed_servers = [server for uuid, server in existing_servers.items() if uuid not in remnawave_uuids]
# Protect external squads referenced by tariffs from being removed during sync
tariff_ext_uuids_result = await db.execute(
select(Tariff.external_squad_uuid).where(Tariff.external_squad_uuid.isnot(None))
)
protected_uuids = {row[0] for row in tariff_ext_uuids_result.fetchall()}
removed_servers = [
server
for uuid, server in existing_servers.items()
if uuid not in remnawave_uuids and uuid not in protected_uuids
]
if removed_servers:
removed_ids = [server.id for server in removed_servers]
+55 -219
View File
@@ -1,6 +1,5 @@
from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
from typing import Optional
import structlog
from sqlalchemy import and_, delete, func, select
@@ -11,7 +10,6 @@ from sqlalchemy.orm.exc import StaleDataError
from app.config import settings
from app.database.crud.notification import clear_notifications
from app.database.models import (
PromoGroup,
Subscription,
SubscriptionServer,
SubscriptionStatus,
@@ -20,7 +18,6 @@ from app.database.models import (
User,
UserStatus,
)
from app.utils.pricing_utils import calculate_months_from_days
from app.utils.timezone import format_local_datetime
@@ -221,6 +218,23 @@ async def create_paid_subscription(
if device_limit is None:
device_limit = settings.DEFAULT_DEVICE_LIMIT
# Fallback: если connected_squads пустой — берём первый доступный сквад
final_squads = list(connected_squads or [])
if not final_squads:
try:
from app.database.crud.server_squad import get_available_server_squads
available = await get_available_server_squads(db)
if available:
final_squads = [available[0].squad_uuid]
logger.warning(
'⚠️ connected_squads пустой при создании подписки, используем fallback сквад',
user_id=user_id,
fallback_squad=final_squads[0],
)
except Exception as error:
logger.error('❌ Не удалось получить fallback сквад', user_id=user_id, error=error)
subscription = Subscription(
user_id=user_id,
status=SubscriptionStatus.ACTIVE.value,
@@ -229,7 +243,7 @@ async def create_paid_subscription(
end_date=end_date,
traffic_limit_gb=traffic_limit_gb,
device_limit=device_limit,
connected_squads=connected_squads or [],
connected_squads=final_squads,
autopay_enabled=settings.is_autopay_enabled_by_default(),
autopay_days_before=settings.DEFAULT_AUTOPAY_DAYS_BEFORE,
tariff_id=tariff_id,
@@ -249,7 +263,7 @@ async def create_paid_subscription(
status=subscription.status,
)
squad_uuids = list(connected_squads or [])
squad_uuids = list(final_squads)
if update_server_counters and squad_uuids:
try:
from app.database.crud.server_squad import (
@@ -299,7 +313,25 @@ async def replace_subscription(
current_time = datetime.now(UTC)
old_squads = set(subscription.connected_squads or [])
new_squads = set(connected_squads or [])
# Fallback: если connected_squads пустой — берём первый доступный сквад
final_connected = list(connected_squads or [])
if not final_connected:
try:
from app.database.crud.server_squad import get_available_server_squads
available = await get_available_server_squads(db)
if available:
final_connected = [available[0].squad_uuid]
logger.warning(
'⚠️ connected_squads пустой при замене подписки, используем fallback сквад',
subscription_id=subscription.id,
fallback_squad=final_connected[0],
)
except Exception as error:
logger.error('❌ Не удалось получить fallback сквад', subscription_id=subscription.id, error=error)
new_squads = set(final_connected)
new_autopay_enabled = subscription.autopay_enabled if autopay_enabled is None else autopay_enabled
new_autopay_days_before = subscription.autopay_days_before if autopay_days_before is None else autopay_days_before
@@ -549,9 +581,17 @@ async def extend_subscription(
logger.info('📱 Обновлен лимит устройств: →', old_devices=old_devices, device_limit=device_limit)
if connected_squads is not None:
old_squads = subscription.connected_squads
subscription.connected_squads = connected_squads
logger.info('🌍 Обновлены сквады: →', old_squads=old_squads, connected_squads=connected_squads)
# Не перезаписываем существующие сквады пустым списком
if connected_squads or not subscription.connected_squads:
old_squads = subscription.connected_squads
subscription.connected_squads = connected_squads
logger.info('🌍 Обновлены сквады: →', old_squads=old_squads, connected_squads=connected_squads)
else:
logger.warning(
'⚠️ Попытка перезаписать сквады пустым списком, сохраняем текущие',
subscription_id=subscription.id,
current_squads=subscription.connected_squads,
)
# Обработка daily полей при смене тарифа
if is_tariff_change and tariff_id is not None:
@@ -1198,212 +1238,6 @@ async def add_subscription_servers(
return subscription
async def get_server_monthly_price(db: AsyncSession, server_squad_id: int) -> int:
from app.database.models import ServerSquad
result = await db.execute(select(ServerSquad.price_kopeks).where(ServerSquad.id == server_squad_id))
return result.scalar() or 0
async def get_servers_monthly_prices(
db: AsyncSession,
server_squad_ids: list[int],
*,
user: Optional['User'] = None,
) -> list[int]:
"""Получает месячные цены серверов с проверкой доступности для промогруппы пользователя."""
from sqlalchemy.orm import selectinload
from app.database.models import ServerSquad
prices = []
# Загружаем промогруппы пользователя если нужно
user_promo_group = None
user_promo_group_id = None
if user:
try:
# Пробуем загрузить промогруппы если ещё не загружены
await db.refresh(user, ['user_promo_groups', 'promo_group'])
except Exception:
pass
try:
user_promo_group = user.get_primary_promo_group()
user_promo_group_id = user_promo_group.id if user_promo_group else None
except Exception as e:
logger.warning('Не удалось получить промогруппу пользователя', error=e)
for server_id in server_squad_ids:
# Загружаем сервер с промогруппами
result = await db.execute(
select(ServerSquad)
.options(selectinload(ServerSquad.allowed_promo_groups))
.where(ServerSquad.id == server_id)
)
server = result.scalar_one_or_none()
if not server:
prices.append(0)
continue
# Проверяем доступность сервера для промогруппы пользователя
is_allowed = True
if user_promo_group_id is not None and server.allowed_promo_groups:
allowed_ids = {pg.id for pg in server.allowed_promo_groups}
is_allowed = user_promo_group_id in allowed_ids
if server.is_available and is_allowed:
prices.append(server.price_kopeks)
else:
# Сервер недоступен для промогруппы пользователя
logger.warning(
'⚠️ Сервер (id=) недоступен для промогруппы пользователя (promo_group_id=), allowed_promo_groups',
display_name=server.display_name,
server_id=server_id,
user_promo_group_id=user_promo_group_id,
value=[pg.id for pg in server.allowed_promo_groups] if server.allowed_promo_groups else [],
)
prices.append(server.price_kopeks) # Всё равно берём реальную цену
return prices
def _get_discount_percent(
user: User | None,
promo_group: PromoGroup | None,
category: str,
*,
period_days: int | None = None,
) -> int:
if user is not None:
try:
return user.get_promo_discount(category, period_days)
except AttributeError:
pass
if promo_group is not None:
return promo_group.get_discount_percent(category, period_days)
return 0
async def calculate_subscription_total_cost(
db: AsyncSession,
period_days: int,
traffic_gb: int,
server_squad_ids: list[int],
devices: int,
*,
user: User | None = None,
promo_group: PromoGroup | None = None,
) -> tuple[int, dict]:
from app.config import PERIOD_PRICES
months_in_period = calculate_months_from_days(period_days)
base_price_original = PERIOD_PRICES.get(period_days, 0)
period_discount_percent = _get_discount_percent(
user,
promo_group,
'period',
period_days=period_days,
)
base_discount_total = base_price_original * period_discount_percent // 100
base_price = base_price_original - base_discount_total
promo_group = promo_group or (user.promo_group if user else None)
traffic_price_per_month = settings.get_traffic_price(traffic_gb)
traffic_discount_percent = _get_discount_percent(
user,
promo_group,
'traffic',
period_days=period_days,
)
traffic_discount_per_month = traffic_price_per_month * traffic_discount_percent // 100
discounted_traffic_per_month = traffic_price_per_month - traffic_discount_per_month
total_traffic_price = discounted_traffic_per_month * months_in_period
total_traffic_discount = traffic_discount_per_month * months_in_period
servers_prices = await get_servers_monthly_prices(db, server_squad_ids, user=user)
servers_price_per_month = sum(servers_prices)
servers_discount_percent = _get_discount_percent(
user,
promo_group,
'servers',
period_days=period_days,
)
servers_discount_per_month = servers_price_per_month * servers_discount_percent // 100
discounted_servers_per_month = servers_price_per_month - servers_discount_per_month
total_servers_price = discounted_servers_per_month * months_in_period
total_servers_discount = servers_discount_per_month * months_in_period
additional_devices = max(0, devices - settings.DEFAULT_DEVICE_LIMIT)
devices_price_per_month = additional_devices * settings.PRICE_PER_DEVICE
devices_discount_percent = _get_discount_percent(
user,
promo_group,
'devices',
period_days=period_days,
)
devices_discount_per_month = devices_price_per_month * devices_discount_percent // 100
discounted_devices_per_month = devices_price_per_month - devices_discount_per_month
total_devices_price = discounted_devices_per_month * months_in_period
total_devices_discount = devices_discount_per_month * months_in_period
total_cost = base_price + total_traffic_price + total_servers_price + total_devices_price
details = {
'base_price': base_price,
'base_price_original': base_price_original,
'base_discount_percent': period_discount_percent,
'base_discount_total': base_discount_total,
'traffic_price_per_month': traffic_price_per_month,
'traffic_discount_percent': traffic_discount_percent,
'traffic_discount_total': total_traffic_discount,
'total_traffic_price': total_traffic_price,
'servers_price_per_month': servers_price_per_month,
'servers_discount_percent': servers_discount_percent,
'servers_discount_total': total_servers_discount,
'total_servers_price': total_servers_price,
'devices_price_per_month': devices_price_per_month,
'devices_discount_percent': devices_discount_percent,
'devices_discount_total': total_devices_discount,
'total_devices_price': total_devices_price,
'months_in_period': months_in_period,
'servers_individual_prices': [
(price - (price * servers_discount_percent // 100)) * months_in_period for price in servers_prices
],
}
logger.debug(
'📊 Расчет стоимости подписки на дней ( мес)', period_days=period_days, months_in_period=months_in_period
)
logger.debug('Базовый период: ₽', base_price=base_price / 100)
if total_traffic_price > 0:
message = f' Трафик: {traffic_price_per_month / 100}₽/мес × {months_in_period} = {total_traffic_price / 100}'
if total_traffic_discount > 0:
message += f' (скидка {traffic_discount_percent}%: -{total_traffic_discount / 100}₽)'
logger.debug(message)
if total_servers_price > 0:
message = (
f' Серверы: {servers_price_per_month / 100}₽/мес × {months_in_period} = {total_servers_price / 100}'
)
if total_servers_discount > 0:
message += f' (скидка {servers_discount_percent}%: -{total_servers_discount / 100}₽)'
logger.debug(message)
if total_devices_price > 0:
message = (
f' Устройства: {devices_price_per_month / 100}₽/мес × {months_in_period} = {total_devices_price / 100}'
)
if total_devices_discount > 0:
message += f' (скидка {devices_discount_percent}%: -{total_devices_discount / 100}₽)'
logger.debug(message)
logger.debug('ИТОГО: ₽', total_cost=total_cost / 100)
return total_cost, details
async def get_subscription_server_ids(db: AsyncSession, subscription_id: int) -> list[int]:
result = await db.execute(
select(SubscriptionServer.server_squad_id).where(SubscriptionServer.subscription_id == subscription_id)
@@ -1901,8 +1735,9 @@ async def get_disabled_daily_subscriptions_for_resume(
# Не возобновляем подписки, приостановленные пользователем вручную
# is_(False) не ловит NULL, поэтому добавляем OR is_(None)
(Subscription.is_daily_paused.is_(False) | Subscription.is_daily_paused.is_(None)),
# Баланс пользователя >= суточной цены тарифа
User.balance_kopeks >= Tariff.daily_price_kopeks,
# Баланс пользователя > 0 (permissive pre-filter;
# actual discounted price check happens in _process_single_charge)
User.balance_kopeks > 0,
)
)
)
@@ -1947,8 +1782,9 @@ async def get_expired_daily_subscriptions_for_recovery(db: AsyncSession) -> list
Subscription.is_trial.is_(False),
# Только недавно экспайренные
Subscription.updated_at >= recovery_threshold,
# Баланс достаточен для списания
User.balance_kopeks >= Tariff.daily_price_kopeks,
# Баланс > 0 (permissive pre-filter;
# actual discounted price check happens in _process_single_charge)
User.balance_kopeks > 0,
)
)
)
+4 -3
View File
@@ -61,16 +61,17 @@ async def get_conversion_statistics(db: AsyncSession) -> dict:
total_conversions = total_conversions_result.scalar() or 0
# Подсчитываем пользователей с платными подписками
users_with_paid_result = await db.execute(select(func.count(User.id)).where(User.has_had_paid_subscription == True))
users_with_paid_result = await db.execute(
select(func.count(User.id)).where(User.has_had_paid_subscription.is_(True))
)
users_with_paid = users_with_paid_result.scalar() or 0
# Подсчитываем всех пользователей с подписками (использовавших триал)
# Считаем что все новые пользователи начинают с триала
total_users_with_subscriptions_result = await db.execute(select(func.count(func.distinct(Subscription.user_id))))
total_users_with_subscriptions = total_users_with_subscriptions_result.scalar() or 0
# Расчёт конверсии: (оплатившие) / (всего с подписками) * 100
# Это показывает какой % пользователей, получивших подписку, в итоге оплатили
# Знаменатель = все юзеры с подписками (включая уже конвертированных)
if total_users_with_subscriptions > 0:
conversion_rate = round((users_with_paid / total_users_with_subscriptions) * 100, 1)
else:
+30 -3
View File
@@ -528,6 +528,27 @@ async def add_user_balance_by_id(
return False
async def lock_user_for_pricing(db: AsyncSession, user_id: int) -> User:
"""Lock user row with FOR UPDATE and return refreshed instance.
Call BEFORE computing prices that depend on promo offer state
to prevent TOCTOU race conditions where two concurrent requests
both read the same promo offer discount and charge a discounted price.
"""
result = await db.execute(
select(User)
.where(User.id == user_id)
.options(
selectinload(User.user_promo_groups).selectinload(UserPromoGroup.promo_group),
selectinload(User.promo_group),
selectinload(User.subscription).selectinload(Subscription.tariff),
)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one()
async def subtract_user_balance(
db: AsyncSession,
user: User,
@@ -1191,8 +1212,11 @@ async def create_user_by_email(
async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
"""Get user by email address."""
result = await db.execute(select(User).where(User.email == email))
"""Get user by email address (case-insensitive)."""
if not email or not email.strip():
return None
email_lower = email.strip().lower()
result = await db.execute(select(User).where(func.lower(User.email) == email_lower))
return result.scalar_one_or_none()
@@ -1208,7 +1232,10 @@ async def is_email_taken(db: AsyncSession, email: str, exclude_user_id: int | No
Returns:
True if email is taken, False otherwise
"""
query = select(User.id).where(User.email == email)
if not email or not email.strip():
return False
email_lower = email.strip().lower()
query = select(User.id).where(func.lower(User.email) == email_lower)
if exclude_user_id:
query = query.where(User.id != exclude_user_id)
result = await db.execute(query)
+1 -1
View File
@@ -756,7 +756,7 @@ class RioPayPayment(Base):
__tablename__ = 'riopay_payments'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
# Идентификаторы
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
+12 -19
View File
@@ -280,12 +280,6 @@ class RemnaWaveAPI:
'X-Real-IP': '127.0.0.1',
}
# Caddy авторизация — добавляется поверх основной
if self.caddy_token:
# Caddy Security: готовый base64 токен используется как есть
headers['Authorization'] = f'Basic {self.caddy_token}'
logger.debug('Используем Caddy Basic Auth')
# Основная авторизация RemnaWave API
if self.auth_type == 'basic' and self.username and self.password:
credentials = f'{self.username}:{self.password}'
@@ -293,16 +287,16 @@ class RemnaWaveAPI:
headers['X-Api-Key'] = f'Basic {encoded_credentials}'
logger.debug('Используем Basic Auth в X-Api-Key заголовке')
elif self.auth_type == 'caddy':
# Для caddy auth_type основная авторизация уже в Authorization header
# Но API ключ всё равно нужен для RemnaWave
# Caddy Security: caddy_token → X-Api-Key, api_key → Authorization: Bearer
if self.api_key:
headers['X-Api-Key'] = self.api_key
logger.debug('Используем API ключ для RemnaWave + Caddy авторизацию')
headers['Authorization'] = f'Bearer {self.api_key}'
if self.caddy_token:
headers['X-Api-Key'] = self.caddy_token
logger.debug('Используем Caddy авторизацию')
else:
# api_key или bearer — стандартный режим
headers['X-Api-Key'] = self.api_key
if not self.caddy_token:
headers['Authorization'] = f'Bearer {self.api_key}'
headers['Authorization'] = f'Bearer {self.api_key}'
logger.debug('Используем API ключ в X-Api-Key заголовке')
return headers
@@ -574,13 +568,12 @@ class RemnaWaveAPI:
if external_squad_uuid is not ...:
data['externalSquadUuid'] = external_squad_uuid
logger.info(
'PATCH /api/users payload',
uuid=uuid,
hwidDeviceLimit=data.get('hwidDeviceLimit'),
status=data.get('status'),
)
response = await self._make_request('PATCH', '/api/users', data)
try:
response = await self._make_request('PATCH', '/api/users', data)
except Exception:
# Логируем полный payload при ошибке для диагностики A039
logger.error('PATCH /api/users FAILED — full payload', payload=data)
raise
user = self._parse_user(response['response'])
logger.info(
'PATCH /api/users response',
+13 -4
View File
@@ -72,18 +72,21 @@ class TributeService:
status = None
amount_kopeks = 0
telegram_user_id = None
trb_user_id = None
payment_id = webhook_data.get('id') or webhook_data.get('payment_id')
status = webhook_data.get('status')
amount_kopeks = webhook_data.get('amount', 0)
telegram_user_id = webhook_data.get('telegram_user_id') or webhook_data.get('user_id')
telegram_user_id = webhook_data.get('telegram_user_id')
trb_user_id = webhook_data.get('trb_user_id')
if not payment_id and 'payload' in webhook_data:
data = webhook_data['payload']
payment_id = data.get('id') or data.get('payment_id')
status = data.get('status')
amount_kopeks = data.get('amount', 0)
telegram_user_id = data.get('telegram_user_id') or data.get('user_id')
telegram_user_id = data.get('telegram_user_id')
trb_user_id = data.get('trb_user_id')
if not payment_id and 'name' in webhook_data:
event_name = webhook_data.get('name')
@@ -91,6 +94,7 @@ class TributeService:
payment_id = str(data.get('donation_request_id'))
amount_kopeks = data.get('amount', 0)
telegram_user_id = data.get('telegram_user_id')
trb_user_id = data.get('trb_user_id')
if event_name in ('new_donation', 'recurrent_donation'):
status = 'paid'
@@ -100,15 +104,19 @@ class TributeService:
status = 'unknown'
logger.info(
'📝 Извлеченные данные: payment_id=, status=, amount_kopeks=, user_id',
'📝 Извлеченные данные: payment_id=, status=, amount_kopeks=, telegram_user_id=, trb_user_id=',
payment_id=payment_id,
status=status,
amount_kopeks=amount_kopeks,
telegram_user_id=telegram_user_id,
trb_user_id=trb_user_id,
)
if not telegram_user_id:
logger.error('❌ Не найден telegram_user_id в webhook данных')
logger.error(
'❌ Не найден telegram_user_id в webhook данных',
trb_user_id=trb_user_id,
)
logger.error(
'🔍 Полные данные для отладки', dumps=json.dumps(webhook_data, ensure_ascii=False, indent=2)
)
@@ -124,6 +132,7 @@ class TributeService:
'event_type': 'payment',
'payment_id': payment_id or f'tribute_{telegram_user_id}_{amount_kopeks}',
'user_id': telegram_user_id,
'trb_user_id': trb_user_id,
'amount_kopeks': int(amount_kopeks) if amount_kopeks else 0,
'status': status or 'paid',
'external_id': f'donation_{payment_id or "unknown"}',
+42 -14
View File
@@ -1103,13 +1103,27 @@ async def confirm_button_selection(callback: types.CallbackQuery, db_user: User,
await callback.message.delete()
except Exception:
pass
await callback.bot.send_photo(
chat_id=callback.message.chat.id,
photo=media_file_id,
caption=preview_text,
reply_markup=types.InlineKeyboardMarkup(inline_keyboard=keyboard),
parse_mode='HTML',
)
# Telegram ограничивает caption до 1024 символов
if len(preview_text) <= 1024:
await callback.bot.send_photo(
chat_id=callback.message.chat.id,
photo=media_file_id,
caption=preview_text,
reply_markup=types.InlineKeyboardMarkup(inline_keyboard=keyboard),
parse_mode='HTML',
)
else:
# Фото без caption + текст отдельным сообщением
await callback.bot.send_photo(
chat_id=callback.message.chat.id,
photo=media_file_id,
)
await callback.bot.send_message(
chat_id=callback.message.chat.id,
text=preview_text,
reply_markup=types.InlineKeyboardMarkup(inline_keyboard=keyboard),
parse_mode='HTML',
)
else:
# Если нет file_id, используем safe редактирование
await safe_edit_or_send_text(
@@ -1244,13 +1258,27 @@ async def confirm_broadcast(callback: types.CallbackQuery, db_user: User, state:
'video': 'video',
'document': 'document',
}[media_type]
await send_method(
chat_id=telegram_id,
**{media_kwarg: media_file_id},
caption=message_text,
parse_mode='HTML',
reply_markup=broadcast_keyboard,
)
# Telegram ограничивает caption до 1024 символов
if len(message_text) <= 1024:
await send_method(
chat_id=telegram_id,
**{media_kwarg: media_file_id},
caption=message_text,
parse_mode='HTML',
reply_markup=broadcast_keyboard,
)
else:
# Медиа без caption + текст отдельным сообщением
await send_method(
chat_id=telegram_id,
**{media_kwarg: media_file_id},
)
await callback.bot.send_message(
chat_id=telegram_id,
text=message_text,
parse_mode='HTML',
reply_markup=broadcast_keyboard,
)
else:
# Неизвестный media_type — отправляем как текст
await callback.bot.send_message(
+51 -6
View File
@@ -4457,6 +4457,11 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
subscription_service = SubscriptionService()
# TOCTOU protection: lock user row before pricing to prevent concurrent balance modifications
from app.database.crud.user import lock_user_for_pricing
target_user = await lock_user_for_pricing(db, target_user.id)
try:
price_kopeks = await _calculate_subscription_period_price(
db,
@@ -4585,11 +4590,10 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
# Внешний сквад: синхронизируем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
remnawave_user = await api.update_user(**update_kwargs)
else:
@@ -4914,7 +4918,7 @@ async def admin_buy_tariff_execute(callback: types.CallbackQuery, db_user: User,
user_id = int(parts[4])
tariff_id = int(parts[5])
period = int(parts[6])
price_kopeks = int(parts[7])
price_kopeks_from_callback = int(parts[7])
user_service = UserService()
profile = await user_service.get_user_profile(db, user_id)
@@ -4933,7 +4937,48 @@ async def admin_buy_tariff_execute(callback: types.CallbackQuery, db_user: User,
await callback.answer('❌ Тариф недоступен', show_alert=True)
return
# Проверяем баланс ещё раз
# TOCTOU protection: lock user row before pricing to prevent concurrent balance modifications
from app.database.crud.user import lock_user_for_pricing
target_user = await lock_user_for_pricing(db, target_user.id)
from app.database.crud.subscription import get_subscription_by_user_id
existing_subscription = await get_subscription_by_user_id(db, target_user.id)
# Recalculate price from locked state (callback data may be stale)
from app.services.pricing_engine import PricingEngine
pricing_engine = PricingEngine()
device_limit = None
if existing_subscription and existing_subscription.tariff_id == tariff_id:
device_limit = existing_subscription.device_limit
try:
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=device_limit,
user=target_user,
)
price_kopeks = result.final_total
except Exception as e:
logger.error(
'Ошибка расчёта стоимости тарифа при списании средств админом для пользователя',
telegram_id=target_user.telegram_id,
e=e,
)
await callback.answer('❌ Не удалось рассчитать стоимость тарифа', show_alert=True)
return
if price_kopeks_from_callback != price_kopeks:
logger.info(
'Стоимость тарифа для пользователя изменилась перед списанием',
telegram_id=target_user.telegram_id,
price_kopeks_from_callback=price_kopeks_from_callback,
price_kopeks=price_kopeks,
)
if target_user.balance_kopeks < price_kopeks:
await callback.answer('❌ Недостаточно средств на балансе', show_alert=True)
return
@@ -4942,7 +4987,6 @@ async def admin_buy_tariff_execute(callback: types.CallbackQuery, db_user: User,
from app.database.crud.subscription import (
create_paid_subscription,
extend_subscription,
get_subscription_by_user_id,
)
from app.database.crud.transaction import create_transaction
from app.database.crud.user import subtract_user_balance
@@ -5373,6 +5417,7 @@ async def confirm_admin_tariff_change(callback: types.CallbackQuery, db_user: Us
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
reset_reason='смена тарифа (админ)',
sync_squads=True,
)
logger.info(
+4
View File
@@ -167,6 +167,7 @@ async def process_cloudpayments_payment_amount(
'AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount:.0f}',
).format(min_amount=min_rub),
reply_markup=get_back_keyboard(db_user.language),
)
return
@@ -177,6 +178,7 @@ async def process_cloudpayments_payment_amount(
'AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount:,.0f}',
).format(max_amount=max_rub),
reply_markup=get_back_keyboard(db_user.language),
)
return
@@ -290,6 +292,7 @@ async def process_cloudpayments_amount(
'AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount:.0f}',
).format(min_amount=min_rub),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
@@ -301,6 +304,7 @@ async def process_cloudpayments_amount(
'AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount:,.0f}',
).format(max_amount=max_rub),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
+10 -4
View File
@@ -133,11 +133,13 @@ async def process_cryptobot_payment_amount(
amount_rubles = amount_kopeks / 100
if amount_rubles < 100:
await message.answer('Минимальная сумма пополнения: 100 ₽')
await message.answer('Минимальная сумма пополнения: 100 ₽', reply_markup=get_back_keyboard(db_user.language))
return
if amount_rubles > 100000:
await message.answer('Максимальная сумма пополнения: 100,000 ₽')
await message.answer(
'Максимальная сумма пополнения: 100,000 ₽', reply_markup=get_back_keyboard(db_user.language)
)
return
try:
@@ -154,11 +156,15 @@ async def process_cryptobot_payment_amount(
amount_usd = round(amount_usd, 2)
if amount_usd < 1:
await message.answer('❌ Минимальная сумма для оплаты в USD: 1.00 USD')
await message.answer(
'❌ Минимальная сумма для оплаты в USD: 1.00 USD', reply_markup=get_back_keyboard(db_user.language)
)
return
if amount_usd > 1000:
await message.answer('❌ Максимальная сумма для оплаты в USD: 1,000 USD')
await message.answer(
'❌ Максимальная сумма для оплаты в USD: 1,000 USD', reply_markup=get_back_keyboard(db_user.language)
)
return
payment_service = PaymentService(message.bot)
+2
View File
@@ -186,6 +186,7 @@ async def process_freekassa_payment_amount(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
@@ -196,6 +197,7 @@ async def process_freekassa_payment_amount(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
+4 -2
View File
@@ -129,11 +129,13 @@ async def process_heleket_payment_amount(
amount_rubles = amount_kopeks / 100
if amount_rubles < 100:
await message.answer('Минимальная сумма пополнения: 100 ₽')
await message.answer('Минимальная сумма пополнения: 100 ₽', reply_markup=get_back_keyboard(db_user.language))
return
if amount_rubles > 100000:
await message.answer('Максимальная сумма пополнения: 100,000 ₽')
await message.answer(
'Максимальная сумма пополнения: 100,000 ₽', reply_markup=get_back_keyboard(db_user.language)
)
return
payment_service = PaymentService(message.bot)
+172 -107
View File
@@ -10,6 +10,7 @@ from app.config import settings
from app.database.models import User
from app.keyboards.inline import get_back_keyboard
from app.localization.texts import get_texts
from app.services.kassa_ai_service import KASSA_AI_SUB_METHODS
from app.services.payment_service import PaymentService
from app.states import BalanceStates
from app.utils.decorators import error_handler
@@ -18,23 +19,55 @@ from app.utils.decorators import error_handler
logger = structlog.get_logger(__name__)
# --- Enabled check + display name lookup by payment method ---
_KASSA_AI_METHOD_CONFIG = {
'kassa_ai': {
'is_enabled': settings.is_kassa_ai_enabled,
'display_name': settings.get_kassa_ai_display_name,
'unavailable_text': 'KassaAI временно недоступен',
},
'kassa_ai_sbp': {
'is_enabled': settings.is_kassa_ai_sbp_enabled,
'display_name': settings.get_kassa_ai_sbp_display_name,
'unavailable_text': 'KassaAI СБП временно недоступен',
},
'kassa_ai_card': {
'is_enabled': settings.is_kassa_ai_card_enabled,
'display_name': settings.get_kassa_ai_card_display_name,
'unavailable_text': 'KassaAI Карта временно недоступна',
},
}
async def _check_topup_restriction(callback: types.CallbackQuery, db_user: User) -> bool:
"""Check if user has topup restriction. Returns True if restricted (handler should abort)."""
if not getattr(db_user, 'restriction_topup', False):
return False
texts = get_texts(db_user.language)
reason = getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором'
support_url = settings.get_support_contact_url()
keyboard = []
if support_url:
keyboard.append([InlineKeyboardButton(text='🆘 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
await callback.message.edit_text(
f'🚫 <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
)
return True
async def _create_kassa_ai_payment_and_respond(
message_or_callback,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
edit_message: bool = False,
payment_method: str = 'kassa_ai',
):
"""
Common logic for creating KassaAI payment and sending response.
Args:
message_or_callback: Either a Message or CallbackQuery object
db_user: User object
db: Database session
amount_kopeks: Amount in kopeks
edit_message: Whether to edit existing message or send new one
"""
"""Common logic for creating KassaAI payment and sending response."""
texts = get_texts(db_user.language)
amount_rub = amount_kopeks / 100
@@ -46,6 +79,9 @@ async def _create_kassa_ai_payment_and_respond(
description='Пополнение баланса',
)
sub = KASSA_AI_SUB_METHODS.get(payment_method)
payment_system_id = sub['payment_system_id'] if sub else settings.KASSA_AI_PAYMENT_SYSTEM_ID
result = await payment_service.create_kassa_ai_payment(
db=db,
user_id=db_user.id,
@@ -53,6 +89,7 @@ async def _create_kassa_ai_payment_and_respond(
description=description,
email=getattr(db_user, 'email', None),
language=db_user.language,
payment_system_id=payment_system_id,
)
if not result:
@@ -74,7 +111,8 @@ async def _create_kassa_ai_payment_and_respond(
return
payment_url = result.get('payment_url')
display_name = settings.get_kassa_ai_display_name()
cfg = _KASSA_AI_METHOD_CONFIG.get(payment_method, _KASSA_AI_METHOD_CONFIG['kassa_ai'])
display_name = cfg['display_name']()
# Create keyboard with payment button
keyboard = InlineKeyboardMarkup(
@@ -128,10 +166,9 @@ async def process_kassa_ai_payment_amount(
db: AsyncSession,
amount_kopeks: int,
state: FSMContext,
payment_method: str = 'kassa_ai',
):
"""
Process payment amount directly (called from quick_amount handlers).
"""
"""Process payment amount directly (called from custom_amount and quick_amount handlers)."""
texts = get_texts(db_user.language)
# Проверка ограничения на пополнение
@@ -161,6 +198,7 @@ async def process_kassa_ai_payment_amount(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
@@ -171,6 +209,7 @@ async def process_kassa_ai_payment_amount(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
@@ -183,53 +222,40 @@ async def process_kassa_ai_payment_amount(
db=db,
amount_kopeks=amount_kopeks,
edit_message=False,
payment_method=payment_method,
)
@error_handler
async def start_kassa_ai_topup(
# --- Generic start/quick-amount implementations ---
async def _start_kassa_ai_sub_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
payment_method: str,
):
"""
Start KassaAI top-up process - ask for amount.
"""
"""Generic start topup handler for any KassaAI sub-method."""
cfg = _KASSA_AI_METHOD_CONFIG[payment_method]
texts = get_texts(db_user.language)
# Проверка ограничения на пополнение
if getattr(db_user, 'restriction_topup', False):
reason = getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором'
support_url = settings.get_support_contact_url()
keyboard = []
if support_url:
keyboard.append([InlineKeyboardButton(text='🆘 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
if not cfg['is_enabled']():
await callback.answer(texts.t('KASSA_AI_NOT_AVAILABLE', cfg['unavailable_text']), show_alert=True)
return
await callback.message.edit_text(
f'🚫 <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
)
if await _check_topup_restriction(callback, db_user):
return
await state.set_state(BalanceStates.waiting_for_amount)
await state.update_data(payment_method='kassa_ai')
await state.update_data(payment_method=payment_method)
min_amount = settings.KASSA_AI_MIN_AMOUNT_KOPEKS // 100
max_amount = settings.KASSA_AI_MAX_AMOUNT_KOPEKS // 100
display_name = settings.get_kassa_ai_display_name()
display_name = cfg['display_name']()
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '◀️ Назад'),
callback_data='menu_balance',
)
]
]
inline_keyboard=[[InlineKeyboardButton(text=texts.t('BACK_BUTTON', '◀️ Назад'), callback_data='menu_balance')]]
)
await callback.message.edit_text(
@@ -249,6 +275,68 @@ async def start_kassa_ai_topup(
)
async def _process_kassa_ai_sub_quick_amount(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
payment_method: str,
):
"""Generic quick amount handler for any KassaAI sub-method."""
cfg = _KASSA_AI_METHOD_CONFIG[payment_method]
texts = get_texts(db_user.language)
if not cfg['is_enabled']():
await callback.answer(texts.t('KASSA_AI_NOT_AVAILABLE', cfg['unavailable_text']), show_alert=True)
return
try:
parts = callback.data.split('|')
amount_kopeks = int(parts[2]) if len(parts) >= 3 else None
if amount_kopeks is None:
raise ValueError
except (ValueError, IndexError):
await callback.answer('Invalid amount', show_alert=True)
return
if await _check_topup_restriction(callback, db_user):
return
min_amount = settings.KASSA_AI_MIN_AMOUNT_KOPEKS
max_amount = settings.KASSA_AI_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await callback.answer(texts.t('AMOUNT_TOO_LOW_SHORT', 'Сумма слишком мала'), show_alert=True)
return
if amount_kopeks > max_amount:
await callback.answer(texts.t('AMOUNT_TOO_HIGH_SHORT', 'Сумма слишком велика'), show_alert=True)
return
await callback.answer()
await state.clear()
await _create_kassa_ai_payment_and_respond(
message_or_callback=callback.message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=True,
payment_method=payment_method,
)
# --- Public handler functions (registered in main.py) ---
@error_handler
async def start_kassa_ai_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""Start KassaAI top-up process - ask for amount."""
await _start_kassa_ai_sub_topup(callback, db_user, db, state, 'kassa_ai')
@error_handler
async def process_kassa_ai_custom_amount(
message: types.Message,
@@ -256,11 +344,10 @@ async def process_kassa_ai_custom_amount(
db: AsyncSession,
state: FSMContext,
):
"""
Process custom amount input for KassaAI payment.
"""
"""Process custom amount input for KassaAI payment."""
data = await state.get_data()
if data.get('payment_method') != 'kassa_ai':
pm = data.get('payment_method', 'kassa_ai')
if pm not in _KASSA_AI_METHOD_CONFIG:
return
texts = get_texts(db_user.language)
@@ -285,6 +372,7 @@ async def process_kassa_ai_custom_amount(
db=db,
amount_kopeks=amount_kopeks,
state=state,
payment_method=pm,
)
@@ -295,72 +383,49 @@ async def process_kassa_ai_quick_amount(
db: AsyncSession,
state: FSMContext,
):
"""
Process quick amount selection for KassaAI payment.
Called when user clicks a predefined amount button.
"""
texts = get_texts(db_user.language)
"""Process quick amount selection for KassaAI payment."""
await _process_kassa_ai_sub_quick_amount(callback, db_user, db, state, 'kassa_ai')
if not settings.is_kassa_ai_enabled():
await callback.answer(
texts.t('KASSA_AI_NOT_AVAILABLE', 'KassaAI временно недоступен'),
show_alert=True,
)
return
# Extract amount from callback data: topup_amount|kassa_ai|{amount_kopeks}
try:
parts = callback.data.split('|')
if len(parts) >= 3:
amount_kopeks = int(parts[2])
else:
await callback.answer('Invalid callback data', show_alert=True)
return
except (ValueError, IndexError):
await callback.answer('Invalid amount', show_alert=True)
return
@error_handler
async def start_kassa_ai_sbp_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""Start KassaAI SBP top-up process."""
await _start_kassa_ai_sub_topup(callback, db_user, db, state, 'kassa_ai_sbp')
# Проверка ограничения на пополнение
if getattr(db_user, 'restriction_topup', False):
reason = getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором'
support_url = settings.get_support_contact_url()
keyboard = []
if support_url:
keyboard.append([InlineKeyboardButton(text='🆘 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
await callback.message.edit_text(
f'🚫 <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
)
return
@error_handler
async def process_kassa_ai_sbp_quick_amount(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""Process quick amount for KassaAI SBP."""
await _process_kassa_ai_sub_quick_amount(callback, db_user, db, state, 'kassa_ai_sbp')
# Validate amount
min_amount = settings.KASSA_AI_MIN_AMOUNT_KOPEKS
max_amount = settings.KASSA_AI_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await callback.answer(
texts.t('AMOUNT_TOO_LOW_SHORT', 'Сумма слишком мала'),
show_alert=True,
)
return
@error_handler
async def start_kassa_ai_card_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""Start KassaAI Card top-up process."""
await _start_kassa_ai_sub_topup(callback, db_user, db, state, 'kassa_ai_card')
if amount_kopeks > max_amount:
await callback.answer(
texts.t('AMOUNT_TOO_HIGH_SHORT', 'Сумма слишком велика'),
show_alert=True,
)
return
await callback.answer()
await state.clear()
await _create_kassa_ai_payment_and_respond(
message_or_callback=callback.message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=True,
)
@error_handler
async def process_kassa_ai_card_quick_amount(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""Process quick amount for KassaAI Card."""
await _process_kassa_ai_sub_quick_amount(callback, db_user, db, state, 'kassa_ai_card')
+81 -120
View File
@@ -18,7 +18,6 @@ from app.keyboards.inline import (
from app.localization.texts import get_texts
from app.states import BalanceStates
from app.utils.decorators import error_handler
from app.utils.price_display import calculate_user_price
logger = structlog.get_logger(__name__)
@@ -132,11 +131,13 @@ async def route_payment_by_method(
)
return True
if payment_method == 'kassa_ai':
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card'):
from .kassa_ai import process_kassa_ai_payment_amount
async with AsyncSessionLocal() as db:
await process_kassa_ai_payment_amount(message, db_user, db, amount_kopeks, state)
await process_kassa_ai_payment_amount(
message, db_user, db, amount_kopeks, state, payment_method=payment_method
)
return True
if payment_method == 'riopay':
@@ -153,7 +154,8 @@ async def get_quick_amount_buttons(language: str, user: User) -> list:
"""
Generate quick amount buttons with user-specific pricing and discounts.
Includes full subscription cost: base period price + devices + servers + traffic.
Uses PricingEngine as the single source of truth for all price calculations,
including base period price, devices, servers, traffic, and per-category discounts.
Args:
language: User's language for formatting
@@ -165,135 +167,77 @@ async def get_quick_amount_buttons(language: str, user: User) -> list:
if not settings.is_quick_amount_buttons_enabled():
return []
from app.config import PERIOD_PRICES
from app.database.crud.subscription import get_subscription_by_user_id
from app.database.database import AsyncSessionLocal
from app.utils.pricing_utils import apply_percentage_discount, calculate_months_from_days
from app.services.pricing_engine import pricing_engine
texts = get_texts(language)
tariff = None
tariff_prices = None
tariff_periods = None
devices_price_per_month = 0
servers_per_month_prices: list[int] = []
traffic_price_per_month = 0
buttons = []
async with AsyncSessionLocal() as db:
subscription = await get_subscription_by_user_id(db, user.id)
# В режиме тарифов получаем цены из тарифа пользователя
tariff = None
tariff_periods = None
if settings.is_tariffs_mode() and subscription and subscription.tariff_id:
from app.database.crud.tariff import get_tariff_by_id
tariff = await get_tariff_by_id(db, subscription.tariff_id)
tariff = subscription.tariff
if tariff and tariff.period_prices:
tariff_prices = {int(k): v for k, v in tariff.period_prices.items()}
tariff_periods = sorted(tariff_prices.keys())
tariff_periods = sorted(int(k) for k in tariff.period_prices.keys())
# Получаем стоимость устройств, серверов и трафика из подписки
if subscription and not subscription.is_trial:
# Устройства: в режиме тарифов используем цену и базовый лимит из тарифа
if settings.is_tariffs_mode() and tariff and tariff_prices:
tariff_device_price = getattr(tariff, 'device_price_kopeks', None)
if tariff_device_price and tariff_device_price > 0:
device_unit_price = tariff_device_price
base_device_limit = tariff.device_limit or 0
else:
device_unit_price = settings.PRICE_PER_DEVICE
base_device_limit = settings.DEFAULT_DEVICE_LIMIT
else:
device_unit_price = settings.PRICE_PER_DEVICE
base_device_limit = settings.DEFAULT_DEVICE_LIMIT
device_limit = subscription.device_limit or base_device_limit
additional_devices = max(0, device_limit - base_device_limit)
if additional_devices > 0:
devices_price_per_month = additional_devices * device_unit_price
# Серверы
connected_squads = subscription.connected_squads or []
if connected_squads:
from app.services.subscription_service import SubscriptionService
subscription_service = SubscriptionService()
_, servers_per_month_prices = await subscription_service.get_countries_price_by_uuids(
connected_squads, db, promo_group_id=user.promo_group_id
)
# Трафик
traffic_price_per_month = settings.get_traffic_price(subscription.traffic_limit_gb)
buttons = []
# Используем периоды тарифа в режиме тарифов, иначе стандартные
if tariff_periods:
periods = tariff_periods[:6]
else:
periods = settings.get_available_subscription_periods()[:6]
for period in periods:
# Получаем цену из тарифа или из PERIOD_PRICES
if tariff_prices and period in tariff_prices:
base_price_kopeks = tariff_prices[period]
if tariff_periods:
periods = tariff_periods[:6]
else:
base_price_kopeks = PERIOD_PRICES.get(period, 0)
periods = settings.get_available_subscription_periods()[:6]
if base_price_kopeks > 0:
# Базовая цена периода с промо-скидками
price_info = calculate_user_price(user, base_price_kopeks, period, 'period')
months = calculate_months_from_days(period)
# Стоимость устройств со скидкой
devices_addon = 0
if devices_price_per_month > 0:
devices_discount = user.get_promo_discount('devices', period)
devices_discounted, _ = apply_percentage_discount(devices_price_per_month, devices_discount)
devices_addon = devices_discounted * months
# Стоимость серверов со скидкой
servers_addon = 0
if servers_per_month_prices:
servers_discount = user.get_promo_discount('servers', period)
for server_price in servers_per_month_prices:
discounted, _ = apply_percentage_discount(server_price, servers_discount)
servers_addon += discounted
servers_addon *= months
# Стоимость трафика со скидкой
traffic_addon = 0
if traffic_price_per_month > 0:
traffic_discount = user.get_promo_discount('traffic', period)
traffic_discounted, _ = apply_percentage_discount(traffic_price_per_month, traffic_discount)
traffic_addon = traffic_discounted * months
total_price = price_info.final_price + devices_addon + servers_addon + traffic_addon
callback_data = f'quick_amount_{total_price}'
period_label = f'{period} дней'
# Скидка считается от полной базовой стоимости (период + аддоны без скидок)
total_base = (
base_price_kopeks
+ (devices_price_per_month + sum(servers_per_month_prices) + traffic_price_per_month) * months
)
has_discount = total_base > total_price and total_base > 0
if has_discount:
discount_pct = round((total_base - total_price) * 100 / total_base)
if discount_pct > 0:
button_text = (
f'{texts.format_price(total_base)}'
f'{texts.format_price(total_price)} '
f'(-{discount_pct}%) • {period_label}'
for period in periods:
try:
if tariff and tariff_periods and period in tariff_periods:
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=subscription.device_limit if subscription else None,
user=user,
)
elif subscription:
result = await pricing_engine.calculate_renewal_price(db, subscription, period, user=user)
else:
result = await pricing_engine.calculate_classic_new_subscription_price(
db,
period,
[],
0,
settings.DEFAULT_DEVICE_LIMIT,
user=user,
)
total_price = result.final_total
original_total = result.original_total
if total_price <= 0:
continue
callback_data = f'quick_amount_{total_price}'
period_label = f'{period} дней'
has_discount = original_total > total_price and original_total > 0
if has_discount:
discount_pct = round((original_total - total_price) * 100 / original_total)
if discount_pct > 0:
button_text = (
f'{texts.format_price(original_total)}'
f'{texts.format_price(total_price)} '
f'(-{discount_pct}%) • {period_label}'
)
else:
button_text = f'{texts.format_price(total_price)}{period_label}'
else:
button_text = f'{texts.format_price(total_price)}{period_label}'
else:
button_text = f'{texts.format_price(total_price)}{period_label}'
buttons.append(types.InlineKeyboardButton(text=button_text, callback_data=callback_data))
buttons.append(types.InlineKeyboardButton(text=button_text, callback_data=callback_data))
except Exception:
logger.warning('Failed to calculate price for period', period=period)
continue
keyboard_rows = []
for i in range(0, len(buttons), 2):
@@ -600,11 +544,13 @@ async def process_topup_amount(message: types.Message, db_user: User, state: FSM
amount_rubles = float(amount_text.replace(',', '.'))
if amount_rubles < 1:
await message.answer('Минимальная сумма пополнения: 1 ₽')
await message.answer('Минимальная сумма пополнения: 1 ₽', reply_markup=get_back_keyboard(db_user.language))
return
if amount_rubles > 50000:
await message.answer('Максимальная сумма пополнения: 50,000 ₽')
await message.answer(
'Максимальная сумма пополнения: 50,000 ₽', reply_markup=get_back_keyboard(db_user.language)
)
return
amount_kopeks = int(amount_rubles * 100)
@@ -614,13 +560,17 @@ async def process_topup_amount(message: types.Message, db_user: User, state: FSM
if payment_method in ['yookassa', 'yookassa_sbp']:
if amount_kopeks < settings.YOOKASSA_MIN_AMOUNT_KOPEKS:
min_rubles = settings.YOOKASSA_MIN_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Минимальная сумма для оплаты через YooKassa: {min_rubles:.0f}')
await message.answer(
f'❌ Минимальная сумма для оплаты через YooKassa: {min_rubles:.0f}',
reply_markup=get_back_keyboard(db_user.language),
)
return
if amount_kopeks > settings.YOOKASSA_MAX_AMOUNT_KOPEKS:
max_rubles = settings.YOOKASSA_MAX_AMOUNT_KOPEKS / 100
await message.answer(
f'❌ Максимальная сумма для оплаты через YooKassa: {max_rubles:,.0f}'.replace(',', ' ')
f'❌ Максимальная сумма для оплаты через YooKassa: {max_rubles:,.0f}'.replace(',', ' '),
reply_markup=get_back_keyboard(db_user.language),
)
return
@@ -848,10 +798,21 @@ def register_balance_handlers(dp: Dispatcher):
dp.callback_query.register(start_freekassa_card_topup, F.data == 'topup_freekassa_card')
dp.callback_query.register(process_freekassa_card_quick_amount, F.data.startswith('topup_amount|freekassa_card|'))
from .kassa_ai import process_kassa_ai_quick_amount, start_kassa_ai_topup
from .kassa_ai import (
process_kassa_ai_card_quick_amount,
process_kassa_ai_quick_amount,
process_kassa_ai_sbp_quick_amount,
start_kassa_ai_card_topup,
start_kassa_ai_sbp_topup,
start_kassa_ai_topup,
)
dp.callback_query.register(start_kassa_ai_topup, F.data == 'topup_kassa_ai')
dp.callback_query.register(process_kassa_ai_quick_amount, F.data.startswith('topup_amount|kassa_ai|'))
dp.callback_query.register(start_kassa_ai_sbp_topup, F.data == 'topup_kassa_ai_sbp')
dp.callback_query.register(process_kassa_ai_sbp_quick_amount, F.data.startswith('topup_amount|kassa_ai_sbp|'))
dp.callback_query.register(start_kassa_ai_card_topup, F.data == 'topup_kassa_ai_card')
dp.callback_query.register(process_kassa_ai_card_quick_amount, F.data.startswith('topup_amount|kassa_ai_card|'))
from .riopay import process_riopay_quick_amount, start_riopay_topup
+4 -2
View File
@@ -124,13 +124,15 @@ async def process_mulenpay_payment_amount(
if amount_kopeks < settings.MULENPAY_MIN_AMOUNT_KOPEKS:
await message.answer(
f'Минимальная сумма пополнения: {settings.format_price(settings.MULENPAY_MIN_AMOUNT_KOPEKS)}'
f'Минимальная сумма пополнения: {settings.format_price(settings.MULENPAY_MIN_AMOUNT_KOPEKS)}',
reply_markup=get_back_keyboard(db_user.language),
)
return
if amount_kopeks > settings.MULENPAY_MAX_AMOUNT_KOPEKS:
await message.answer(
f'Максимальная сумма пополнения: {settings.format_price(settings.MULENPAY_MAX_AMOUNT_KOPEKS)}'
f'Максимальная сумма пополнения: {settings.format_price(settings.MULENPAY_MAX_AMOUNT_KOPEKS)}',
reply_markup=get_back_keyboard(db_user.language),
)
return
+8 -2
View File
@@ -359,12 +359,18 @@ async def process_pal24_payment_amount(
if amount_kopeks < settings.PAL24_MIN_AMOUNT_KOPEKS:
min_rubles = settings.PAL24_MIN_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Минимальная сумма для оплаты через PayPalych: {min_rubles:.0f}')
await message.answer(
f'❌ Минимальная сумма для оплаты через PayPalych: {min_rubles:.0f}',
reply_markup=get_back_keyboard(db_user.language),
)
return
if amount_kopeks > settings.PAL24_MAX_AMOUNT_KOPEKS:
max_rubles = settings.PAL24_MAX_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Максимальная сумма для оплаты через PayPalych: {max_rubles:,.0f}'.replace(',', ' '))
await message.answer(
f'❌ Максимальная сумма для оплаты через PayPalych: {max_rubles:,.0f}'.replace(',', ' '),
reply_markup=get_back_keyboard(db_user.language),
)
return
available_methods = _get_available_pal24_methods()
+4 -2
View File
@@ -250,7 +250,8 @@ async def process_platega_payment_amount(
texts.t(
'PLATEGA_AMOUNT_TOO_LOW',
'Минимальная сумма для оплаты через Platega: {amount}',
).format(amount=settings.format_price(settings.PLATEGA_MIN_AMOUNT_KOPEKS))
).format(amount=settings.format_price(settings.PLATEGA_MIN_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
)
return
@@ -259,7 +260,8 @@ async def process_platega_payment_amount(
texts.t(
'PLATEGA_AMOUNT_TOO_HIGH',
'Максимальная сумма для оплаты через Platega: {amount}',
).format(amount=settings.format_price(settings.PLATEGA_MAX_AMOUNT_KOPEKS))
).format(amount=settings.format_price(settings.PLATEGA_MAX_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
)
return
+2
View File
@@ -161,6 +161,7 @@ async def process_riopay_payment_amount(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
@@ -171,6 +172,7 @@ async def process_riopay_payment_amount(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
+4 -2
View File
@@ -120,7 +120,8 @@ async def process_wata_payment_amount(
texts.t(
'WATA_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {amount}',
).format(amount=settings.format_price(settings.WATA_MIN_AMOUNT_KOPEKS))
).format(amount=settings.format_price(settings.WATA_MIN_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
)
return
@@ -129,7 +130,8 @@ async def process_wata_payment_amount(
texts.t(
'WATA_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {amount}',
).format(amount=settings.format_price(settings.WATA_MAX_AMOUNT_KOPEKS))
).format(amount=settings.format_price(settings.WATA_MAX_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
)
return
+16 -4
View File
@@ -178,12 +178,18 @@ async def process_yookassa_payment_amount(
if amount_kopeks < settings.YOOKASSA_MIN_AMOUNT_KOPEKS:
min_rubles = settings.YOOKASSA_MIN_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Минимальная сумма для оплаты картой: {min_rubles:.0f}')
await message.answer(
f'❌ Минимальная сумма для оплаты картой: {min_rubles:.0f}',
reply_markup=get_back_keyboard(db_user.language),
)
return
if amount_kopeks > settings.YOOKASSA_MAX_AMOUNT_KOPEKS:
max_rubles = settings.YOOKASSA_MAX_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Максимальная сумма для оплаты картой: {max_rubles:,.0f}'.replace(',', ' '))
await message.answer(
f'❌ Максимальная сумма для оплаты картой: {max_rubles:,.0f}'.replace(',', ' '),
reply_markup=get_back_keyboard(db_user.language),
)
return
try:
@@ -327,12 +333,18 @@ async def process_yookassa_sbp_payment_amount(
if amount_kopeks < settings.YOOKASSA_MIN_AMOUNT_KOPEKS:
min_rubles = settings.YOOKASSA_MIN_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Минимальная сумма для оплаты через СБП: {min_rubles:.0f}')
await message.answer(
f'❌ Минимальная сумма для оплаты через СБП: {min_rubles:.0f}',
reply_markup=get_back_keyboard(db_user.language),
)
return
if amount_kopeks > settings.YOOKASSA_MAX_AMOUNT_KOPEKS:
max_rubles = settings.YOOKASSA_MAX_AMOUNT_KOPEKS / 100
await message.answer(f'❌ Максимальная сумма для оплаты через СБП: {max_rubles:,.0f}'.replace(',', ' '))
await message.answer(
f'❌ Максимальная сумма для оплаты через СБП: {max_rubles:,.0f}'.replace(',', ' '),
reply_markup=get_back_keyboard(db_user.language),
)
return
try:
+23 -7
View File
@@ -1249,7 +1249,7 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
"""
texts = get_texts(db_user.language)
from app.database.crud.server_squad import get_available_server_squads, get_server_ids_by_uuids
from app.database.crud.server_squad import get_available_server_squads
from app.database.crud.subscription import create_paid_subscription, get_subscription_by_user_id
from app.database.crud.transaction import create_transaction
from app.database.crud.user import subtract_user_balance
@@ -1287,7 +1287,9 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
if not connected_squads and available_servers:
connected_squads = [available_servers[0].squad_uuid]
server_ids = await get_server_ids_by_uuids(db, connected_squads) if connected_squads else []
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
balance = db_user.balance_kopeks
available_periods = sorted(settings.get_available_subscription_periods(), reverse=True)
@@ -1299,7 +1301,7 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
best_price = 0
best_pricing = None # Cache pricing result for reuse in finalize()
# Для продления используем PricingEngine (единый расчёт для всех поверхностей).
# PricingEngine единый расчёт для всех поверхностей (и продление, и новая подписка).
from app.services.pricing_engine import pricing_engine
renewal_service = SubscriptionRenewalService() if subscription else None
@@ -1310,9 +1312,15 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
pricing_result = await pricing_engine.calculate_renewal_price(db, subscription, period, user=db_user)
price = pricing_result.final_total
else:
price, _ = await subscription_service.calculate_subscription_price_with_months(
period, traffic_limit_gb, server_ids, device_limit, db, user=db_user
new_pricing = await pricing_engine.calculate_classic_new_subscription_price(
db,
period,
connected_squads,
traffic_limit_gb,
device_limit,
user=db_user,
)
price = new_pricing.final_total
if price <= balance:
best_period = period
best_price = price
@@ -1326,9 +1334,15 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
min_pricing = await pricing_engine.calculate_renewal_price(db, subscription, min_period, user=db_user)
min_price = min_pricing.final_total
else:
min_price, _ = await subscription_service.calculate_subscription_price_with_months(
min_period, traffic_limit_gb, server_ids, device_limit, db, user=db_user
min_new_pricing = await pricing_engine.calculate_classic_new_subscription_price(
db,
min_period,
connected_squads,
traffic_limit_gb,
device_limit,
user=db_user,
)
min_price = min_new_pricing.final_total
missing = min_price - balance
await callback.answer(
texts.t('INSUFFICIENT_FUNDS_DETAILED', f'❌ Недостаточно средств. Не хватает {missing // 100}'),
@@ -1365,12 +1379,14 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
)
else:
# Списать баланс ДО создания подписки (чтобы не было orphaned subscription при неудаче)
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
success = await subtract_user_balance(
db,
db_user,
best_price,
f'Активация подписки на {best_period} дней',
mark_as_paid_subscription=True,
consume_promo_offer=consume_promo,
)
if not success:
await callback.answer('❌ Недостаточно средств', show_alert=True)
+37 -9
View File
@@ -401,13 +401,25 @@ async def handle_simple_subscription_pay_with_balance(
state_data=data,
)
# Рассчитываем цену подписки
# Lock user BEFORE pricing to prevent TOCTOU
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
db_user = await lock_user_for_pricing(db, db_user.id)
# Рассчитываем цену подписки (group discounts per-category)
price_kopeks, price_breakdown = await _calculate_simple_subscription_price(
db,
subscription_params,
user=db_user,
resolved_squad_uuid=resolved_squad_uuid,
)
# PricingEngine already applies promo-offer discount inside calculate_classic_new_subscription_price.
# Only determine whether to consume the offer (zero it out after use).
from app.utils.promo_offer import get_user_active_promo_discount_percent
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
total_required = price_kopeks
logger.warning(
'SIMPLE_SUBSCRIPTION_DEBUG_PAY_BALANCE | user= | period= | base= | traffic= | devices= | servers= | discount= | total_required= | balance',
@@ -431,15 +443,13 @@ async def handle_simple_subscription_pay_with_balance(
try:
# Списываем средства с баланса пользователя
from app.database.crud.user import subtract_user_balance
purchase_description = f'Оплата подписки на {subscription_params["period_days"]} дней'
success = await subtract_user_balance(
db,
db_user,
price_kopeks,
purchase_description,
consume_promo_offer=False,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
@@ -840,7 +850,7 @@ async def handle_simple_subscription_payment_method(
state_data=data,
)
# Рассчитываем цену подписки
# Рассчитываем цену подписки (group discounts per-category)
price_kopeks, _ = await _calculate_simple_subscription_price(
db,
subscription_params,
@@ -848,6 +858,14 @@ async def handle_simple_subscription_payment_method(
resolved_squad_uuid=resolved_squad_uuid,
)
# Apply promo-offer discount on top of group discounts (consistent with balance-pay path)
from app.services.pricing_engine import PricingEngine
from app.utils.promo_offer import get_user_active_promo_discount_percent
offer_pct = get_user_active_promo_discount_percent(db_user)
if offer_pct > 0:
price_kopeks = PricingEngine.apply_discount(price_kopeks, offer_pct)
if payment_method == 'stars':
# Оплата через Telegram Stars
order = await purchase_service.create_subscription_order(
@@ -2121,13 +2139,25 @@ async def confirm_simple_subscription_purchase(
state_data=data,
)
# Рассчитываем цену подписки
# Lock user BEFORE pricing to prevent TOCTOU
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
db_user = await lock_user_for_pricing(db, db_user.id)
# Рассчитываем цену подписки (group discounts per-category)
price_kopeks, price_breakdown = await _calculate_simple_subscription_price(
db,
subscription_params,
user=db_user,
resolved_squad_uuid=resolved_squad_uuid,
)
# PricingEngine already applies promo-offer discount inside calculate_classic_new_subscription_price.
# Only determine whether to consume the offer (zero it out after use).
from app.utils.promo_offer import get_user_active_promo_discount_percent
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
total_required = price_kopeks
logger.warning(
'SIMPLE_SUBSCRIPTION_DEBUG_CONFIRM | user= | period= | base= | traffic= | devices= | servers= | discount= | total_required= | balance',
@@ -2151,15 +2181,13 @@ async def confirm_simple_subscription_purchase(
try:
# Списываем средства с баланса пользователя
from app.database.crud.user import subtract_user_balance
purchase_description = f'Оплата подписки на {subscription_params["period_days"]} дней'
success = await subtract_user_balance(
db,
db_user,
price_kopeks,
purchase_description,
consume_promo_offer=False,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
+201
View File
@@ -51,6 +51,7 @@ from app.services.privacy_policy_service import PrivacyPolicyService
from app.services.referral_service import process_referral_registration
from app.services.subscription_service import SubscriptionService
from app.services.support_settings_service import SupportSettingsService
from app.services.web_auth_service import WEB_AUTH_TOKEN_MIN_LENGTH, link_web_auth_token
from app.states import RegistrationStates
from app.utils.promo_offer import (
build_promo_offer_hint,
@@ -197,6 +198,80 @@ async def _claim_phantom_user(
return True, phantom
async def _merge_phantom_into_active_user(
db: AsyncSession,
phantom: 'User',
active_user: 'User',
) -> None:
"""Merge a phantom user (created by guest landing purchase) into an existing active user.
Transfers GuestPurchase records and handles subscription conflict.
The phantom is soft-deleted (status=DELETED, username cleared) to preserve
audit trail and avoid CASCADE deletion of payment/transaction records.
"""
from sqlalchemy import update
logger.info(
'Merging phantom user into active user',
phantom_id=phantom.id,
active_user_id=active_user.id,
phantom_username=phantom.username,
)
# Transfer GuestPurchase.user_id references
await db.execute(update(GuestPurchase).where(GuestPurchase.user_id == phantom.id).values(user_id=active_user.id))
# Transfer GuestPurchase.buyer_user_id references
await db.execute(
update(GuestPurchase).where(GuestPurchase.buyer_user_id == phantom.id).values(buyer_user_id=active_user.id)
)
# Transfer balance
if phantom.balance_kopeks and phantom.balance_kopeks > 0:
active_user.balance_kopeks = (active_user.balance_kopeks or 0) + phantom.balance_kopeks
logger.info('Transferred balance from phantom', amount_kopeks=phantom.balance_kopeks)
# Handle subscription
await db.refresh(phantom, ['subscription'])
await db.refresh(active_user, ['subscription'])
if phantom.subscription and not active_user.subscription:
# Transfer subscription from phantom to active user
phantom.subscription.user_id = active_user.id
# Transfer remnawave_uuid
if phantom.remnawave_uuid and not active_user.remnawave_uuid:
active_user.remnawave_uuid = phantom.remnawave_uuid
phantom.remnawave_uuid = None
await db.flush()
logger.info(
'Transferred subscription from phantom to active user',
subscription_id=phantom.subscription.id,
)
elif phantom.subscription:
# Both have subscriptions — disable phantom's Remnawave user and free server slots
logger.warning(
'Both phantom and active user have subscriptions, disabling phantom',
phantom_subscription_id=phantom.subscription.id,
active_subscription_id=active_user.subscription.id,
)
if phantom.remnawave_uuid:
try:
subscription_service = SubscriptionService()
await subscription_service.disable_remnawave_user(phantom.remnawave_uuid)
except Exception as exc:
logger.warning('Failed to disable phantom Remnawave user', error=str(exc))
await decrement_subscription_server_counts(db, phantom.subscription)
# Soft-delete phantom: clear identifiers to prevent future matches,
# preserve record for audit trail and avoid CASCADE deletion of payments/transactions
phantom.status = UserStatus.DELETED.value
phantom.username = None
phantom.remnawave_uuid = None
await db.flush()
logger.info('Phantom user merged and soft-deleted', phantom_id=phantom.id, active_user_id=active_user.id)
def _calculate_subscription_flags(subscription):
if not subscription:
return False, False
@@ -302,6 +377,9 @@ async def handle_potential_referral_code(message: types.Message, state: FSMConte
language = data.get('language') or (getattr(user, 'language', None) if user else None) or DEFAULT_LANGUAGE
texts = get_texts(language)
if not message.text:
return False
from app.utils.promo_rate_limiter import promo_limiter, validate_promo_format
potential_code = message.text.strip()
@@ -530,6 +608,40 @@ async def cmd_start(message: types.Message, state: FSMContext, db: AsyncSession,
await state.update_data(pending_gift_token=gift_token)
start_parameter = None # Don't treat as campaign or referral
# Handle web auth deep links: /start webauth_{token}
if start_parameter and start_parameter.startswith('webauth_'):
web_auth_token = start_parameter.removeprefix('webauth_')
if len(web_auth_token) >= WEB_AUTH_TOKEN_MIN_LENGTH:
user = db_user or await get_user_by_telegram_id(db, message.from_user.id)
if user and user.status != UserStatus.DELETED.value:
texts = get_texts(user.language)
keyboard = types.InlineKeyboardMarkup(
inline_keyboard=[
[
types.InlineKeyboardButton(
text=texts.t('WEB_AUTH_CONFIRM_YES', '✅ Да, войти'),
callback_data=f'webauth_confirm:{web_auth_token}',
),
types.InlineKeyboardButton(
text=texts.t('WEB_AUTH_CONFIRM_NO', '❌ Нет'),
callback_data='webauth_deny',
),
],
]
)
await message.answer(
texts.t(
'WEB_AUTH_CONFIRM_PROMPT',
'🔐 Подтвердите вход в личный кабинет. Если вы не запрашивали вход — нажмите «Нет».',
),
reply_markup=keyboard,
)
else:
logger.warning('Web auth attempt from unregistered user', telegram_id=message.from_user.id)
await message.answer('❌ Сначала зарегистрируйтесь в боте, затем попробуйте войти в кабинет.')
return
start_parameter = None # Invalid token, ignore
if start_parameter:
campaign = await get_campaign_by_start_parameter(
db,
@@ -586,6 +698,21 @@ async def cmd_start(message: types.Message, state: FSMContext, db: AsyncSession,
if user and user.status != UserStatus.DELETED.value:
logger.info('✅ Активный пользователь найден', telegram_id=user.telegram_id)
# Check for phantom user created by guest landing purchase and merge
if message.from_user.username:
phantom = await find_phantom_user_by_username(db, message.from_user.username)
if phantom and phantom.id != user.id:
try:
await _merge_phantom_into_active_user(db, phantom, user)
await db.refresh(user, ['subscription'])
except Exception:
await db.rollback()
logger.exception(
'Failed to merge phantom user',
phantom_id=phantom.id,
active_user_id=user.id,
)
profile_updated = False
if user.username != message.from_user.username:
@@ -1186,6 +1313,10 @@ async def process_referral_code_input(message: types.Message, state: FSMContext,
language = data.get('language', DEFAULT_LANGUAGE)
texts = get_texts(language)
if not message.text:
await message.answer(texts.t('REFERRAL_OR_PROMO_CODE_INVALID', '❌ Неверный реферальный код или промокод'))
return
from app.utils.promo_rate_limiter import promo_limiter, validate_promo_format
code = message.text.strip()
@@ -2341,6 +2472,33 @@ async def required_sub_channel_check(
except Exception as e:
logger.error('Ошибка при обработке реферальной регистрации', error=e)
# Применяем бонус рекламной кампании (record_campaign_registration)
campaign_message = await _apply_campaign_bonus_if_needed(db, user, state_data, texts)
try:
await db.refresh(user)
except Exception as refresh_error:
logger.error(
'Ошибка обновления данных пользователя после бонуса кампании',
telegram_id=user.telegram_id,
refresh_error=refresh_error,
)
try:
await db.refresh(user, ['subscription'])
except Exception as refresh_sub_error:
logger.error(
'Ошибка обновления подписки после бонуса кампании',
telegram_id=user.telegram_id,
refresh_sub_error=refresh_sub_error,
)
if campaign_message:
try:
await bot.send_message(
chat_id=query.from_user.id,
text=campaign_message,
)
except Exception as e:
logger.error('Ошибка отправки сообщения о бонусе кампании', error=e)
# Показываем главное меню после создания пользователя
has_active_subscription, subscription_is_active = _calculate_subscription_flags(user.subscription)
@@ -2439,6 +2597,43 @@ async def required_sub_channel_check(
pass
async def process_webauth_confirm(
callback: types.CallbackQuery,
db: AsyncSession,
):
"""Handle web auth confirmation or denial."""
await callback.answer()
if not isinstance(callback.message, types.Message):
return
if callback.data == 'webauth_deny':
await callback.message.edit_text('❌ Вход отменён.')
return
# Extract token from callback_data: "webauth_confirm:{token}"
token = callback.data.split(':', 1)[1] if ':' in callback.data else ''
if len(token) < WEB_AUTH_TOKEN_MIN_LENGTH:
await callback.message.edit_text('❌ Ошибка: неверный токен.')
return
user = await get_user_by_telegram_id(db, callback.from_user.id)
if not user or user.status != UserStatus.ACTIVE.value:
await callback.message.edit_text('❌ Учётная запись неактивна.')
return
linked = await link_web_auth_token(token, callback.from_user.id, user.id)
texts = get_texts(user.language)
if linked:
await callback.message.edit_text(
texts.t('WEB_AUTH_SUCCESS', '✅ Авторизация в кабинете подтверждена! Вернитесь в браузер.'),
)
else:
await callback.message.edit_text(
texts.t('WEB_AUTH_EXPIRED', '❌ Ссылка для входа истекла. Попробуйте снова.'),
)
def register_handlers(dp: Dispatcher):
logger.debug('=== НАЧАЛО регистрации обработчиков start.py ===')
@@ -2483,4 +2678,10 @@ def register_handlers(dp: Dispatcher):
dp.callback_query.register(required_sub_channel_check, F.data.in_(['sub_channel_check']))
logger.debug('Зарегистрирован required_sub_channel_check')
dp.callback_query.register(
process_webauth_confirm,
F.data.startswith('webauth_confirm:') | F.data.in_(['webauth_deny']),
)
logger.debug('Зарегистрирован process_webauth_confirm')
logger.debug('=== КОНЕЦ регистрации обработчиков start.py ===')
+8 -1
View File
@@ -1,4 +1,5 @@
from aiogram import types
from aiogram.exceptions import TelegramBadRequest
from aiogram.fsm.context import FSMContext
from sqlalchemy.ext.asyncio import AsyncSession
@@ -114,7 +115,13 @@ async def toggle_autopay(callback: types.CallbackQuery, db_user: User, db: Async
status = texts.t('AUTOPAY_STATUS_ENABLED', 'включен') if enable else texts.t('AUTOPAY_STATUS_DISABLED', 'выключен')
await callback.answer(texts.t('AUTOPAY_TOGGLE_SUCCESS', '✅ Автоплатеж {status}!').format(status=status))
await handle_autopay_menu(callback, db_user, db)
try:
await handle_autopay_menu(callback, db_user, db)
except TelegramBadRequest as e:
if 'message is not modified' in str(e):
pass
else:
raise
async def show_autopay_days(callback: types.CallbackQuery, db_user: User):
-37
View File
@@ -56,43 +56,6 @@ def _format_text_with_placeholders(template: str, values: dict[str, Any]) -> str
return template
def _get_addon_discount_percent_for_user(
user: User | None,
category: str,
period_days_hint: int | None = None,
) -> int:
if user is None:
return 0
promo_group = user.get_primary_promo_group()
if promo_group is None:
return 0
if not getattr(promo_group, 'apply_discounts_to_addons', True):
return 0
try:
return user.get_promo_discount(category, period_days_hint)
except AttributeError:
return 0
def _apply_addon_discount(
user: User | None,
category: str,
amount: int,
period_days_hint: int | None = None,
) -> dict[str, int]:
percent = _get_addon_discount_percent_for_user(user, category, period_days_hint)
discounted_amount, discount_value = apply_percentage_discount(amount, percent)
return {
'discounted': discounted_amount,
'discount': discount_value,
'percent': percent,
}
def _get_promo_offer_discount_percent(user: User | None) -> int:
return get_user_active_promo_discount_percent(user)
+34 -45
View File
@@ -5,9 +5,9 @@ from aiogram import types
from aiogram.fsm.context import FSMContext
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import PERIOD_PRICES, settings
from app.config import settings
from app.database.crud.transaction import create_transaction
from app.database.crud.user import subtract_user_balance
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
from app.database.models import TransactionType, User
from app.keyboards.inline import (
get_back_keyboard,
@@ -17,6 +17,7 @@ from app.keyboards.inline import (
get_manage_countries_keyboard,
)
from app.localization.texts import get_texts
from app.services.pricing_engine import PricingEngine, pricing_engine
from app.services.subscription_checkout_service import (
save_subscription_checkout_draft,
should_offer_checkout_resume,
@@ -28,7 +29,7 @@ from app.utils.pricing_utils import (
calculate_prorated_price,
)
from .common import _get_addon_discount_percent_for_user, _get_period_hint_from_subscription, logger
from .common import _get_period_hint_from_subscription, logger
from .summary import present_subscription_summary
@@ -58,7 +59,7 @@ async def handle_add_countries(callback: types.CallbackQuery, db_user: User, db:
current_countries = subscription.connected_squads
period_hint_days = _get_period_hint_from_subscription(subscription)
servers_discount_percent = _get_addon_discount_percent_for_user(
servers_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'servers',
period_hint_days,
@@ -171,7 +172,7 @@ async def handle_manage_country(callback: types.CallbackQuery, db_user: User, db
countries = await _get_available_countries(db_user.promo_group_id)
allowed_country_ids = {country['uuid'] for country in countries}
if country_uuid not in allowed_country_ids and country_uuid not in current_selected:
if country_uuid not in allowed_country_ids:
texts = get_texts(db_user.language)
await callback.answer(
texts.t(
@@ -194,7 +195,7 @@ async def handle_manage_country(callback: types.CallbackQuery, db_user: User, db
await state.update_data(countries=current_selected)
period_hint_days = _get_period_hint_from_subscription(subscription)
servers_discount_percent = _get_addon_discount_percent_for_user(
servers_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'servers',
period_hint_days,
@@ -235,11 +236,7 @@ async def apply_countries_changes(callback: types.CallbackQuery, db_user: User,
countries = await _get_available_countries(db_user.promo_group_id)
allowed_country_ids = {country['uuid'] for country in countries}
selected_countries = [
country_uuid
for country_uuid in selected_countries
if country_uuid in allowed_country_ids or country_uuid in current_countries
]
selected_countries = [country_uuid for country_uuid in selected_countries if country_uuid in allowed_country_ids]
added = [c for c in selected_countries if c not in current_countries]
removed = [c for c in current_countries if c not in selected_countries]
@@ -257,7 +254,12 @@ async def apply_countries_changes(callback: types.CallbackQuery, db_user: User,
days_to_pay = max(1, (subscription.end_date - now).days)
period_hint_days = days_to_pay if days_to_pay > 0 else None
servers_discount_percent = _get_addon_discount_percent_for_user(
# TOCTOU protection: lock user row before reading discount and charging balance
db_user = await lock_user_for_pricing(db, db_user.id)
subscription = db_user.subscription
servers_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'servers',
period_hint_days,
@@ -392,7 +394,7 @@ async def apply_countries_changes(callback: types.CallbackQuery, db_user: User,
await db.commit()
subscription_service = SubscriptionService()
await subscription_service.update_remnawave_user(db, subscription)
await subscription_service.update_remnawave_user(db, subscription, sync_squads=True)
await db.refresh(subscription)
@@ -496,31 +498,18 @@ async def select_country(callback: types.CallbackQuery, state: FSMContext, db_us
await callback.answer('❌ Сервер недоступен для вашей промогруппы', show_alert=True)
return
period_base_price = PERIOD_PRICES.get(data['period_days'], 0)
discounted_base_price, _ = apply_percentage_discount(
period_base_price,
db_user.get_promo_discount('period', data['period_days']),
)
base_price = discounted_base_price + settings.get_traffic_price(data['traffic_gb'])
try:
subscription_service = SubscriptionService()
countries_price, _ = await subscription_service.get_countries_price_by_uuids(
selected_countries,
db,
promo_group_id=db_user.promo_group_id,
)
except AttributeError:
logger.warning('Используем fallback функцию для расчета цен стран')
countries_price, _ = await get_countries_price_by_uuids_fallback(
selected_countries,
db,
promo_group_id=db_user.promo_group_id,
)
data['countries'] = selected_countries
data['total_price'] = base_price + countries_price
# Вычисляем цену через PricingEngine с актуальными FSM-данными
pricing_result = await pricing_engine.calculate_classic_new_subscription_price(
db,
data['period_days'],
list(selected_countries),
data.get('traffic_gb', 0) or 0,
data.get('devices', settings.DEFAULT_DEVICE_LIMIT),
user=db_user,
)
data['total_price'] = pricing_result.final_total
await state.set_data(data)
await callback.message.edit_reply_markup(
@@ -700,7 +689,7 @@ async def handle_add_country_to_subscription(
total_price = 0
subscription = db_user.subscription
period_hint_days = _get_period_hint_from_subscription(subscription)
servers_discount_percent = _get_addon_discount_percent_for_user(
servers_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'servers',
period_hint_days,
@@ -795,11 +784,7 @@ async def confirm_add_countries_to_subscription(
countries = await _get_available_countries(db_user.promo_group_id)
allowed_country_ids = {country['uuid'] for country in countries}
selected_countries = [
country_uuid
for country_uuid in selected_countries
if country_uuid in allowed_country_ids or country_uuid in current_countries
]
selected_countries = [country_uuid for country_uuid in selected_countries if country_uuid in allowed_country_ids]
new_countries = [c for c in selected_countries if c not in current_countries]
removed_countries = [c for c in current_countries if c not in selected_countries]
@@ -808,12 +793,16 @@ async def confirm_add_countries_to_subscription(
await callback.answer('⚠️ Изменения не обнаружены', show_alert=True)
return
# TOCTOU protection: lock user row before reading discount and charging balance
db_user = await lock_user_for_pricing(db, db_user.id)
subscription = db_user.subscription
total_price = 0
new_countries_names = []
removed_countries_names = []
period_hint_days = _get_period_hint_from_subscription(subscription)
servers_discount_percent = _get_addon_discount_percent_for_user(
servers_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'servers',
period_hint_days,
@@ -909,7 +898,7 @@ async def confirm_add_countries_to_subscription(
await db.commit()
subscription_service = SubscriptionService()
await subscription_service.update_remnawave_user(db, subscription)
await subscription_service.update_remnawave_user(db, subscription, sync_squads=True)
await db.refresh(db_user)
await db.refresh(subscription)
+42 -8
View File
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.transaction import create_transaction
from app.database.crud.user import subtract_user_balance
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
from app.database.models import Subscription, TransactionType, User
from app.keyboards.inline import (
get_app_selection_keyboard,
@@ -21,6 +21,7 @@ from app.keyboards.inline import (
get_specific_app_keyboard,
)
from app.localization.texts import get_texts
from app.services.pricing_engine import PricingEngine
from app.services.remnawave_service import RemnaWaveService
from app.services.subscription_service import SubscriptionService
from app.services.user_cart_service import user_cart_service
@@ -33,7 +34,6 @@ from app.utils.subscription_utils import (
)
from .common import (
_get_addon_discount_percent_for_user,
_get_period_hint_from_subscription,
get_apps_for_platform_async,
get_device_name,
@@ -174,7 +174,7 @@ async def handle_change_devices(callback: types.CallbackQuery, db_user: User, db
current_devices = subscription.device_limit
period_hint_days = _get_period_hint_from_subscription(subscription)
devices_discount_percent = _get_addon_discount_percent_for_user(
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
period_hint_days,
@@ -325,7 +325,7 @@ async def confirm_change_devices(callback: types.CallbackQuery, db_user: User, d
days_left = max(1, (subscription.end_date - now).days)
period_hint_days = days_left
devices_discount_percent = _get_addon_discount_percent_for_user(
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
period_hint_days,
@@ -345,7 +345,7 @@ async def confirm_change_devices(callback: types.CallbackQuery, db_user: User, d
days_left = max(1, (subscription.end_date - now).days)
period_hint_days = days_left
devices_discount_percent = _get_addon_discount_percent_for_user(
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
period_hint_days,
@@ -492,7 +492,8 @@ async def confirm_change_devices(callback: types.CallbackQuery, db_user: User, d
async def execute_change_devices(callback: types.CallbackQuery, db_user: User, db: AsyncSession):
callback_parts = callback.data.split('_')
new_devices_count = int(callback_parts[3])
price = int(callback_parts[4])
db_user = await lock_user_for_pricing(db, db_user.id)
texts = get_texts(db_user.language)
subscription = db_user.subscription
@@ -514,12 +515,15 @@ async def execute_change_devices(callback: types.CallbackQuery, db_user: User, d
show_alert=True,
)
return
price_per_device = tariff_device_price
elif not settings.is_devices_selection_enabled():
await callback.answer(
texts.t('DEVICES_SELECTION_DISABLED', '⚠️ Изменение количества устройств недоступно'),
show_alert=True,
)
return
else:
price_per_device = settings.PRICE_PER_DEVICE
# Проверяем минимальное количество устройств на тарифе
tariff_min_devices = (getattr(tariff, 'device_limit', 1) or 1) if tariff else 1
@@ -533,6 +537,33 @@ async def execute_change_devices(callback: types.CallbackQuery, db_user: User, d
)
return
# Recompute price under lock (callback-baked value may be stale)
devices_difference = new_devices_count - current_devices
if devices_difference > 0:
if tariff:
chargeable_devices = devices_difference
elif current_devices < settings.DEFAULT_DEVICE_LIMIT:
free_devices = settings.DEFAULT_DEVICE_LIMIT - current_devices
chargeable_devices = max(0, devices_difference - free_devices)
else:
chargeable_devices = devices_difference
devices_price_per_month = chargeable_devices * price_per_device
days_left = max(1, (subscription.end_date - datetime.now(UTC)).days)
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
days_left,
)
discounted_per_month, _ = apply_percentage_discount(
devices_price_per_month,
devices_discount_percent,
)
price = int(discounted_per_month * days_left / 30)
price = max(100, price)
else:
price = 0
try:
if price > 0:
success = await subtract_user_balance(
@@ -1148,6 +1179,9 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
devices_price_per_month = devices_count * price_per_device
# TOCTOU: lock user row before reading promo/discount state
db_user = await lock_user_for_pricing(db, db_user.id)
# Проверяем является ли тариф суточным
is_daily_tariff = tariff and getattr(tariff, 'is_daily', False)
@@ -1157,7 +1191,7 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
days_left = max(1, (subscription.end_date - now).days)
period_hint_days = days_left
devices_discount_percent = _get_addon_discount_percent_for_user(
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
period_hint_days,
@@ -1177,7 +1211,7 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
days_left = max(1, (subscription.end_date - now).days)
period_hint_days = days_left
devices_discount_percent = _get_addon_discount_percent_for_user(
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
period_hint_days,
+104 -239
View File
@@ -4,18 +4,15 @@ from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import PERIOD_PRICES, settings
from app.config import settings
from app.database.models import User
from app.utils.pricing_utils import (
apply_percentage_discount,
calculate_months_from_days,
format_period_description,
validate_pricing_calculation,
)
from app.utils.timezone import format_local_datetime
from .common import _apply_discount_to_monthly_component, _apply_promo_offer_discount, logger
from .countries import _get_available_countries, _get_countries_info, get_countries_price_by_uuids_fallback
from .common import logger
from .countries import _get_available_countries, _get_countries_info
from .devices import get_current_devices_count
from .promo import _build_promo_group_discount_text, _get_promo_offer_hint
@@ -25,82 +22,18 @@ async def _prepare_subscription_summary(
data: dict[str, Any],
texts,
) -> tuple[str, dict[str, Any]]:
from app.database.database import AsyncSessionLocal
from app.services.pricing_engine import PricingEngine, pricing_engine
summary_data = dict(data)
if 'period_days' not in summary_data:
raise KeyError('period_days missing from subscription data — FSM state likely expired')
countries = await _get_available_countries(db_user.promo_group_id)
months_in_period = calculate_months_from_days(summary_data['period_days'])
period_display = format_period_description(summary_data['period_days'], db_user.language)
base_price_original = PERIOD_PRICES.get(summary_data['period_days'], 0)
period_discount_percent = db_user.get_promo_discount(
'period',
summary_data['period_days'],
)
base_price, base_discount_total = apply_percentage_discount(
base_price_original,
period_discount_percent,
)
if settings.is_traffic_fixed():
traffic_limit = settings.get_fixed_traffic_limit()
traffic_price_per_month = settings.get_traffic_price(traffic_limit)
final_traffic_gb = traffic_limit
else:
traffic_gb = summary_data.get('traffic_gb', 0)
traffic_price_per_month = settings.get_traffic_price(traffic_gb)
final_traffic_gb = traffic_gb
traffic_discount_percent = db_user.get_promo_discount(
'traffic',
summary_data['period_days'],
)
traffic_component = _apply_discount_to_monthly_component(
traffic_price_per_month,
traffic_discount_percent,
months_in_period,
)
total_traffic_price = traffic_component['total']
countries_price_per_month = 0
selected_countries_names: list[str] = []
selected_server_prices: list[int] = []
server_monthly_prices: list[int] = []
selected_country_ids = set(summary_data.get('countries', []))
for country in countries:
if country['uuid'] in selected_country_ids:
server_price_per_month = country['price_kopeks']
countries_price_per_month += server_price_per_month
selected_countries_names.append(html.escape(country['name']))
server_monthly_prices.append(server_price_per_month)
servers_discount_percent = db_user.get_promo_discount(
'servers',
summary_data['period_days'],
)
total_countries_price = 0
total_servers_discount = 0
discounted_servers_price_per_month = 0
for server_price_per_month in server_monthly_prices:
discounted_per_month, discount_per_month = apply_percentage_discount(
server_price_per_month,
servers_discount_percent,
)
total_price_for_server = discounted_per_month * months_in_period
total_discount_for_server = discount_per_month * months_in_period
discounted_servers_price_per_month += discounted_per_month
total_countries_price += total_price_for_server
total_servers_discount += total_discount_for_server
selected_server_prices.append(total_price_for_server)
period_days = summary_data['period_days']
# --- Resolve device limit (same logic as before) ---
devices_selection_enabled = settings.is_devices_selection_enabled()
forced_disabled_limit: int | None = None
if devices_selection_enabled:
devices_selected = summary_data.get('devices', settings.DEFAULT_DEVICE_LIMIT)
else:
@@ -109,54 +42,75 @@ async def _prepare_subscription_summary(
devices_selected = settings.DEFAULT_DEVICE_LIMIT
else:
devices_selected = forced_disabled_limit
summary_data['devices'] = devices_selected
additional_devices = max(0, devices_selected - settings.DEFAULT_DEVICE_LIMIT)
devices_price_per_month = additional_devices * settings.PRICE_PER_DEVICE
devices_discount_percent = db_user.get_promo_discount(
'devices',
summary_data['period_days'],
)
devices_component = _apply_discount_to_monthly_component(
devices_price_per_month,
devices_discount_percent,
months_in_period,
)
total_devices_price = devices_component['total']
total_price = base_price + total_traffic_price + total_countries_price + total_devices_price
# --- Resolve traffic ---
if settings.is_traffic_fixed():
final_traffic_gb = settings.get_fixed_traffic_limit()
else:
final_traffic_gb = summary_data.get('traffic_gb', 0)
# --- Resolve connected squads ---
connected_squads = list(summary_data.get('countries', []))
# --- Delegate pricing to PricingEngine ---
async with AsyncSessionLocal() as db:
pricing = await pricing_engine.calculate_classic_new_subscription_price(
db,
period_days,
connected_squads,
final_traffic_gb,
devices_selected,
user=db_user,
)
# --- Build legacy dict from PricingEngine result ---
details = PricingEngine.classic_pricing_to_purchase_details(pricing)
bd = pricing.breakdown
months_in_period = details['months_in_period']
base_price = details['base_price']
base_price_original = details['base_price_original']
base_discount_total = details['base_discount_total']
period_discount_percent = details['base_discount_percent']
traffic_price_per_month = details['traffic_price_per_month']
traffic_discount_percent = details['traffic_discount_percent']
traffic_discount_total = details['traffic_discount_total']
total_traffic_price = details['total_traffic_price']
servers_price_per_month = details['servers_price_per_month']
servers_discount_percent = details['servers_discount_percent']
servers_discount_total = details['servers_discount_total']
total_servers_price = details['total_servers_price']
devices_price_per_month = details['devices_price_per_month']
devices_discount_percent = details['devices_discount_percent']
devices_discount_total = details['devices_discount_total']
total_devices_price = details['total_devices_price']
# Compute discounted per-month values (not in classic_pricing_to_purchase_details)
traffic_discounted_per_month = PricingEngine.apply_discount(traffic_price_per_month, traffic_discount_percent)
servers_discounted_per_month = PricingEngine.apply_discount(servers_price_per_month, servers_discount_percent)
devices_discounted_per_month = PricingEngine.apply_discount(devices_price_per_month, devices_discount_percent)
discounted_monthly_additions = (
traffic_component['discounted_per_month']
+ discounted_servers_price_per_month
+ devices_component['discounted_per_month']
traffic_discounted_per_month + servers_discounted_per_month + devices_discounted_per_month
)
is_valid = validate_pricing_calculation(
base_price,
discounted_monthly_additions,
months_in_period,
total_price,
)
if not is_valid:
raise ValueError('Subscription price calculation validation failed')
original_total_price = total_price
promo_offer_component = _apply_promo_offer_discount(db_user, total_price)
if promo_offer_component['discount'] > 0:
total_price = promo_offer_component['discounted']
# --- Promo offer discount (already computed by PricingEngine) ---
promo_offer_discount = pricing.promo_offer_discount
offer_pct = bd.get('offer_discount_pct', 0)
# subtotal before promo offer = final_total + promo_offer_discount
subtotal_before_offer = pricing.final_total + promo_offer_discount
total_price = pricing.final_total
summary_data['total_price'] = total_price
if promo_offer_component['discount'] > 0:
summary_data['promo_offer_discount_percent'] = promo_offer_component['percent']
summary_data['promo_offer_discount_value'] = promo_offer_component['discount']
summary_data['total_price_before_promo_offer'] = original_total_price
if promo_offer_discount > 0:
summary_data['promo_offer_discount_percent'] = offer_pct
summary_data['promo_offer_discount_value'] = promo_offer_discount
summary_data['total_price_before_promo_offer'] = subtotal_before_offer
else:
summary_data.pop('promo_offer_discount_percent', None)
summary_data.pop('promo_offer_discount_value', None)
summary_data.pop('total_price_before_promo_offer', None)
summary_data['server_prices_for_period'] = selected_server_prices
summary_data['server_prices_for_period'] = details['servers_individual_prices']
summary_data['months_in_period'] = months_in_period
summary_data['base_price'] = base_price
summary_data['base_price_original'] = base_price_original
@@ -164,24 +118,27 @@ async def _prepare_subscription_summary(
summary_data['base_discount_total'] = base_discount_total
summary_data['final_traffic_gb'] = final_traffic_gb
summary_data['traffic_price_per_month'] = traffic_price_per_month
summary_data['traffic_discount_percent'] = traffic_component['discount_percent']
summary_data['traffic_discount_total'] = traffic_component['discount_total']
summary_data['traffic_discounted_price_per_month'] = traffic_component['discounted_per_month']
summary_data['traffic_discount_percent'] = traffic_discount_percent
summary_data['traffic_discount_total'] = traffic_discount_total
summary_data['traffic_discounted_price_per_month'] = traffic_discounted_per_month
summary_data['total_traffic_price'] = total_traffic_price
summary_data['servers_price_per_month'] = countries_price_per_month
summary_data['countries_price_per_month'] = countries_price_per_month
summary_data['servers_price_per_month'] = servers_price_per_month
summary_data['countries_price_per_month'] = servers_price_per_month
summary_data['servers_discount_percent'] = servers_discount_percent
summary_data['servers_discount_total'] = total_servers_discount
summary_data['servers_discounted_price_per_month'] = discounted_servers_price_per_month
summary_data['total_servers_price'] = total_countries_price
summary_data['total_countries_price'] = total_countries_price
summary_data['servers_discount_total'] = servers_discount_total
summary_data['servers_discounted_price_per_month'] = servers_discounted_per_month
summary_data['total_servers_price'] = total_servers_price
summary_data['total_countries_price'] = total_servers_price
summary_data['devices_price_per_month'] = devices_price_per_month
summary_data['devices_discount_percent'] = devices_component['discount_percent']
summary_data['devices_discount_total'] = devices_component['discount_total']
summary_data['devices_discounted_price_per_month'] = devices_component['discounted_per_month']
summary_data['devices_discount_percent'] = devices_discount_percent
summary_data['devices_discount_total'] = devices_discount_total
summary_data['devices_discounted_price_per_month'] = devices_discounted_per_month
summary_data['total_devices_price'] = total_devices_price
summary_data['discounted_monthly_additions'] = discounted_monthly_additions
# --- Build display text ---
period_display = format_period_description(period_days, db_user.language)
if settings.is_traffic_fixed():
if final_traffic_gb == 0:
traffic_display = 'Безлимитный'
@@ -192,6 +149,13 @@ async def _prepare_subscription_summary(
else:
traffic_display = f'{summary_data.get("traffic_gb", 0)} ГБ'
# Resolve country display names (still needed for the summary text)
countries = await _get_available_countries(db_user.promo_group_id)
selected_country_ids = set(connected_squads)
selected_countries_names: list[str] = [
html.escape(country['name']) for country in countries if country['uuid'] in selected_country_ids
]
details_lines = []
# Добавляем строку базового периода только если цена не равна 0
@@ -212,40 +176,34 @@ async def _prepare_subscription_summary(
f'- Трафик: {texts.format_price(traffic_price_per_month)}/мес × {months_in_period}'
f' = {texts.format_price(total_traffic_price)}'
)
if traffic_component['discount_total'] > 0:
traffic_line += (
f' (скидка {traffic_component["discount_percent"]}%:'
f' -{texts.format_price(traffic_component["discount_total"])})'
)
if traffic_discount_total > 0:
traffic_line += f' (скидка {traffic_discount_percent}%: -{texts.format_price(traffic_discount_total)})'
details_lines.append(traffic_line)
if total_countries_price > 0:
if total_servers_price > 0:
servers_line = (
f'- Серверы: {texts.format_price(countries_price_per_month)}/мес × {months_in_period}'
f' = {texts.format_price(total_countries_price)}'
f'- Серверы: {texts.format_price(servers_price_per_month)}/мес × {months_in_period}'
f' = {texts.format_price(total_servers_price)}'
)
if total_servers_discount > 0:
servers_line += f' (скидка {servers_discount_percent}%: -{texts.format_price(total_servers_discount)})'
if servers_discount_total > 0:
servers_line += f' (скидка {servers_discount_percent}%: -{texts.format_price(servers_discount_total)})'
details_lines.append(servers_line)
if devices_selection_enabled and total_devices_price > 0:
devices_line = (
f'- Доп. устройства: {texts.format_price(devices_price_per_month)}/мес × {months_in_period}'
f' = {texts.format_price(total_devices_price)}'
)
if devices_component['discount_total'] > 0:
devices_line += (
f' (скидка {devices_component["discount_percent"]}%:'
f' -{texts.format_price(devices_component["discount_total"])})'
)
if devices_discount_total > 0:
devices_line += f' (скидка {devices_discount_percent}%: -{texts.format_price(devices_discount_total)})'
details_lines.append(devices_line)
if promo_offer_component['discount'] > 0:
if promo_offer_discount > 0:
details_lines.append(
texts.t(
'SUBSCRIPTION_SUMMARY_PROMO_DISCOUNT',
'- Промо-предложение: -{amount} ({percent}% дополнительно)',
).format(
amount=texts.format_price(promo_offer_component['discount']),
percent=promo_offer_component['percent'],
amount=texts.format_price(promo_offer_discount),
percent=offer_pct,
)
)
@@ -309,114 +267,21 @@ async def get_subscription_cost(subscription, db: AsyncSession) -> int:
if subscription.is_trial:
return 0
from app.config import settings
from app.database.crud.tariff import get_tariff_by_id
from app.services.subscription_service import SubscriptionService
subscription_service = SubscriptionService()
from app.services.pricing_engine import pricing_engine
try:
owner = subscription.user
except AttributeError:
owner = None
promo_group_id = getattr(owner, 'promo_group_id', None) if owner else None
# В тарифном режиме цена тарифа уже включает серверы и трафик
tariff = None
tariff_price_found = False
if settings.is_tariffs_mode() and subscription.tariff_id:
tariff = await get_tariff_by_id(db, subscription.tariff_id)
if tariff and tariff.period_prices:
base_cost_original = tariff.period_prices.get('30', 0) or tariff.period_prices.get(30, 0)
if base_cost_original > 0:
tariff_price_found = True
if not tariff_price_found:
base_cost_original = PERIOD_PRICES.get(30, 0)
if tariff_price_found:
# Тарифный режим: серверы и трафик включены в цену.
# Порядок: база + устройства → скидка на полную сумму (как в calculate_renewal_price).
from app.utils.promo_offer import get_user_active_promo_discount_percent
original_price = base_cost_original
tariff_device_limit = tariff.device_limit if tariff.device_limit is not None else 0
device_limit = subscription.device_limit if subscription.device_limit is not None else tariff_device_limit
extra_devices = max(0, device_limit - tariff_device_limit)
device_price_per_unit = (
tariff.device_price_kopeks
if tariff and tariff.device_price_kopeks is not None
else settings.PRICE_PER_DEVICE
)
devices_price = extra_devices * device_price_per_unit
original_price += devices_price
# Скидка промогруппы на полную сумму (база + устройства)
period_discount_percent = 0
if owner:
try:
period_discount_percent = owner.get_promo_discount('period', 30)
except AttributeError:
pass
discount_total = original_price * period_discount_percent // 100
total_cost = original_price - discount_total
# Promo-offer скидка (временная)
promo_offer_percent = get_user_active_promo_discount_percent(owner)
if promo_offer_percent > 0:
promo_offer_discount = total_cost * promo_offer_percent // 100
total_cost = total_cost - promo_offer_discount
else:
# Классический режим: серверы + трафик + устройства считаются отдельно
period_discount_percent = 0
if owner:
try:
period_discount_percent = owner.get_promo_discount('period', 30)
except AttributeError:
period_discount_percent = 0
base_cost, _ = apply_percentage_discount(
base_cost_original,
period_discount_percent,
)
try:
servers_cost, _ = await subscription_service.get_countries_price_by_uuids(
subscription.connected_squads,
db,
promo_group_id=promo_group_id,
)
except AttributeError:
servers_cost, _ = await get_countries_price_by_uuids_fallback(
subscription.connected_squads,
db,
promo_group_id=promo_group_id,
)
traffic_cost = settings.get_traffic_price(subscription.traffic_limit_gb)
device_limit = subscription.device_limit
if device_limit is None:
if settings.is_devices_selection_enabled():
device_limit = settings.DEFAULT_DEVICE_LIMIT
else:
forced_limit = settings.get_disabled_mode_device_limit()
if forced_limit is None:
device_limit = settings.DEFAULT_DEVICE_LIMIT
else:
device_limit = forced_limit
devices_cost = max(0, (device_limit or 0) - settings.DEFAULT_DEVICE_LIMIT) * settings.PRICE_PER_DEVICE
total_cost = base_cost + servers_cost + traffic_cost + devices_cost
logger.info('Месячная стоимость подписки', subscription_id=subscription.id, total_cost_kopeks=total_cost)
result = await pricing_engine.calculate_renewal_price(db, subscription, 30, user=owner)
total_cost = result.final_total
logger.info('Monthly subscription cost', subscription_id=subscription.id, total_cost_kopeks=total_cost)
return total_cost
except Exception as e:
logger.error('Ошибка расчета стоимости подписки', error=e)
logger.error('Error calculating subscription cost', error=e)
return 0
+129 -186
View File
@@ -9,7 +9,7 @@ from aiogram.fsm.context import FSMContext
from aiogram.types import InaccessibleMessage, InlineKeyboardButton, InlineKeyboardMarkup
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import PERIOD_PRICES, settings
from app.config import settings
from app.database.crud.subscription import (
create_paid_subscription,
create_pending_trial_subscription,
@@ -37,6 +37,7 @@ from app.keyboards.inline import (
)
from app.localization.texts import get_texts
from app.services.admin_notification_service import AdminNotificationService
from app.services.pricing_engine import pricing_engine
from app.services.remnawave_service import RemnaWaveConfigurationError
from app.services.subscription_checkout_service import (
clear_subscription_checkout_draft,
@@ -99,7 +100,6 @@ from app.handlers.simple_subscription import (
from app.states import SubscriptionStates
from app.utils.price_display import PriceInfo, format_price_text
from app.utils.pricing_utils import (
apply_percentage_discount,
calculate_months_from_days,
format_period_description,
)
@@ -343,8 +343,23 @@ async def show_subscription_info(callback: types.CallbackQuery, db_user: User, d
]
if is_daily:
# Для суточного тарифа показываем цену и прогресс-бар
daily_price = getattr(tariff, 'daily_price_kopeks', 0) / 100
# Для суточного тарифа показываем цену с учётом скидки промогруппы + promo-offer
raw_daily_kopeks = getattr(tariff, 'daily_price_kopeks', 0)
promo_group = (
db_user.get_primary_promo_group() if hasattr(db_user, 'get_primary_promo_group') else None
)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
from app.services.pricing_engine import PricingEngine
from app.utils.promo_offer import get_user_active_promo_discount_percent
daily_offer_pct = get_user_active_promo_discount_percent(db_user)
if daily_group_pct > 0 or daily_offer_pct > 0:
daily_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
raw_daily_kopeks, daily_group_pct, daily_offer_pct
)
else:
daily_kopeks = raw_daily_kopeks
daily_price = daily_kopeks / 100
tariff_info_lines.append(f'Цена: {daily_price:.2f} ₽/день')
# Прогресс-бар до следующего списания
@@ -1735,9 +1750,11 @@ async def confirm_extend_subscription(callback: types.CallbackQuery, db_user: Us
await callback.answer('⚠ У вас нет активной подписки', show_alert=True)
return
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine
from app.services.subscription_renewal_service import SubscriptionRenewalChargeError, SubscriptionRenewalService
db_user = await lock_user_for_pricing(db, db_user.id)
months_in_period = calculate_months_from_days(days)
try:
@@ -1884,7 +1901,7 @@ async def confirm_extend_subscription(callback: types.CallbackQuery, db_user: Us
await callback.answer()
async def select_period(callback: types.CallbackQuery, state: FSMContext, db_user: User):
async def select_period(callback: types.CallbackQuery, state: FSMContext, db_user: User, db: AsyncSession):
period_days = int(callback.data.split('_')[1])
texts = get_texts(db_user.language)
@@ -1894,18 +1911,23 @@ async def select_period(callback: types.CallbackQuery, state: FSMContext, db_use
await callback.answer(texts.t('PERIOD_NOT_AVAILABLE', '❌ Этот период больше недоступен'), show_alert=True)
return
# Получаем цену с защитой от KeyError
period_price = PERIOD_PRICES.get(period_days, 0)
data = await state.get_data()
data['period_days'] = period_days
data['total_price'] = period_price
if settings.is_traffic_fixed():
fixed_traffic_price = settings.get_traffic_price(settings.get_fixed_traffic_limit())
data['total_price'] += fixed_traffic_price
data['traffic_gb'] = settings.get_fixed_traffic_limit()
# Вычисляем промежуточную цену через PricingEngine (countries/devices ещё не выбраны)
pricing_result = await pricing_engine.calculate_classic_new_subscription_price(
db,
period_days,
list(data.get('countries', [])),
data.get('traffic_gb', 0) or 0,
data.get('devices', settings.DEFAULT_DEVICE_LIMIT),
user=db_user,
)
data['total_price'] = pricing_result.final_total
await state.set_data(data)
if settings.is_traffic_selectable():
@@ -1958,7 +1980,7 @@ async def select_period(callback: types.CallbackQuery, state: FSMContext, db_use
await callback.answer()
async def select_devices(callback: types.CallbackQuery, state: FSMContext, db_user: User):
async def select_devices(callback: types.CallbackQuery, state: FSMContext, db_user: User, db: AsyncSession):
texts = get_texts(db_user.language)
if not settings.is_devices_selection_enabled():
@@ -1980,27 +2002,27 @@ async def select_devices(callback: types.CallbackQuery, state: FSMContext, db_us
data = await state.get_data()
# Получаем цену периода с защитой от KeyError
period_days = data.get('period_days')
if not period_days or period_days not in PERIOD_PRICES:
if not period_days:
await callback.answer(
texts.t('PERIOD_NOT_AVAILABLE', '❌ Период больше недоступен, начните заново'), show_alert=True
)
return
base_price = PERIOD_PRICES.get(period_days, 0) + settings.get_traffic_price(data.get('traffic_gb', 0))
countries = await _get_available_countries(db_user.promo_group_id)
# Проверяем, что ключ 'countries' существует в данных перед доступом к нему
selected_countries = data.get('countries', [])
countries_price = sum(c['price_kopeks'] for c in countries if c['uuid'] in selected_countries)
devices_price = max(0, devices - settings.DEFAULT_DEVICE_LIMIT) * settings.PRICE_PER_DEVICE
previous_devices = data.get('devices', settings.DEFAULT_DEVICE_LIMIT)
data['devices'] = devices
data['total_price'] = base_price + countries_price + devices_price
# Вычисляем цену через PricingEngine с актуальными FSM-данными
pricing_result = await pricing_engine.calculate_classic_new_subscription_price(
db,
period_days,
list(data.get('countries', [])),
data.get('traffic_gb', 0) or 0,
devices,
user=db_user,
)
data['total_price'] = pricing_result.final_total
await state.set_data(data)
if devices != previous_devices:
@@ -2049,8 +2071,6 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
await save_subscription_checkout_draft(db_user.id, dict(data))
resume_callback = 'subscription_resume_checkout' if should_offer_checkout_resume(db_user, True) else None
countries = await _get_available_countries(db_user.promo_group_id)
period_days = data.get('period_days')
if period_days is None:
await callback.message.edit_text(
@@ -2059,62 +2079,8 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
)
await callback.answer()
return
months_in_period = data.get('months_in_period', calculate_months_from_days(period_days))
# Всегда пересчитываем base_price из PERIOD_PRICES для безопасности
# (не доверяем кэшированным значениям из FSM данных)
base_price_original = PERIOD_PRICES.get(period_days, 0)
base_discount_percent = db_user.get_promo_discount(
'period',
period_days,
)
base_price, base_discount_total = apply_percentage_discount(
base_price_original,
base_discount_percent,
)
server_prices = data.get('server_prices_for_period', [])
if not server_prices:
countries_price_per_month = 0
per_month_prices: list[int] = []
for country in countries:
# Проверяем, что ключ 'countries' существует в данных перед доступом к нему
selected_countries = data.get('countries', [])
if country['uuid'] in selected_countries:
server_price_per_month = country['price_kopeks']
countries_price_per_month += server_price_per_month
per_month_prices.append(server_price_per_month)
servers_discount_percent = db_user.get_promo_discount(
'servers',
period_days,
)
total_servers_price = 0
total_servers_discount = 0
discounted_servers_price_per_month = 0
server_prices = []
for server_price_per_month in per_month_prices:
discounted_per_month, discount_per_month = apply_percentage_discount(
server_price_per_month,
servers_discount_percent,
)
total_price_for_server = discounted_per_month * months_in_period
total_discount_for_server = discount_per_month * months_in_period
discounted_servers_price_per_month += discounted_per_month
total_servers_price += total_price_for_server
total_servers_discount += total_discount_for_server
server_prices.append(total_price_for_server)
total_countries_price = total_servers_price
else:
total_countries_price = data.get('total_servers_price', sum(server_prices))
countries_price_per_month = data.get('servers_price_per_month', 0)
discounted_servers_price_per_month = data.get('servers_discounted_price_per_month', countries_price_per_month)
total_servers_discount = data.get('servers_discount_total', 0)
servers_discount_percent = data.get('servers_discount_percent', 0)
# --- Resolve device limit (needed for PricingEngine and subscription creation) ---
devices_selection_enabled = settings.is_devices_selection_enabled()
forced_disabled_limit: int | None = None
if devices_selection_enabled:
@@ -2126,95 +2092,42 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
else:
devices_selected = forced_disabled_limit
additional_devices = max(0, devices_selected - settings.DEFAULT_DEVICE_LIMIT)
devices_price_per_month = data.get('devices_price_per_month', additional_devices * settings.PRICE_PER_DEVICE)
devices_discount_percent = 0
discounted_devices_price_per_month = 0
devices_discount_total = 0
total_devices_price = 0
if devices_selection_enabled and additional_devices > 0:
if 'devices_discount_percent' in data:
devices_discount_percent = data.get('devices_discount_percent', 0)
discounted_devices_price_per_month = data.get('devices_discounted_price_per_month', devices_price_per_month)
devices_discount_total = data.get('devices_discount_total', 0)
total_devices_price = data.get('total_devices_price', discounted_devices_price_per_month * months_in_period)
else:
devices_discount_percent = db_user.get_promo_discount(
'devices',
period_days,
)
discounted_devices_price_per_month, discount_per_month = apply_percentage_discount(
devices_price_per_month,
devices_discount_percent,
)
devices_discount_total = discount_per_month * months_in_period
total_devices_price = discounted_devices_price_per_month * months_in_period
# --- Resolve traffic ---
if settings.is_traffic_fixed():
final_traffic_gb = settings.get_fixed_traffic_limit()
traffic_price_per_month = data.get('traffic_price_per_month', settings.get_traffic_price(final_traffic_gb))
else:
final_traffic_gb = data.get('final_traffic_gb', data.get('traffic_gb'))
traffic_gb = data.get('traffic_gb')
if traffic_gb is not None:
traffic_price_per_month = data.get('traffic_price_per_month', settings.get_traffic_price(traffic_gb))
else:
traffic_price_per_month = data.get('traffic_price_per_month', 0)
final_traffic_gb = data.get('final_traffic_gb', data.get('traffic_gb', 0))
if 'traffic_discount_percent' in data:
traffic_discount_percent = data.get('traffic_discount_percent', 0)
discounted_traffic_price_per_month = data.get('traffic_discounted_price_per_month', traffic_price_per_month)
traffic_discount_total = data.get('traffic_discount_total', 0)
total_traffic_price = data.get('total_traffic_price', discounted_traffic_price_per_month * months_in_period)
else:
traffic_discount_percent = db_user.get_promo_discount(
'traffic',
period_days,
)
discounted_traffic_price_per_month, discount_per_month = apply_percentage_discount(
traffic_price_per_month,
traffic_discount_percent,
)
traffic_discount_total = discount_per_month * months_in_period
total_traffic_price = discounted_traffic_price_per_month * months_in_period
total_servers_price = data.get('total_servers_price', total_countries_price)
# --- Resolve connected squads ---
connected_squads = list(data.get('countries', []))
cached_total_price = data.get('total_price', 0)
cached_promo_discount_value = data.get('promo_offer_discount_value', 0)
# Всегда пересчитываем monthly_additions из компонентов для безопасности
discounted_monthly_additions = (
discounted_traffic_price_per_month + discounted_servers_price_per_month + discounted_devices_price_per_month
# Lock user BEFORE promo-offer read to prevent TOCTOU
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
# --- Delegate pricing to PricingEngine ---
from app.services.pricing_engine import PricingEngine, pricing_engine
pricing_result = await pricing_engine.calculate_classic_new_subscription_price(
db,
period_days,
connected_squads,
final_traffic_gb,
devices_selected,
user=db_user,
)
details = PricingEngine.classic_pricing_to_purchase_details(pricing_result)
# Вычисляем ожидаемую цену до промо-скидки из компонентов
calculated_total_before_promo = base_price + (discounted_monthly_additions * months_in_period)
final_price = pricing_result.final_total
server_prices = details['servers_individual_prices']
months_in_period = details['months_in_period']
promo_offer_discount_value = pricing_result.promo_offer_discount
promo_offer_discount_percent = pricing_result.breakdown.get('offer_discount_pct', 0)
# Получаем сохраненную цену до промо-скидки или используем вычисленную
validation_total_price = data.get('total_price_before_promo_offer')
if validation_total_price is None and cached_promo_discount_value > 0:
validation_total_price = cached_total_price + cached_promo_discount_value
if validation_total_price is None:
validation_total_price = cached_total_price
current_promo_offer_percent = _get_promo_offer_discount_percent(db_user)
if current_promo_offer_percent > 0:
final_price, promo_offer_discount_value = apply_percentage_discount(
calculated_total_before_promo,
current_promo_offer_percent,
)
promo_offer_discount_percent = current_promo_offer_percent
else:
final_price = calculated_total_before_promo
promo_offer_discount_value = 0
promo_offer_discount_percent = 0
# Валидация: проверяем что cached_total_price соответствует ожидаемой финальной цене
# Блокируем только если цена ВЫРОСЛА (пользователь переплатит).
# Если цена снизилась (промо-скидка активировалась) — разрешаем покупку по новой цене.
# --- Price validation: block if price increased significantly vs cached FSM price ---
price_difference = final_price - cached_total_price
if price_difference > 0:
max_allowed_increase = max(500, int(final_price * 0.05)) # 5% или минимум 5₽
@@ -2244,36 +2157,50 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
final_price=final_price / 100,
)
# Используем пересчитанную цену
validation_total_price = calculated_total_before_promo
# --- Logging ---
base_price_original = details['base_price_original']
base_price = details['base_price']
base_discount_total = details['base_discount_total']
base_discount_percent = details['base_discount_percent']
logger.info('Расчет покупки подписки на дней ( мес)', data=data['period_days'], months_in_period=months_in_period)
base_log = f' Период: {base_price_original / 100}'
if base_discount_total and base_discount_total > 0:
base_log += f'{base_price / 100}₽ (скидка {base_discount_percent}%: -{base_discount_total / 100}₽)'
logger.info(base_log)
if total_traffic_price > 0:
message = f' Трафик: {traffic_price_per_month / 100}₽/мес × {months_in_period} = {total_traffic_price / 100}'
if traffic_discount_total > 0:
message += f' (скидка {traffic_discount_percent}%: -{traffic_discount_total / 100})'
logger.info(message)
if total_servers_price > 0:
message = (
f' Серверы: {countries_price_per_month / 100}₽/мес × {months_in_period} = {total_servers_price / 100}'
if details['total_traffic_price'] > 0:
traffic_msg = (
f' Трафик: {details["traffic_price_per_month"] / 100}₽/мес'
f' × {months_in_period} = {details["total_traffic_price"] / 100}'
)
if total_servers_discount > 0:
message += f' (скидка {servers_discount_percent}%: -{total_servers_discount / 100}₽)'
logger.info(message)
if total_devices_price > 0:
message = (
f' Устройства: {devices_price_per_month / 100}₽/мес × {months_in_period} = {total_devices_price / 100}'
if details['traffic_discount_total'] > 0:
traffic_msg += (
f' (скидка {details["traffic_discount_percent"]}%: -{details["traffic_discount_total"] / 100}₽)'
)
logger.info(traffic_msg)
if details['total_servers_price'] > 0:
servers_msg = (
f' Серверы: {details["servers_price_per_month"] / 100}₽/мес'
f' × {months_in_period} = {details["total_servers_price"] / 100}'
)
if devices_discount_total > 0:
message += f' (скидка {devices_discount_percent}%: -{devices_discount_total / 100}₽)'
logger.info(message)
if details['servers_discount_total'] > 0:
servers_msg += (
f' (скидка {details["servers_discount_percent"]}%: -{details["servers_discount_total"] / 100}₽)'
)
logger.info(servers_msg)
if details['total_devices_price'] > 0:
devices_msg = (
f' Устройства: {details["devices_price_per_month"] / 100}₽/мес'
f' × {months_in_period} = {details["total_devices_price"] / 100}'
)
if details['devices_discount_total'] > 0:
devices_msg += (
f' (скидка {details["devices_discount_percent"]}%: -{details["devices_discount_total"] / 100}₽)'
)
logger.info(devices_msg)
if promo_offer_discount_value > 0:
logger.info(
'🎯 Промо-предложение: -₽ (%)',
'Промо-предложение: -₽ (%)',
promo_offer_discount_value=promo_offer_discount_value / 100,
promo_offer_discount_percent=promo_offer_discount_percent,
)
@@ -2521,6 +2448,7 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
subscription,
reset_traffic=True,
reset_reason='покупка подписки',
sync_squads=True,
)
else:
remnawave_user = await subscription_service.create_remnawave_user(
@@ -2953,7 +2881,16 @@ async def handle_toggle_daily_subscription_pause(callback: types.CallbackQuery,
# При возобновлении проверяем баланс
if needs_resume:
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import PricingEngine
db_user = await lock_user_for_pricing(db, db_user.id)
promo_group = PricingEngine.resolve_promo_group(db_user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
if daily_price > 0 and db_user.balance_kopeks < daily_price:
await callback.answer(
texts.t(
@@ -2966,7 +2903,6 @@ async def handle_toggle_daily_subscription_pause(callback: types.CallbackQuery,
if needs_resume:
# Списываем суточную оплату ДО активации (чтобы не было бесплатного дня)
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
if daily_price > 0 and is_inactive:
from app.database.crud.user import subtract_user_balance
@@ -4147,13 +4083,14 @@ async def _extend_existing_subscription(
):
"""Продлевает существующую подписку."""
from app.database.crud.transaction import create_transaction
from app.database.crud.user import subtract_user_balance
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
from app.database.models import TransactionType
from app.services.subscription_service import SubscriptionService
db_user = await lock_user_for_pricing(db, db_user.id)
texts = get_texts(db_user.language)
# Рассчитываем цену подписки
# Рассчитываем цену подписки (group discounts per-category)
subscription_params = {
'period_days': period_days,
'device_limit': device_limit,
@@ -4166,6 +4103,12 @@ async def _extend_existing_subscription(
user=db_user,
resolved_squad_uuid=squad_uuid,
)
# PricingEngine already applies promo-offer discount inside calculate_classic_new_subscription_price.
# Only determine whether to consume the offer (zero it out after use).
from app.utils.promo_offer import get_user_active_promo_discount_percent
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
logger.warning(
'SIMPLE_SUBSCRIPTION_EXTEND_PRICE | user= | total= | base= | traffic= | devices= | servers= | discount= | device_limit',
db_user_id=db_user.id,
@@ -4212,7 +4155,7 @@ async def _extend_existing_subscription(
'device_limit': device_limit,
'traffic_limit_gb': traffic_limit_gb,
'squad_uuid': squad_uuid,
'consume_promo_offer': False,
'consume_promo_offer': consume_promo,
}
await user_cart_service.save_user_cart(db_user.id, cart_data)
@@ -4233,7 +4176,7 @@ async def _extend_existing_subscription(
db_user,
price_kopeks,
f'Продление подписки на {period_days} дней',
consume_promo_offer=False, # Простая покупка не использует промо-скидки
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
+354 -190
View File
@@ -79,9 +79,14 @@ def format_tariffs_list_text(
discount_icon = ''
if is_daily:
# Для суточных тарифов показываем цену за день
# Для суточных тарифов показываем цену за день с учётом скидки промогруппы
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
price_text = f'🔄 {format_price_kopeks(daily_price, compact=True)}/день'
if db_user:
group_pct, offer_pct, daily_discount = _get_user_period_discount(db_user, 1)
if daily_discount > 0:
daily_price = _apply_promo_discount(daily_price, group_pct, offer_pct)
discount_icon = '🔥'
price_text = f'🔄 {format_price_kopeks(daily_price, compact=True)}/день{discount_icon}'
else:
# Для периодных тарифов показываем минимальную цену
prices = tariff.period_prices or {}
@@ -394,21 +399,42 @@ def _calculate_custom_tariff_price(
return period_price, traffic_price, total_price
def format_custom_tariff_preview(
async def format_custom_tariff_preview(
tariff: Tariff,
days: int,
traffic_gb: int,
user_balance: int,
db_user: User | None = None,
discount_percent: int = 0,
group_pct: int = 0,
offer_pct: int = 0,
) -> str:
"""Форматирует предпросмотр покупки с кастомными параметрами."""
period_price, traffic_price, total_price = _calculate_custom_tariff_price(tariff, days, traffic_gb)
"""Форматирует предпросмотр покупки с кастомными параметрами.
# Применяем скидку
if discount_percent > 0:
total_price = _apply_promo_discount(total_price, group_pct, offer_pct)
Uses PricingEngine when db_user is provided for accurate per-category discounts
(period, traffic addon). Falls back to manual calculation otherwise.
"""
if db_user is not None:
# Use PricingEngine — single source of truth for all discounts
from app.services.pricing_engine import pricing_engine
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
days,
device_limit=tariff.device_limit,
custom_traffic_gb=traffic_gb if tariff.can_purchase_custom_traffic() else None,
user=db_user,
)
period_price = result.base_price
traffic_price = result.traffic_price
total_price = result.final_total
has_discount = result.promo_group_discount > 0 or result.promo_offer_discount > 0
else:
# Fallback: raw prices without discounts
period_price, traffic_price, total_price = _calculate_custom_tariff_price(tariff, days, traffic_gb)
has_discount = discount_percent > 0
if has_discount:
total_price = _apply_promo_discount(total_price, group_pct, offer_pct)
traffic_display = f'{traffic_gb} ГБ' if traffic_gb > 0 else format_traffic(tariff.traffic_limit_gb)
@@ -433,7 +459,7 @@ def format_custom_tariff_preview(
text += f'📱 Устройств: {tariff.device_limit}\n'
if discount_percent > 0:
if has_discount:
text += f'\n🎁 <b>Скидка: {discount_percent}%</b>\n'
text += f"""
@@ -477,7 +503,9 @@ async def show_tariffs_list(
return
# Проверяем есть ли у пользователя скидки по периодам
promo_group = getattr(db_user, 'promo_group', None)
promo_group = db_user.get_primary_promo_group() if hasattr(db_user, 'get_primary_promo_group') else None
if promo_group is None:
promo_group = getattr(db_user, 'promo_group', None)
has_period_discounts = False
if promo_group:
period_discounts = getattr(promo_group, 'period_discounts', None)
@@ -514,7 +542,12 @@ async def select_tariff(
if is_daily:
# Для суточного тарифа показываем подтверждение без выбора периода
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
group_pct, offer_pct, daily_discount = _get_user_period_discount(db_user, 1)
daily_price = (
_apply_promo_discount(raw_daily_price, group_pct, offer_pct) if daily_discount > 0 else raw_daily_price
)
discount_text = f'\n💎 Скидка: {daily_discount}%' if daily_discount > 0 else ''
user_balance = db_user.balance_kopeks or 0
traffic = format_traffic(tariff.traffic_limit_gb)
@@ -525,7 +558,8 @@ async def select_tariff(
f'📊 Трафик: {traffic}\n'
f'📱 Устройств: {tariff.device_limit}\n'
f'🔄 Тип: <b>Суточный</b>\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}\n\n'
f'ℹ️ Средства будут списываться автоматически раз в сутки.\n'
f'Вы можете приостановить подписку в любой момент.',
@@ -557,7 +591,8 @@ async def select_tariff(
f'❌ <b>Недостаточно средств</b>\n\n'
f'📦 Тариф: <b>{tariff.name}</b>\n'
f'🔄 Тип: Суточный\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день\n\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}\n'
f'⚠️ Не хватает: <b>{format_price_kopeks(missing)}</b>\n\n'
f'🛒 <i>Корзина сохранена! После пополнения баланса подписка будет оформлена автоматически.</i>',
@@ -588,14 +623,13 @@ async def select_tariff(
period_offer_pct=offer_pct,
)
preview_text = format_custom_tariff_preview(
preview_text = await format_custom_tariff_preview(
tariff=tariff,
days=initial_days,
traffic_gb=initial_traffic,
user_balance=user_balance,
db_user=db_user,
discount_percent=discount_percent,
group_pct=group_pct,
offer_pct=offer_pct,
)
await callback.message.edit_text(
@@ -672,14 +706,13 @@ async def handle_custom_days_change(
user_balance = db_user.balance_kopeks or 0
preview_text = format_custom_tariff_preview(
preview_text = await format_custom_tariff_preview(
tariff=tariff,
days=new_days,
traffic_gb=current_traffic,
user_balance=user_balance,
db_user=db_user,
discount_percent=discount_percent,
group_pct=group_pct,
offer_pct=offer_pct,
)
await callback.message.edit_text(
@@ -722,8 +755,6 @@ async def handle_custom_traffic_change(
current_days = state_data.get('custom_days', tariff.min_days)
current_traffic = state_data.get('custom_traffic_gb', tariff.min_traffic_gb)
discount_percent = state_data.get('period_discount_percent', 0)
group_pct = state_data.get('period_group_pct', 0)
offer_pct = state_data.get('period_offer_pct', 0)
# Применяем изменение
new_traffic = current_traffic + delta
@@ -733,14 +764,13 @@ async def handle_custom_traffic_change(
user_balance = db_user.balance_kopeks or 0
preview_text = format_custom_tariff_preview(
preview_text = await format_custom_tariff_preview(
tariff=tariff,
days=current_days,
traffic_gb=new_traffic,
user_balance=user_balance,
db_user=db_user,
discount_percent=discount_percent,
group_pct=group_pct,
offer_pct=offer_pct,
)
await callback.message.edit_text(
@@ -777,28 +807,33 @@ async def handle_custom_confirm(
await callback.answer('Тариф недоступен', show_alert=True)
return
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
state_data = await state.get_data()
custom_days = state_data.get('custom_days', tariff.min_days)
custom_traffic = state_data.get('custom_traffic_gb', tariff.min_traffic_gb)
discount_percent = state_data.get('period_discount_percent', 0)
group_pct = state_data.get('period_group_pct', 0)
offer_pct = state_data.get('period_offer_pct', 0)
# Рассчитываем цену (используем общую функцию)
period_price, traffic_price, total_price = _calculate_custom_tariff_price(tariff, custom_days, custom_traffic)
# Calculate price via PricingEngine (single source of truth for all discounts)
from app.services.pricing_engine import pricing_engine
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
custom_days,
device_limit=tariff.device_limit,
custom_traffic_gb=custom_traffic if tariff.can_purchase_custom_traffic() else None,
user=db_user,
)
total_price = result.final_total
# Проверяем, что цена за период валидна
if period_price == 0 and not tariff.can_purchase_custom_days():
# Период не найден в period_prices - ошибка
if result.base_price == 0 and not tariff.can_purchase_custom_days():
await callback.answer('Выбранный период недоступен для этого тарифа', show_alert=True)
return
# Применяем скидку к цене периода (не к трафику)
if discount_percent > 0:
period_price = _apply_promo_discount(period_price, group_pct, offer_pct)
total_price = period_price + traffic_price
# Проверяем баланс
# Проверяем баланс (user already locked, balance is fresh)
user_balance = db_user.balance_kopeks or 0
if user_balance < total_price:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
@@ -807,7 +842,7 @@ async def handle_custom_confirm(
texts = get_texts(db_user.language)
# Save promo offer state before deduction (for restore on failure)
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
consume_promo = result.promo_offer_discount > 0
saved_promo_percent = int(getattr(db_user, 'promo_offer_discount_percent', 0) or 0) if consume_promo else 0
saved_promo_source = getattr(db_user, 'promo_offer_discount_source', None) if consume_promo else None
saved_promo_expires = getattr(db_user, 'promo_offer_discount_expires_at', None) if consume_promo else None
@@ -1014,14 +1049,13 @@ async def select_tariff_period_with_traffic(
period_offer_pct=offer_pct,
)
preview_text = format_custom_tariff_preview(
preview_text = await format_custom_tariff_preview(
tariff=tariff,
days=period,
traffic_gb=initial_traffic,
user_balance=user_balance,
db_user=db_user,
discount_percent=discount_percent,
group_pct=group_pct,
offer_pct=offer_pct,
)
await callback.message.edit_text(
@@ -1152,34 +1186,28 @@ async def confirm_tariff_purchase(
await callback.answer('Тариф недоступен', show_alert=True)
return
# Получаем цену
prices = tariff.period_prices or {}
base_price = prices.get(str(period), 0)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
# Calculate price via PricingEngine (single source of truth)
from app.services.pricing_engine import pricing_engine
# Add extra device cost if user has more devices than tariff's included limit
existing_sub = await get_subscription_by_user_id(db, db_user.id)
device_price_per_unit = (
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
)
extra_devices = 0
device_limit = None
if existing_sub and existing_sub.tariff_id == tariff.id:
extra_devices = max(0, (existing_sub.device_limit or 0) - (tariff.device_limit or 0))
devices_price = extra_devices * device_price_per_unit
device_limit = existing_sub.device_limit
# Apply discounts sequentially (matching PricingEngine): group first, then offer
subtotal = base_price + devices_price
promo_group = db_user.get_primary_promo_group()
group_discount_pct = promo_group.get_discount_percent('period', period) if promo_group else 0
if group_discount_pct > 0:
subtotal = subtotal - subtotal * group_discount_pct // 100
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=device_limit,
user=db_user,
)
final_price = result.final_total
offer_discount_pct = get_user_active_promo_discount_percent(db_user)
if offer_discount_pct > 0:
subtotal = subtotal - subtotal * offer_discount_pct // 100
final_price = max(0, subtotal)
# Проверяем баланс
# Проверяем баланс (user already locked, balance is fresh)
user_balance = db_user.balance_kopeks or 0
if user_balance < final_price:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
@@ -1188,7 +1216,7 @@ async def confirm_tariff_purchase(
texts = get_texts(db_user.language)
# Списываем баланс
consume_promo = get_user_active_promo_discount_percent(db_user) > 0
consume_promo = result.promo_offer_discount > 0
# Save promo offer state before deduction (for restore on failure)
saved_promo_percent = int(getattr(db_user, 'promo_offer_discount_percent', 0) or 0) if consume_promo else 0
saved_promo_source = getattr(db_user, 'promo_offer_discount_source', None) if consume_promo else None
@@ -1382,9 +1410,26 @@ async def confirm_daily_tariff_purchase(
await callback.answer('Некорректная цена тарифа', show_alert=True)
return
# Проверяем баланс
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
# Apply group + promo-offer discounts via PricingEngine (single source of truth)
from app.services.pricing_engine import pricing_engine
pricing_result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period_days=1,
device_limit=tariff.device_limit,
user=db_user,
)
final_daily_price = pricing_result.final_total
consume_promo = pricing_result.breakdown.get('offer_discount_pct', 0) > 0
# Проверяем баланс (user already locked, balance is fresh)
user_balance = db_user.balance_kopeks or 0
if user_balance < daily_price:
if user_balance < final_daily_price:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
@@ -1395,8 +1440,9 @@ async def confirm_daily_tariff_purchase(
success = await subtract_user_balance(
db,
db_user,
daily_price,
final_daily_price,
f'Покупка суточного тарифа {tariff.name} (первый день)',
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -1485,7 +1531,7 @@ async def confirm_daily_tariff_purchase(
await add_user_balance(
db,
db_user,
daily_price,
final_daily_price,
'Возврат: ошибка покупки суточного тарифа',
create_transaction=True,
transaction_type=TransactionType.REFUND,
@@ -1494,7 +1540,7 @@ async def confirm_daily_tariff_purchase(
logger.critical(
'CRITICAL: не удалось вернуть средства после ошибки покупки суточного тарифа',
user_id=db_user.id,
price_kopeks=daily_price,
price_kopeks=final_daily_price,
refund_error=refund_error,
)
await callback.answer('Произошла ошибка при оформлении подписки', show_alert=True)
@@ -1518,7 +1564,7 @@ async def confirm_daily_tariff_purchase(
db,
user_id=db_user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=daily_price,
amount_kopeks=final_daily_price,
description=f'Покупка суточного тарифа {tariff.name} (первый день)',
)
@@ -1532,7 +1578,7 @@ async def confirm_daily_tariff_purchase(
None,
1, # 1 день
was_trial_conversion=False,
amount_kopeks=daily_price,
amount_kopeks=final_daily_price,
purchase_type='renewal' if existing_subscription else 'first_purchase',
)
except Exception as e:
@@ -1555,7 +1601,7 @@ async def confirm_daily_tariff_purchase(
f'📊 Трафик: {traffic}\n'
f'📱 Устройств: {tariff.device_limit}\n'
f'🔄 Тип: Суточный\n'
f'💰 Списано: {format_price_kopeks(daily_price)}\n\n'
f'💰 Списано: {format_price_kopeks(final_daily_price)}\n\n'
f'ℹ️ Следующее списание через 24 часа.\n'
f'Перейдите в раздел «Подписка» для подключения.',
reply_markup=InlineKeyboardMarkup(
@@ -1591,26 +1637,39 @@ def get_tariff_extend_keyboard(
subscription_device_limit: int | None = None,
) -> InlineKeyboardMarkup:
"""Создает клавиатуру выбора периода для продления по тарифу с учетом скидок по периодам."""
from app.services.pricing_engine import PricingEngine
texts = get_texts(language)
buttons = []
promo_group = PricingEngine.resolve_promo_group(db_user) if db_user else None
prices = tariff.period_prices or {}
for period_str in sorted(prices.keys(), key=int):
period = int(period_str)
price = prices[period_str]
base_price = prices[period_str]
# Добавляем стоимость дополнительных устройств
# Стоимость дополнительных устройств
devices_cost = 0
if subscription_device_limit is not None:
price += _calc_extra_devices_cost(tariff, subscription_device_limit, period)
devices_cost = _calc_extra_devices_cost(tariff, subscription_device_limit, period)
# Получаем скидку для конкретного периода
group_pct, offer_pct, discount_percent = 0, 0, 0
if db_user:
group_pct, offer_pct, discount_percent = _get_user_period_discount(db_user, period)
# Per-category group discounts (period + devices separately, like PricingEngine)
period_pct = promo_group.get_discount_percent('period', period) if promo_group else 0
devices_pct = promo_group.get_discount_percent('devices', period) if promo_group else 0
offer_pct = get_user_active_promo_discount_percent(db_user) if db_user else 0
if discount_percent > 0:
price = _apply_promo_discount(price, group_pct, offer_pct)
price_text = f'{format_price_kopeks(price)} 🔥−{discount_percent}%'
discounted_base = PricingEngine.apply_discount(base_price, period_pct)
discounted_devices = PricingEngine.apply_discount(devices_cost, devices_pct)
subtotal = discounted_base + discounted_devices
price = PricingEngine.apply_discount(subtotal, offer_pct)
# Combined display discount
total_original = base_price + devices_cost
has_discount = price < total_original and total_original > 0
if has_discount:
combined_pct = round((1 - price / total_original) * 100)
price_text = f'{format_price_kopeks(price)} 🔥−{combined_pct}%'
else:
price_text = format_price_kopeks(price)
@@ -1662,7 +1721,9 @@ async def show_tariff_extend(
traffic = format_traffic(tariff.traffic_limit_gb)
# Проверяем есть ли у пользователя скидки по периодам
promo_group = getattr(db_user, 'promo_group', None)
promo_group = db_user.get_primary_promo_group() if hasattr(db_user, 'get_primary_promo_group') else None
if promo_group is None:
promo_group = getattr(db_user, 'promo_group', None)
has_period_discounts = False
if promo_group:
period_discounts = getattr(promo_group, 'period_discounts', None)
@@ -1716,14 +1777,21 @@ async def select_tariff_extend_period(
subscription = await get_subscription_by_user_id(db, db_user.id)
actual_device_limit = (subscription.device_limit if subscription else None) or tariff.device_limit
# Получаем скидку для выбранного периода
group_pct, offer_pct, discount_percent = _get_user_period_discount(db_user, period)
# Calculate price via PricingEngine (per-category discounts: period + devices)
from app.services.pricing_engine import pricing_engine
# Получаем цену (тариф + дополнительные устройства)
prices = tariff.period_prices or {}
base_price = prices.get(str(period), 0)
base_price += _calc_extra_devices_cost(tariff, actual_device_limit, period)
final_price = _apply_promo_discount(base_price, group_pct, offer_pct)
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=actual_device_limit,
user=db_user,
)
final_price = result.final_total
original_price = result.original_total
total_discount = result.promo_group_discount + result.promo_offer_discount
discount_percent = (
round((1 - final_price / original_price) * 100) if original_price > 0 and total_discount > 0 else 0
)
# Проверяем баланс
user_balance = db_user.balance_kopeks or 0
@@ -1733,7 +1801,7 @@ async def select_tariff_extend_period(
if user_balance >= final_price:
discount_text = ''
if discount_percent > 0:
discount_text = f'\n🎁 Скидка: {discount_percent}% (-{format_price_kopeks(base_price - final_price)})'
discount_text = f'\n🎁 Скидка: {discount_percent}% (-{format_price_kopeks(total_discount)})'
await callback.message.edit_text(
f'✅ <b>Подтверждение продления</b>\n\n'
@@ -1791,8 +1859,6 @@ async def select_tariff_extend_period(
extend_tariff_id=tariff_id,
extend_period=period,
extend_discount_percent=discount_percent,
extend_group_pct=group_pct,
extend_offer_pct=offer_pct,
)
await callback.answer()
@@ -1821,15 +1887,21 @@ async def confirm_tariff_extend(
actual_device_limit = subscription.device_limit or tariff.device_limit
data = await state.get_data()
group_pct = data.get('extend_group_pct', 0)
offer_pct = data.get('extend_offer_pct', 0)
from app.database.crud.user import lock_user_for_pricing
# Получаем цену (тариф + дополнительные устройства)
prices = tariff.period_prices or {}
base_price = prices.get(str(period), 0)
base_price += _calc_extra_devices_cost(tariff, actual_device_limit, period)
final_price = _apply_promo_discount(base_price, group_pct, offer_pct)
db_user = await lock_user_for_pricing(db, db_user.id)
# Calculate price via PricingEngine (handles per-category discounts: period + devices)
from app.services.pricing_engine import pricing_engine
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=actual_device_limit,
user=db_user,
)
final_price = result.final_total
consume_promo = result.promo_offer_discount > 0
# Проверяем баланс
user_balance = db_user.balance_kopeks or 0
@@ -1846,7 +1918,7 @@ async def confirm_tariff_extend(
db_user,
final_price,
f'Продление тарифа {tariff.name} на {period} дней',
consume_promo_offer=get_user_active_promo_discount_percent(db_user) > 0,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -1966,9 +2038,14 @@ def format_tariff_switch_list_text(
discount_icon = ''
if is_daily:
# Для суточных тарифов показываем цену за день
# Для суточных тарифов показываем цену за день с учётом скидки промогруппы
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
price_text = f'🔄 {format_price_kopeks(daily_price, compact=True)}/день'
if db_user:
group_pct, offer_pct, daily_discount = _get_user_period_discount(db_user, 1)
if daily_discount > 0:
daily_price = _apply_promo_discount(daily_price, group_pct, offer_pct)
discount_icon = '🔥'
price_text = f'🔄 {format_price_kopeks(daily_price, compact=True)}/день{discount_icon}'
else:
prices = tariff.period_prices or {}
if prices:
@@ -2124,7 +2201,9 @@ async def show_tariff_switch_list(
current_tariff_name = current_tariff.name
# Проверяем есть ли у пользователя скидки по периодам
promo_group = getattr(db_user, 'promo_group', None)
promo_group = db_user.get_primary_promo_group() if hasattr(db_user, 'get_primary_promo_group') else None
if promo_group is None:
promo_group = getattr(db_user, 'promo_group', None)
has_period_discounts = False
if promo_group:
period_discounts = getattr(promo_group, 'period_discounts', None)
@@ -2170,7 +2249,12 @@ async def select_tariff_switch(
if is_daily:
# Для суточного тарифа показываем подтверждение без выбора периода
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
group_pct, offer_pct, daily_discount = _get_user_period_discount(db_user, 1)
daily_price = (
_apply_promo_discount(raw_daily_price, group_pct, offer_pct) if daily_discount > 0 else raw_daily_price
)
discount_text = f'\n💎 Скидка: {daily_discount}%' if daily_discount > 0 else ''
user_balance = db_user.balance_kopeks or 0
# Проверяем текущую подписку на оставшиеся дни
@@ -2189,7 +2273,8 @@ async def select_tariff_switch(
f'📊 Трафик: {traffic}\n'
f'📱 Устройств: {tariff.device_limit}\n'
f'🔄 Тип: <b>Суточный</b>\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}'
f'{days_warning}\n\n'
f'ℹ️ Средства будут списываться автоматически раз в сутки.\n'
@@ -2212,7 +2297,8 @@ async def select_tariff_switch(
f'❌ <b>Недостаточно средств</b>\n\n'
f'📦 Тариф: <b>{tariff.name}</b>\n'
f'🔄 Тип: Суточный\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день\n\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}\n'
f'⚠️ Не хватает: <b>{format_price_kopeks(missing)}</b>'
f'{days_warning}',
@@ -2269,13 +2355,21 @@ async def select_tariff_switch_period(
data = await state.get_data()
current_tariff_id = data.get('current_tariff_id')
# Получаем скидку для выбранного периода
group_pct, offer_pct, discount_percent = _get_user_period_discount(db_user, period)
# Calculate price via PricingEngine (per-category discounts: period + devices for new tariff)
from app.services.pricing_engine import pricing_engine
# Получаем цену
prices = tariff.period_prices or {}
base_price = prices.get(str(period), 0)
final_price = _apply_promo_discount(base_price, group_pct, offer_pct)
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=tariff.device_limit or 0,
user=db_user,
)
final_price = result.final_total
original_price = result.original_total
total_discount = result.promo_group_discount + result.promo_offer_discount
discount_percent = (
round((1 - final_price / original_price) * 100) if original_price > 0 and total_discount > 0 else 0
)
# Проверяем баланс
user_balance = db_user.balance_kopeks or 0
@@ -2300,7 +2394,7 @@ async def select_tariff_switch_period(
if user_balance >= final_price:
discount_text = ''
if discount_percent > 0:
discount_text = f'\n🎁 Скидка: {discount_percent}% (-{format_price_kopeks(base_price - final_price)})'
discount_text = f'\n🎁 Скидка: {discount_percent}% (-{format_price_kopeks(total_discount)})'
await callback.message.edit_text(
f'✅ <b>Подтверждение переключения тарифа</b>\n\n'
@@ -2354,13 +2448,30 @@ async def confirm_tariff_switch(
await callback.answer('Тариф недоступен', show_alert=True)
return
# Получаем скидку для выбранного периода
group_pct, offer_pct, discount_percent = _get_user_period_discount(db_user, period)
from app.database.crud.user import lock_user_for_pricing
# Получаем цену
prices = tariff.period_prices or {}
base_price = prices.get(str(period), 0)
final_price = _apply_promo_discount(base_price, group_pct, offer_pct)
db_user = await lock_user_for_pricing(db, db_user.id)
# Проверяем наличие подписки (need device_limit for pricing)
subscription = await get_subscription_by_user_id(db, db_user.id)
if not subscription:
await callback.answer('У вас нет активной подписки', show_alert=True)
return
# Calculate price via PricingEngine (handles per-category discounts + extra devices)
from app.services.pricing_engine import pricing_engine
effective_device_limit = (
subscription.device_limit if subscription.tariff_id == tariff.id else (tariff.device_limit or 0)
)
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period,
device_limit=effective_device_limit,
user=db_user,
)
final_price = result.final_total
consume_promo = result.promo_offer_discount > 0
# Проверяем баланс
user_balance = db_user.balance_kopeks or 0
@@ -2368,12 +2479,6 @@ async def confirm_tariff_switch(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Проверяем наличие подписки
subscription = await get_subscription_by_user_id(db, db_user.id)
if not subscription:
await callback.answer('У вас нет активной подписки', show_alert=True)
return
texts = get_texts(db_user.language)
try:
@@ -2383,7 +2488,7 @@ async def confirm_tariff_switch(
db_user,
final_price,
f'Смена тарифа на {tariff.name} ({period} дней)',
consume_promo_offer=get_user_active_promo_discount_percent(db_user) > 0,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -2536,9 +2641,26 @@ async def confirm_daily_tariff_switch(
await callback.answer('Некорректная цена тарифа', show_alert=True)
return
# Проверяем баланс
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
# Apply group + promo-offer discounts via PricingEngine (single source of truth)
from app.services.pricing_engine import pricing_engine
pricing_result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period_days=1,
device_limit=tariff.device_limit,
user=db_user,
)
final_daily_price = pricing_result.final_total
consume_promo = pricing_result.breakdown.get('offer_discount_pct', 0) > 0
# Проверяем баланс (user already locked, balance is fresh)
user_balance = db_user.balance_kopeks or 0
if user_balance < daily_price:
if user_balance < final_daily_price:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
@@ -2555,8 +2677,9 @@ async def confirm_daily_tariff_switch(
success = await subtract_user_balance(
db,
db_user,
daily_price,
final_daily_price,
f'Смена на суточный тариф {tariff.name} (первый день)',
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -2639,7 +2762,7 @@ async def confirm_daily_tariff_switch(
db,
user_id=db_user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=daily_price,
amount_kopeks=final_daily_price,
description=f'Смена на суточный тариф {tariff.name} (первый день)',
)
@@ -2653,7 +2776,7 @@ async def confirm_daily_tariff_switch(
None,
1, # 1 день
was_trial_conversion=False,
amount_kopeks=daily_price,
amount_kopeks=final_daily_price,
purchase_type='tariff_switch',
)
except Exception as e:
@@ -2669,7 +2792,7 @@ async def confirm_daily_tariff_switch(
f'📊 Трафик: {traffic}\n'
f'📱 Устройств: {tariff.device_limit}\n'
f'🔄 Тип: Суточный\n'
f'💰 Списано: {format_price_kopeks(daily_price)}\n\n'
f'💰 Списано: {format_price_kopeks(final_daily_price)}\n\n'
f'ℹ️ Следующее списание через 24 часа.',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
@@ -2683,65 +2806,53 @@ async def confirm_daily_tariff_switch(
except Exception as e:
logger.error('Ошибка при смене на суточный тариф', error=e, exc_info=True)
await db.rollback()
# Compensating refund: balance was already committed by subtract_user_balance
try:
from app.database.crud.user import add_user_balance
await add_user_balance(
db,
db_user,
final_daily_price,
'Возврат: ошибка смены на суточный тариф',
create_transaction=True,
transaction_type=TransactionType.REFUND,
)
except Exception as refund_error:
logger.critical(
'CRITICAL: не удалось вернуть средства после ошибки смены на суточный тариф',
user_id=db_user.id,
price_kopeks=final_daily_price,
refund_error=refund_error,
)
await callback.answer('Произошла ошибка при смене тарифа', show_alert=True)
# ==================== Мгновенное переключение тарифов (без выбора периода) ====================
def _get_tariff_monthly_price(tariff: Tariff) -> int:
"""Получает месячную цену тарифа (30 дней) с fallback на пропорциональный расчёт."""
price = tariff.get_price_for_period(30)
if price is not None:
return price
# Fallback: пропорционально пересчитываем из первого доступного периода
periods = tariff.get_available_periods()
if periods:
first_period = periods[0]
first_price = tariff.get_price_for_period(first_period)
if first_price:
return int(first_price * 30 / first_period)
return 0
def _calculate_instant_switch_cost(
current_tariff: Tariff,
new_tariff: Tariff,
remaining_days: int,
db_user: User | None = None,
) -> tuple[int, bool]:
"""
Рассчитывает стоимость мгновенного переключения тарифа.
Если новый тариф дороже - доплата пропорционально оставшимся дням.
Если дешевле или равен - бесплатно.
Формула: (new_monthly - current_monthly) * remaining_days / 30
Скидка применяется к обоим тарифам одинаково.
"""Рассчитывает стоимость мгновенного переключения тарифа.
Делегирует расчёт в PricingEngine.calculate_tariff_switch_cost().
Returns:
(upgrade_cost_kopeks, is_upgrade)
"""
current_monthly = _get_tariff_monthly_price(current_tariff)
new_monthly = _get_tariff_monthly_price(new_tariff)
from app.services.pricing_engine import pricing_engine
group_pct, offer_pct, discount_percent = 0, 0, 0
if db_user:
group_pct, offer_pct, discount_percent = _get_user_period_discount(db_user, 30)
if discount_percent > 0:
current_monthly = _apply_promo_discount(current_monthly, group_pct, offer_pct)
new_monthly = _apply_promo_discount(new_monthly, group_pct, offer_pct)
price_diff = new_monthly - current_monthly
if price_diff <= 0:
return 0, False
upgrade_cost = int(price_diff * remaining_days / 30)
return upgrade_cost, True
result = pricing_engine.calculate_tariff_switch_cost(
current_tariff,
new_tariff,
remaining_days,
user=db_user,
)
return result.upgrade_cost, result.is_upgrade
def format_instant_switch_list_text(
@@ -2984,7 +3095,15 @@ async def preview_instant_switch(
# Для суточного тарифа особая логика показа
if is_new_daily:
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
# Применяем групповую скидку + promo-offer для отображения
daily_group_pct, daily_offer_pct, daily_discount = _get_user_period_discount(db_user, 1)
daily_price = (
_apply_promo_discount(raw_daily_price, daily_group_pct, daily_offer_pct)
if daily_discount > 0
else raw_daily_price
)
discount_text = f'\n💎 Скидка: {daily_discount}%' if daily_discount > 0 else ''
user_balance = db_user.balance_kopeks or 0
if user_balance >= daily_price:
@@ -2997,7 +3116,8 @@ async def preview_instant_switch(
f' • Трафик: {traffic}\n'
f' • Устройств: {new_tariff.device_limit}\n'
f' • Тип: 🔄 Суточный\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>\n\n'
f'💰 <b>Цена: {format_price_kopeks(daily_price)}/день</b>'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}'
f'{daily_warning}\n\n'
f'ℹ️ Средства будут списываться автоматически раз в сутки.',
@@ -3010,7 +3130,8 @@ async def preview_instant_switch(
f'❌ <b>Недостаточно средств</b>\n\n'
f'📦 Тариф: <b>{new_tariff.name}</b>\n'
f'🔄 Тип: Суточный\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день\n\n'
f'💰 Цена: {format_price_kopeks(daily_price)}/день'
f'{discount_text}\n\n'
f'💳 Ваш баланс: {format_price_kopeks(user_balance)}\n'
f'⚠️ Не хватает: <b>{format_price_kopeks(missing)}</b>'
f'{daily_warning}',
@@ -3099,19 +3220,37 @@ async def confirm_instant_switch(
await callback.answer('Тариф недоступен', show_alert=True)
return
# Получаем данные из состояния
data = await state.get_data()
upgrade_cost = data.get('upgrade_cost', 0)
is_upgrade = data.get('is_upgrade', False)
remaining_days = data.get('remaining_days', 0)
# Проверяем подписку
subscription = await get_subscription_by_user_id(db, db_user.id)
if not subscription:
await callback.answer('Подписка не найдена', show_alert=True)
return
# Проверяем баланс если это upgrade
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
# Recompute upgrade_cost under lock (FSM-stored value may be stale)
current_tariff = await get_tariff_by_id(db, subscription.tariff_id) if subscription.tariff_id else None
if not current_tariff:
await callback.answer('Текущий тариф не найден', show_alert=True)
return
remaining_days = max(0, (subscription.end_date - datetime.now(UTC)).days) if subscription.end_date else 0
# Use full TariffSwitchResult to access offer_discount_pct for consume_promo_offer flag
from app.services.pricing_engine import pricing_engine
switch_result = pricing_engine.calculate_tariff_switch_cost(
current_tariff,
new_tariff,
remaining_days,
user=db_user,
)
upgrade_cost = switch_result.upgrade_cost
is_upgrade = switch_result.is_upgrade
consume_promo = switch_result.offer_discount_pct > 0
# Проверяем баланс если это upgrade (use locked user's fresh balance)
user_balance = db_user.balance_kopeks or 0
if is_upgrade and user_balance < upgrade_cost:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
@@ -3121,13 +3260,14 @@ async def confirm_instant_switch(
try:
# Списываем баланс если это upgrade
# upgrade_cost includes both group + offer discounts from PricingEngine
if is_upgrade and upgrade_cost > 0:
success = await subtract_user_balance(
db,
db_user,
upgrade_cost,
f'Переключение на тариф {new_tariff.name}',
consume_promo_offer=get_user_active_promo_discount_percent(db_user) > 0,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -3176,7 +3316,15 @@ async def confirm_instant_switch(
if is_new_daily:
# Для суточного тарифа - сбрасываем на 1 день и настраиваем суточные параметры
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
# Apply group + promo-offer discounts via PricingEngine (single source of truth)
daily_pricing = await pricing_engine.calculate_tariff_purchase_price(
new_tariff,
period_days=1,
device_limit=new_tariff.device_limit,
user=db_user,
)
daily_price = daily_pricing.final_total
consume_promo_for_daily = daily_pricing.breakdown.get('offer_discount_pct', 0) > 0
# Списываем первый день если ещё не списано (upgrade_cost был 0)
if upgrade_cost == 0 and daily_price > 0:
@@ -3186,6 +3334,7 @@ async def confirm_instant_switch(
db_user,
daily_price,
f'Переключение на суточный тариф {new_tariff.name} (первый день)',
consume_promo_offer=consume_promo_for_daily,
mark_as_paid_subscription=True,
)
if not success:
@@ -3199,6 +3348,22 @@ async def confirm_instant_switch(
description=f'Переключение на суточный тариф {new_tariff.name} (первый день)',
)
# Уведомление админу о списании за первый день суточного тарифа
try:
admin_notification_service = AdminNotificationService(callback.bot)
await admin_notification_service.send_subscription_purchase_notification(
db,
db_user,
subscription,
None,
1,
was_trial_conversion=False,
amount_kopeks=daily_price,
purchase_type='tariff_switch',
)
except Exception as e:
logger.error('Ошибка отправки уведомления админу', error=e)
subscription.end_date = datetime.now(UTC) + timedelta(days=1)
subscription.is_trial = False
subscription.is_daily_paused = False
@@ -3266,7 +3431,6 @@ async def confirm_instant_switch(
# Для суточного тарифа другое сообщение об успехе
if is_new_daily:
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0)
await callback.message.edit_text(
f'🎉 <b>Тариф успешно изменён!</b>\n\n'
f'📦 Новый тариф: <b>{new_tariff.name}</b>\n'
+45 -18
View File
@@ -19,18 +19,16 @@ from app.keyboards.inline import (
get_reset_traffic_confirm_keyboard,
)
from app.localization.texts import get_texts
from app.services.pricing_engine import PricingEngine
from app.services.remnawave_service import RemnaWaveService
from app.services.subscription_service import SubscriptionService
from app.services.user_cart_service import user_cart_service
from app.states import SubscriptionStates
from app.utils.pricing_utils import (
apply_percentage_discount,
calculate_prorated_price,
)
from .common import (
_apply_addon_discount,
_get_addon_discount_percent_for_user,
_get_period_hint_from_subscription,
get_confirm_switch_traffic_keyboard,
get_traffic_switch_keyboard,
@@ -84,7 +82,7 @@ async def handle_add_traffic(callback: types.CallbackQuery, db_user: User, db: A
packages = tariff.get_traffic_topup_packages()
period_hint_days = _get_period_hint_from_subscription(subscription)
traffic_discount_percent = _get_addon_discount_percent_for_user(
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
period_hint_days,
@@ -136,7 +134,7 @@ async def handle_add_traffic(callback: types.CallbackQuery, db_user: User, db: A
current_traffic = subscription.traffic_limit_gb
period_hint_days = _get_period_hint_from_subscription(subscription)
traffic_discount_percent = _get_addon_discount_percent_for_user(
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
period_hint_days,
@@ -261,6 +259,10 @@ async def confirm_reset_traffic(callback: types.CallbackQuery, db_user: User, db
await callback.answer('⚠️ В текущем режиме трафик фиксированный', show_alert=True)
return
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
texts = get_texts(db_user.language)
subscription = db_user.subscription
@@ -471,16 +473,18 @@ async def add_traffic(callback: types.CallbackQuery, db_user: User, db: AsyncSes
await callback.answer('⚠️ Цена для этого пакета не настроена', show_alert=True)
return
# Lock user BEFORE price computation to prevent TOCTOU on group discount
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
subscription = db_user.subscription
period_hint_days = _get_period_hint_from_subscription(subscription)
discount_result = _apply_addon_discount(
db_user,
'traffic',
discounted_per_month, discount_per_month, traffic_discount_pct = PricingEngine.calculate_traffic_discount(
base_price,
db_user,
period_hint_days,
)
discounted_per_month = discount_result['discounted']
discount_per_month = discount_result['discount']
charged_days = 30
# На тарифах пакеты трафика покупаются на 1 месяц (30 дней),
@@ -510,7 +514,7 @@ async def add_traffic(callback: types.CallbackQuery, db_user: User, db: AsyncSes
'traffic_gb': traffic_gb,
'price_kopeks': price,
'base_price_kopeks': discounted_per_month,
'discount_percent': discount_result['percent'],
'discount_percent': traffic_discount_pct,
'source': 'bot',
'description': f'Докупка {traffic_gb} ГБ трафика',
}
@@ -619,7 +623,7 @@ async def add_traffic(callback: types.CallbackQuery, db_user: User, db: AsyncSes
if price > 0:
success_text += f'\n💰 Списано: {texts.format_price(price)}'
if total_discount_value > 0:
success_text += f' (скидка {discount_result["percent"]}%: -{texts.format_price(total_discount_value)})'
success_text += f' (скидка {traffic_discount_pct}%: -{texts.format_price(total_discount_value)})'
await callback.message.edit_text(success_text, reply_markup=get_back_keyboard(db_user.language))
@@ -668,7 +672,7 @@ async def handle_switch_traffic(callback: types.CallbackQuery, db_user: User, db
base_traffic = current_traffic - purchased_traffic
period_hint_days = _get_period_hint_from_subscription(subscription)
traffic_discount_percent = _get_addon_discount_percent_for_user(
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
period_hint_days,
@@ -722,17 +726,17 @@ async def confirm_switch_traffic(callback: types.CallbackQuery, db_user: User, d
now = datetime.now(UTC)
days_remaining = max(1, (subscription.end_date - now).days)
period_hint_days = days_remaining if days_remaining > 0 else None
traffic_discount_percent = _get_addon_discount_percent_for_user(
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
period_hint_days,
)
discounted_old_per_month, _ = apply_percentage_discount(
discounted_old_per_month = PricingEngine.apply_discount(
old_price_per_month,
traffic_discount_percent,
)
discounted_new_per_month, _ = apply_percentage_discount(
discounted_new_per_month = PricingEngine.apply_discount(
new_price_per_month,
traffic_discount_percent,
)
@@ -800,12 +804,35 @@ async def confirm_switch_traffic(callback: types.CallbackQuery, db_user: User, d
async def execute_switch_traffic(callback: types.CallbackQuery, db_user: User, db: AsyncSession):
callback_parts = callback.data.split('_')
new_traffic_gb = int(callback_parts[3])
price_difference = int(callback_parts[4])
from app.database.crud.user import lock_user_for_pricing
db_user = await lock_user_for_pricing(db, db_user.id)
texts = get_texts(db_user.language)
subscription = db_user.subscription
current_traffic = subscription.traffic_limit_gb
# Recompute price under lock (callback-baked value may be stale)
purchased_traffic = getattr(subscription, 'purchased_traffic_gb', 0) or 0
base_traffic = current_traffic - purchased_traffic
old_price_per_month = settings.get_traffic_price(base_traffic)
new_price_per_month = settings.get_traffic_price(new_traffic_gb)
days_remaining = max(1, (subscription.end_date - datetime.now(UTC)).days)
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
days_remaining,
)
discounted_old = PricingEngine.apply_discount(old_price_per_month, traffic_discount_percent)
discounted_new = PricingEngine.apply_discount(new_price_per_month, traffic_discount_percent)
price_diff_per_month = discounted_new - discounted_old
if price_diff_per_month > 0:
price_difference = int(price_diff_per_month * days_remaining / 30)
price_difference = max(100, price_difference)
else:
price_difference = 0
try:
if price_difference > 0:
success = await subtract_user_balance(
+29 -1
View File
@@ -1695,7 +1695,35 @@ def get_payment_methods_keyboard(amount_kopeks: int, language: str = DEFAULT_LAN
)
has_direct_payment_methods = True
if settings.is_kassa_ai_enabled():
if settings.is_kassa_ai_sbp_enabled():
sbp_name = settings.get_kassa_ai_sbp_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_KASSA_AI_SBP', f'📱 {sbp_name}'),
callback_data=_build_callback('kassa_ai_sbp'),
)
]
)
has_direct_payment_methods = True
if settings.is_kassa_ai_card_enabled():
card_name = settings.get_kassa_ai_card_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_KASSA_AI_CARD', f'💳 {card_name}'),
callback_data=_build_callback('kassa_ai_card'),
)
]
)
has_direct_payment_methods = True
if (
settings.is_kassa_ai_enabled()
and not settings.is_kassa_ai_sbp_enabled()
and not settings.is_kassa_ai_card_enabled()
):
kassa_ai_name = settings.get_kassa_ai_display_name()
keyboard.append(
[
+28 -6
View File
@@ -1105,9 +1105,20 @@ class BackupService:
existing = existing_user.scalar_one_or_none()
if existing:
for key, value in processed_data.items():
if key != 'id':
setattr(existing, key, value)
try:
async with db.begin_nested():
for key, value in processed_data.items():
if key != 'id':
setattr(existing, key, value)
await db.flush()
except IntegrityError:
db.expire(existing)
logger.warning(
'Конфликт уникального ключа при обновлении пользователя, пропускаем',
user_id=processed_data.get('id'),
telegram_id=processed_data.get('telegram_id'),
)
continue
else:
instance = User(**processed_data)
try:
@@ -1376,9 +1387,20 @@ class BackupService:
existing = existing_record.scalar_one_or_none()
if existing:
for key, value in processed_data.items():
if key not in pk_cols:
setattr(existing, key, value)
try:
async with db.begin_nested():
for key, value in processed_data.items():
if key not in pk_cols:
setattr(existing, key, value)
await db.flush()
except IntegrityError:
db.expire(existing)
logger.warning(
'Конфликт уникального ключа при обновлении записи, пропускаем',
table_name=table_name,
pk={col: processed_data.get(col) for col in pk_cols},
)
continue
else:
instance = model(**processed_data)
try:
+16 -2
View File
@@ -123,11 +123,25 @@ class DailySubscriptionService:
logger.warning('Тариф не найден для подписки', subscription_id=subscription.id)
return 'error'
daily_price = tariff.daily_price_kopeks
if daily_price <= 0:
raw_daily_price = tariff.daily_price_kopeks
if raw_daily_price <= 0:
logger.warning('Некорректная суточная цена для тарифа', tariff_id=tariff.id)
return 'error'
# Lock user row to prevent TOCTOU between discount read and balance charge
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply group discount to daily price (consistent with PricingEngine._calculate_switch_to_daily)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
# Проверяем баланс
if user.balance_kopeks < daily_price:
# Недостаточно средств - приостанавливаем подписку
+21 -5
View File
@@ -118,7 +118,9 @@ async def validate_and_calculate(
overrides = landing.discount_overrides or {}
tariff_override = overrides.get(str(tariff_id))
effective_discount = tariff_override if tariff_override is not None else landing.discount_percent
price_kopeks = max(1, price_kopeks - (price_kopeks * effective_discount // 100))
from app.services.pricing_engine import PricingEngine
price_kopeks = max(1, PricingEngine.apply_discount(price_kopeks, effective_discount))
return tariff, price_kopeks
@@ -283,6 +285,13 @@ async def fulfill_purchase(
)
return purchase
squads = list(tariff.allowed_squads or [])
if not squads:
from app.database.crud.server_squad import get_all_server_squads
all_servers, _ = await get_all_server_squads(db, available_only=True)
squads = [s.squad_uuid for s in all_servers if s.squad_uuid]
if existing_subscription is not None:
# Expired/inactive subscription — replace it
existing_subscription.tariff_id = tariff.id
@@ -292,7 +301,7 @@ async def fulfill_purchase(
duration_days=purchase.period_days,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
connected_squads=tariff.allowed_squads or [],
connected_squads=squads,
is_trial=False,
update_server_counters=True,
)
@@ -304,7 +313,7 @@ async def fulfill_purchase(
duration_days=purchase.period_days,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
connected_squads=tariff.allowed_squads or [],
connected_squads=squads,
tariff_id=tariff.id,
update_server_counters=True,
)
@@ -888,6 +897,13 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
existing_subscription = await get_subscription_by_user_id(db, user.id)
subscription_service = SubscriptionService()
squads = list(tariff.allowed_squads or [])
if not squads:
from app.database.crud.server_squad import get_all_server_squads
all_servers, _ = await get_all_server_squads(db, available_only=True)
squads = [s.squad_uuid for s in all_servers if s.squad_uuid]
if existing_subscription is not None:
subscription = await replace_subscription(
db,
@@ -895,7 +911,7 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
duration_days=purchase.period_days,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
connected_squads=tariff.allowed_squads or [],
connected_squads=squads,
is_trial=False,
update_server_counters=True,
commit=False,
@@ -908,7 +924,7 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
duration_days=purchase.period_days,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
connected_squads=tariff.allowed_squads or [],
connected_squads=squads,
tariff_id=tariff.id,
update_server_counters=True,
commit=False,
+6
View File
@@ -14,6 +14,12 @@ from app.config import settings
logger = structlog.get_logger(__name__)
# Sub-method to payment_system_id mapping
KASSA_AI_SUB_METHODS = {
'kassa_ai_sbp': {'payment_system_id': 44},
'kassa_ai_card': {'payment_system_id': 36},
}
# Кэш для публичного IP
_cached_public_ip: str | None = None
_ip_fetch_lock = asyncio.Lock()
+49 -51
View File
@@ -223,20 +223,20 @@ class MonitoringService:
# ВАЖНО: autopay ПЕРЕД check_expired — иначе подписки с автоплатой
# экспайрятся до того, как autopay успеет их продлить
if settings.ENABLE_AUTOPAY:
await self._process_autopayments(db)
# Рекуррентные автоплатежи: пополнение баланса с сохранённой карты
if settings.YOOKASSA_RECURRENT_ENABLED:
try:
from app.services.recurrent_payment_service import process_recurrent_payments
# Продление с баланса работает всегда, если у подписки autopay_enabled=True
await self._process_autopayments(db)
# Рекуррентные автоплатежи с карты: требуют ENABLE_AUTOPAY + YOOKASSA_RECURRENT_ENABLED
if settings.ENABLE_AUTOPAY and settings.YOOKASSA_RECURRENT_ENABLED:
try:
from app.services.recurrent_payment_service import process_recurrent_payments
await process_recurrent_payments(db=db, bot=self.bot)
except Exception as recurrent_error:
logger.error(
'Ошибка рекуррентных автоплатежей',
error=recurrent_error,
exc_info=True,
)
await process_recurrent_payments(db=db, bot=self.bot)
except Exception as recurrent_error:
logger.error(
'Ошибка рекуррентных автоплатежей',
error=recurrent_error,
exc_info=True,
)
await self._check_expired_subscriptions(db)
await self._check_expiring_subscriptions(db)
await self._check_trial_expiring_soon(db)
@@ -384,17 +384,16 @@ class MonitoringService:
description=settings.format_remnawave_user_description(
full_name=user.full_name, username=user.username, telegram_id=user.telegram_id
),
active_internal_squads=subscription.connected_squads,
)
# Не пересылаем activeInternalSquads в рутинном sync — сквады уже назначены
# при создании подписки, пересылка стейловых UUID вызывает FK violation → A039
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
if subscription.tariff and subscription.tariff.external_squad_uuid:
update_kwargs['external_squad_uuid'] = subscription.tariff.external_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
# Внешний сквад НЕ пересылаем в рутинном sync — стейловый UUID
# вызывает FK violation → A039. Назначается при создании подписки.
updated_user = await api.update_user(**update_kwargs)
@@ -1053,8 +1052,11 @@ class MonitoringService:
autopay_period = 30
try:
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine
user = await lock_user_for_pricing(db, user.id)
pricing = await pricing_engine.calculate_renewal_price(
db,
subscription,
@@ -1301,43 +1303,39 @@ class MonitoringService:
texts = get_texts(user.language)
days_text = format_days_declension(days, user.language)
if settings.ENABLE_AUTOPAY:
if subscription.autopay_enabled and has_saved_card:
autopay_status = texts.t(
'AUTOPAY_STATUS_CARD_ACTIVE',
'✅ Включен — будет автоматическое списание с карты',
)
action_text = texts.t(
'AUTOPAY_ACTION_CHECK_BALANCE',
'💰 Убедитесь, что на балансе достаточно средств: {balance}',
).format(balance=texts.format_price(user.balance_kopeks))
elif subscription.autopay_enabled:
autopay_status = texts.t(
'AUTOPAY_STATUS_NO_CARD',
'✅ Включен — подписка продлится автоматически',
)
action_text = texts.t(
'AUTOPAY_ACTION_CHECK_BALANCE',
'💰 Убедитесь, что на балансе достаточно средств: {balance}',
).format(balance=texts.format_price(user.balance_kopeks))
else:
autopay_status = texts.t(
'AUTOPAY_STATUS_OFF',
'❌ Отключен — не забудьте продлить вручную!',
)
action_text = texts.t(
'AUTOPAY_ACTION_ENABLE',
'💡 Включите автоплатеж или продлите подписку вручную',
)
if subscription.autopay_enabled and has_saved_card:
autopay_status = texts.t(
'AUTOPAY_STATUS_CARD_ACTIVE',
'✅ Включен — будет автоматическое списание с карты',
)
action_text = texts.t(
'AUTOPAY_ACTION_CHECK_BALANCE',
'💰 Убедитесь, что на балансе достаточно средств: {balance}',
).format(balance=texts.format_price(user.balance_kopeks))
elif subscription.autopay_enabled:
autopay_status = texts.t(
'AUTOPAY_STATUS_NO_CARD',
'✅ Включен — подписка продлится автоматически',
)
action_text = texts.t(
'AUTOPAY_ACTION_CHECK_BALANCE',
'💰 Убедитесь, что на балансе достаточно средств: {balance}',
).format(balance=texts.format_price(user.balance_kopeks))
else:
autopay_status = texts.t(
'AUTOPAY_STATUS_OFF',
'❌ Отключен — не забудьте продлить вручную!',
)
action_text = texts.t(
'AUTOPAY_ACTION_RENEW',
'💡 Продлите подписку вручную',
)
if settings.ENABLE_AUTOPAY:
action_text = texts.t(
'AUTOPAY_ACTION_ENABLE',
'💡 Включите автоплатеж или продлите подписку вручную',
)
else:
action_text = texts.t(
'AUTOPAY_ACTION_RENEW',
'💡 Продлите подписку вручную',
)
end_date = format_local_datetime(subscription.end_date, '%d.%m.%Y %H:%M')
message = texts.t(
+7 -24
View File
@@ -939,8 +939,7 @@ class PartnerStatsService:
registrations_dict = {str(row.date): int(row.count) for row in registrations_by_day.all()}
# --- Daily revenue (DAILY_STATS_DAYS days) ---
# Revenue = real deposits (positive) + abs(subscription_payments) (stored negative)
# Exclude promo/bonus deposits (payment_method IS NULL) from revenue
# Revenue = real deposits only (exclude bonus/promo balance spending on subscriptions)
revenue_amount_expr = func.coalesce(
func.sum(
case(
@@ -951,10 +950,6 @@ class PartnerStatsService:
),
Transaction.amount_kopeks,
),
(
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
func.abs(Transaction.amount_kopeks),
),
else_=0,
)
),
@@ -971,12 +966,8 @@ class PartnerStatsService:
Transaction.user_id.in_(campaign_user_ids_sq),
Transaction.is_completed.is_(True),
Transaction.created_at >= start_date,
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
),
Transaction.type == TransactionType.DEPOSIT.value,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
)
)
.group_by(func.date(Transaction.created_at))
@@ -1027,12 +1018,8 @@ class PartnerStatsService:
Transaction.user_id.in_(campaign_user_ids_sq),
Transaction.is_completed.is_(True),
Transaction.created_at >= week_ago,
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
),
Transaction.type == TransactionType.DEPOSIT.value,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
)
)
)
@@ -1046,12 +1033,8 @@ class PartnerStatsService:
Transaction.is_completed.is_(True),
Transaction.created_at >= previous_start,
Transaction.created_at < week_ago,
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
),
Transaction.type == TransactionType.DEPOSIT.value,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
)
)
)
+1 -1
View File
@@ -347,7 +347,7 @@ class CloudPaymentsPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения CloudPayments', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
+106 -99
View File
@@ -325,7 +325,111 @@ async def send_cart_notification_after_topup(
exc_info=True,
)
# Try to auto-extend expired subscription (works without cart)
cart_data = await user_cart_service.get_user_cart(user.id)
# В приоритете всегда сохраненная корзина: она отражает явный выбор пользователя
# (период/тариф/сумма). Автопродление expired — только когда корзины нет.
if cart_data:
cart_total = cart_data.get('total_price', 0)
if not cart_total:
logger.warning(
'Сохраненная корзина найдена, но total_price отсутствует или некорректен',
user_id=user.id,
cart_total=cart_total,
)
return False
# Try auto-purchase first
auto_purchase_success = False
try:
auto_purchase_success = await auto_purchase_saved_cart_after_topup(db, user, bot=bot)
except Exception as auto_error:
logger.error(
'Ошибка автоматической покупки подписки для пользователя',
user_id=user.id,
auto_error=auto_error,
exc_info=True,
)
if auto_purchase_success:
return False
if not bot or not getattr(user, 'telegram_id', None):
return False
# Refresh balance from DB to account for any changes during auto-purchase attempt
refreshed_user = await get_user_by_id(db, user.id)
balance = getattr(refreshed_user or user, 'balance_kopeks', 0)
texts = get_texts(getattr(user, 'language', 'ru'))
# Build message based on whether balance is sufficient
fmt = settings.format_price
cart_total_formatted = fmt(cart_total)
if balance >= cart_total:
template = texts.get('BALANCE_TOPPED_UP_CART_SUFFICIENT', '')
message_text = template.format(
amount=fmt(amount_kopeks),
balance=fmt(balance),
cart_total=cart_total_formatted,
total_amount=cart_total_formatted,
)
else:
missing = cart_total - balance
template = texts.get('BALANCE_TOPPED_UP_CART_INSUFFICIENT', '')
message_text = template.format(
amount=fmt(amount_kopeks),
balance=fmt(balance),
cart_total=cart_total_formatted,
total_amount=cart_total_formatted,
missing=fmt(missing),
)
if not message_text:
logger.warning('Missing cart notification template', language=getattr(user, 'language', 'ru'))
return False
sent = False
try:
keyboard = types.InlineKeyboardMarkup(
inline_keyboard=[
[
types.InlineKeyboardButton(
text=texts.get('RETURN_TO_SUBSCRIPTION_CHECKOUT', '⬅️ Checkout'),
callback_data='return_to_saved_cart',
)
],
[
types.InlineKeyboardButton(
text=texts.get('MY_BALANCE_BUTTON', '💰 Balance'),
callback_data='menu_balance',
)
],
[
types.InlineKeyboardButton(
text=texts.get('MAIN_MENU_BUTTON', '🏠 Menu'),
callback_data='back_to_menu',
)
],
]
)
await bot.send_message(
chat_id=user.telegram_id,
text=message_text,
reply_markup=keyboard,
parse_mode='HTML',
)
sent = True
logger.info('Sent cart notification to user', user_id=user.id)
except Exception as send_error:
logger.error(
'Failed to send cart notification to user',
user_id=user.id,
error=send_error,
)
return sent
# Try to auto-extend expired subscription only when there is no saved cart.
try:
auto_extended = await try_auto_extend_expired_after_topup(db, user, bot=bot)
if auto_extended:
@@ -338,104 +442,7 @@ async def send_cart_notification_after_topup(
exc_info=True,
)
cart_data = await user_cart_service.get_user_cart(user.id)
if not cart_data:
return False
cart_total = cart_data.get('total_price', 0)
if not cart_total:
return False
# Try auto-purchase first
auto_purchase_success = False
try:
auto_purchase_success = await auto_purchase_saved_cart_after_topup(db, user, bot=bot)
except Exception as auto_error:
logger.error(
'Ошибка автоматической покупки подписки для пользователя',
user_id=user.id,
auto_error=auto_error,
exc_info=True,
)
if auto_purchase_success:
return False
if not bot or not getattr(user, 'telegram_id', None):
return False
# Refresh balance from DB to account for any changes during auto-purchase attempt
refreshed_user = await get_user_by_id(db, user.id)
balance = getattr(refreshed_user or user, 'balance_kopeks', 0)
texts = get_texts(getattr(user, 'language', 'ru'))
# Build message based on whether balance is sufficient
fmt = settings.format_price
cart_total_formatted = fmt(cart_total)
if balance >= cart_total:
template = texts.get('BALANCE_TOPPED_UP_CART_SUFFICIENT', '')
message_text = template.format(
amount=fmt(amount_kopeks),
balance=fmt(balance),
cart_total=cart_total_formatted,
total_amount=cart_total_formatted,
)
else:
missing = cart_total - balance
template = texts.get('BALANCE_TOPPED_UP_CART_INSUFFICIENT', '')
message_text = template.format(
amount=fmt(amount_kopeks),
balance=fmt(balance),
cart_total=cart_total_formatted,
total_amount=cart_total_formatted,
missing=fmt(missing),
)
if not message_text:
logger.warning('Missing cart notification template', language=getattr(user, 'language', 'ru'))
return False
sent = False
try:
keyboard = types.InlineKeyboardMarkup(
inline_keyboard=[
[
types.InlineKeyboardButton(
text=texts.get('RETURN_TO_SUBSCRIPTION_CHECKOUT', '⬅️ Checkout'),
callback_data='return_to_saved_cart',
)
],
[
types.InlineKeyboardButton(
text=texts.get('MY_BALANCE_BUTTON', '💰 Balance'),
callback_data='menu_balance',
)
],
[
types.InlineKeyboardButton(
text=texts.get('MAIN_MENU_BUTTON', '🏠 Menu'),
callback_data='back_to_menu',
)
],
]
)
await bot.send_message(
chat_id=user.telegram_id,
text=message_text,
reply_markup=keyboard,
parse_mode='HTML',
)
sent = True
logger.info('Sent cart notification to user', user_id=user.id)
except Exception as send_error:
logger.error(
'Failed to send cart notification to user',
user_id=user.id,
error=send_error,
)
return sent
return False
# ---------------------------------------------------------------------------
+1 -1
View File
@@ -338,7 +338,7 @@ class CryptoBotPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения CryptoBot', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -347,7 +347,7 @@ class FreekassaPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения Freekassa', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -391,7 +391,7 @@ class HeleketPaymentMixin:
except Exception as error: # pragma: no cover - defensive
logger.error('Ошибка реферального начисления Heleket', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
+8 -3
View File
@@ -28,6 +28,7 @@ class KassaAiPaymentMixin:
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
payment_system_id: int | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж KassaAI.
@@ -96,7 +97,9 @@ class KassaAiPaymentMixin:
amount=amount_rubles,
currency=currency,
email=email,
payment_system_id=settings.KASSA_AI_PAYMENT_SYSTEM_ID,
payment_system_id=payment_system_id
if payment_system_id is not None
else settings.KASSA_AI_PAYMENT_SYSTEM_ID,
)
payment_url = result.get('location')
@@ -118,7 +121,9 @@ class KassaAiPaymentMixin:
currency=currency,
description=description,
payment_url=payment_url,
payment_system_id=settings.KASSA_AI_PAYMENT_SYSTEM_ID,
payment_system_id=payment_system_id
if payment_system_id is not None
else settings.KASSA_AI_PAYMENT_SYSTEM_ID,
expires_at=expires_at,
metadata_json=metadata,
)
@@ -335,7 +340,7 @@ class KassaAiPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения KassaAI', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -322,7 +322,7 @@ class MulenPayPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения', display_name=display_name, error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -434,7 +434,7 @@ class Pal24PaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения Pal24', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -442,7 +442,7 @@ class PlategaPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения Platega', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
+25 -6
View File
@@ -42,11 +42,13 @@ class RioPayPaymentMixin:
self,
db: AsyncSession,
*,
user_id: int,
user_id: int | None,
amount_kopeks: int,
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
success_url: str | None = None,
fail_url: str | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж RioPay.
@@ -76,8 +78,11 @@ class RioPayPaymentMixin:
return None
# Получаем telegram_id пользователя для order_id
user = await get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
if user_id is not None:
user = await get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
else:
tg_id = 'guest'
# Генерируем уникальный order_id с telegram_id для удобного поиска
order_id = f'rp{tg_id}_{uuid.uuid4().hex[:6]}'
@@ -103,8 +108,8 @@ class RioPayPaymentMixin:
currency=currency,
external_id=order_id,
purpose=description,
success_url=settings.RIOPAY_SUCCESS_URL,
fail_url=settings.RIOPAY_FAIL_URL,
success_url=success_url or settings.RIOPAY_SUCCESS_URL,
fail_url=fail_url or settings.RIOPAY_FAIL_URL,
)
payment_url = result.get('paymentLink')
@@ -275,6 +280,20 @@ class RioPayPaymentMixin:
logger.info('RioPay платеж уже привязан к транзакции', order_id=payment.order_id, trigger=trigger)
return True
# --- Guest purchase flow (landing page / gift) ---
riopay_metadata = dict(getattr(payment, 'metadata_json', {}) or {})
from app.services.payment.common import try_fulfill_guest_purchase
guest_result = await try_fulfill_guest_purchase(
db,
metadata=riopay_metadata,
payment_amount_kopeks=payment.amount_kopeks,
provider_payment_id=str(riopay_order_id) if riopay_order_id else payment.order_id,
provider_name='riopay',
)
if guest_result is not None:
return True
# Получаем пользователя
user = await get_user_by_id(db, payment.user_id)
if not user:
@@ -316,7 +335,7 @@ class RioPayPaymentMixin:
UserModel.balance_kopeks: UserModel.balance_kopeks + payment.amount_kopeks,
UserModel.updated_at: datetime.now(UTC),
}
if was_first_topup:
if was_first_topup and not user.referred_by_id:
update_values[UserModel.has_made_first_topup] = True
await db.execute(update(UserModel).where(UserModel.id == user.id).values(update_values))
+9 -1
View File
@@ -260,6 +260,14 @@ class TelegramStarsMixin:
logger.error('Не удалось активировать pending подписку пользователя', user_id=user.id)
return False
# Consume promo-offer discount (invoice was created with discounted price)
try:
from app.utils.promo_offer import consume_user_promo_offer
await consume_user_promo_offer(db, user.id)
except Exception as promo_error:
logger.warning('Ошибка потребления промо-оффера при Stars оплате', user_id=user.id, error=promo_error)
try:
from app.services.subscription_service import SubscriptionService
@@ -434,7 +442,7 @@ class TelegramStarsMixin:
"❌ Описание '' не подходит для реферальной логики", description_for_referral=description_for_referral
)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
+1 -1
View File
@@ -529,7 +529,7 @@ class WataPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения WATA', error=error)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
+13 -1
View File
@@ -819,7 +819,7 @@ class YooKassaPaymentMixin:
except Exception as error:
logger.error('Ошибка обработки реферального пополнения YooKassa', error=error)
if was_first_topup and not getattr(user, 'has_made_first_topup', False):
if was_first_topup and not getattr(user, 'has_made_first_topup', False) and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
@@ -912,6 +912,18 @@ class YooKassaPaymentMixin:
if subscription:
logger.info('Подписка успешно активирована для пользователя', user_id=user.id)
# Consume promo-offer discount (invoice was created with discounted price)
try:
from app.utils.promo_offer import consume_user_promo_offer
await consume_user_promo_offer(db, user.id)
except Exception as promo_error:
logger.warning(
'Ошибка потребления промо-оффера при YooKassa оплате',
user_id=user.id,
error=promo_error,
)
# Обновляем данные подписки в RemnaWave, чтобы получить актуальные ссылки
try:
remnawave_user = await subscription_service.create_remnawave_user(db, subscription)
@@ -126,7 +126,10 @@ def _get_method_defaults() -> dict:
'is_configured': settings.is_kassa_ai_enabled(),
'default_min': settings.KASSA_AI_MIN_AMOUNT_KOPEKS,
'default_max': settings.KASSA_AI_MAX_AMOUNT_KOPEKS,
'available_sub_options': None,
'available_sub_options': [
{'id': 'sbp', 'name': 'СБП'},
{'id': 'card', 'name': 'Карта'},
],
},
'riopay': {
'default_display_name': settings.get_riopay_display_name(),
+32 -3
View File
@@ -666,23 +666,52 @@ class PaymentService(
return None
# --- KassaAI ----------------------------------------------------------
if payment_method == 'kassa_ai':
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card'):
if not settings.is_kassa_ai_enabled():
logger.warning('KassaAI is not enabled, cannot create guest payment')
return None
from app.services.kassa_ai_service import KASSA_AI_SUB_METHODS
sub = KASSA_AI_SUB_METHODS.get(payment_method)
ps_id = sub['payment_system_id'] if sub else None
result = await self.create_kassa_ai_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
payment_system_id=ps_id,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'kassa_ai')
await _patch_guest_metadata(result['local_payment_id'], payment_method)
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('order_id'),
'provider': 'kassa_ai',
'provider': payment_method,
}
return None
# --- RioPay -----------------------------------------------------------
if payment_method == 'riopay':
if not settings.is_riopay_enabled():
logger.warning('RioPay is not enabled, cannot create guest payment')
return None
result = await self.create_riopay_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
success_url=return_url,
fail_url=return_url,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'riopay')
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('riopay_order_id') or result.get('order_id'),
'provider': 'riopay',
}
return None
+83 -6
View File
@@ -27,6 +27,7 @@ from app.database.models import (
Pal24Payment,
PaymentMethod,
PlategaPayment,
RioPayPayment,
Transaction,
TransactionType,
User,
@@ -72,6 +73,7 @@ SUPPORTED_MANUAL_CHECK_METHODS: frozenset[PaymentMethod] = frozenset(
PaymentMethod.CLOUDPAYMENTS,
PaymentMethod.FREEKASSA,
PaymentMethod.KASSA_AI,
PaymentMethod.RIOPAY,
}
)
@@ -90,6 +92,7 @@ SUPPORTED_AUTO_CHECK_METHODS: frozenset[PaymentMethod] = frozenset(
# Payments are processed via webhook (wata_webhook.py).
PaymentMethod.FREEKASSA,
PaymentMethod.KASSA_AI,
PaymentMethod.RIOPAY,
}
)
@@ -115,6 +118,8 @@ def method_display_name(method: PaymentMethod) -> str:
return 'Freekassa'
if method == PaymentMethod.KASSA_AI:
return settings.get_kassa_ai_display_name()
if method == PaymentMethod.RIOPAY:
return settings.get_riopay_display_name()
if method == PaymentMethod.TELEGRAM_STARS:
return 'Telegram Stars'
return method.value
@@ -141,6 +146,8 @@ def _method_is_enabled(method: PaymentMethod) -> bool:
return settings.is_freekassa_enabled()
if method == PaymentMethod.KASSA_AI:
return settings.is_kassa_ai_enabled()
if method == PaymentMethod.RIOPAY:
return settings.is_riopay_enabled()
return False
@@ -242,12 +249,23 @@ class AutoPaymentVerificationService:
)
for record in candidates:
refreshed = await run_manual_check(
session,
record.method,
record.local_id,
self._payment_service,
)
try:
refreshed = await run_manual_check(
session,
record.method,
record.local_id,
self._payment_service,
)
except Exception as check_error:
logger.error(
'Ошибка проверки платежа, откатываем сессию',
method_display_name=method_display_name(record.method),
identifier=record.identifier,
error=check_error,
)
if session.in_transaction():
await session.rollback()
continue
if not refreshed:
logger.debug(
@@ -365,6 +383,13 @@ def _is_kassa_ai_pending(payment: KassaAiPayment) -> bool:
return status in {'pending', 'created', 'processing'}
def _is_riopay_pending(payment: RioPayPayment) -> bool:
if payment.is_paid:
return False
status = (payment.status or '').lower()
return status in {'pending'}
def _parse_cryptobot_amount_kopeks(payment: CryptoBotPayment) -> int:
payload = payment.payload or ''
match = re.search(r'_(\d+)$', payload)
@@ -682,6 +707,32 @@ async def _fetch_kassa_ai_payments(db: AsyncSession, cutoff: datetime) -> list[P
return records
async def _fetch_riopay_payments(db: AsyncSession, cutoff: datetime) -> list[PendingPayment]:
stmt = (
select(RioPayPayment)
.options(selectinload(RioPayPayment.user))
.where(RioPayPayment.created_at >= cutoff)
.order_by(desc(RioPayPayment.created_at))
)
result = await db.execute(stmt)
records: list[PendingPayment] = []
for payment in result.scalars().all():
if not _is_riopay_pending(payment):
continue
record = _build_record(
PaymentMethod.RIOPAY,
payment,
identifier=payment.order_id,
amount_kopeks=payment.amount_kopeks,
status=payment.status or '',
is_paid=bool(payment.is_paid),
expires_at=getattr(payment, 'expires_at', None),
)
if record:
records.append(record)
return records
async def _fetch_stars_transactions(db: AsyncSession, cutoff: datetime) -> list[PendingPayment]:
stmt = (
select(Transaction)
@@ -729,6 +780,7 @@ async def list_recent_pending_payments(
await _fetch_cloudpayments_payments(db, cutoff),
await _fetch_freekassa_payments(db, cutoff),
await _fetch_kassa_ai_payments(db, cutoff),
await _fetch_riopay_payments(db, cutoff),
await _fetch_stars_transactions(db, cutoff),
)
@@ -897,6 +949,21 @@ async def get_payment_record(
is_paid=bool(payment.is_paid),
)
if method == PaymentMethod.RIOPAY:
payment = await db.get(RioPayPayment, local_payment_id)
if not payment:
return None
await db.refresh(payment, attribute_names=['user'])
return _build_record(
method,
payment,
identifier=payment.order_id,
amount_kopeks=payment.amount_kopeks,
status=payment.status or '',
is_paid=bool(payment.is_paid),
expires_at=getattr(payment, 'expires_at', None),
)
if method == PaymentMethod.TELEGRAM_STARS:
transaction = await db.get(Transaction, local_payment_id)
if not transaction:
@@ -955,6 +1022,13 @@ async def run_manual_check(
elif method == PaymentMethod.KASSA_AI:
result = await payment_service.get_kassa_ai_payment_status(db, local_payment_id)
payment = result.get('payment') if result else None
elif method == PaymentMethod.RIOPAY:
riopay_payment = await db.get(RioPayPayment, local_payment_id)
if riopay_payment:
result = await payment_service.check_riopay_payment_status(db, riopay_payment.order_id)
payment = result.get('payment') if result else None
else:
payment = None
else:
logger.warning('Manual check requested for unsupported method', method=method)
return None
@@ -972,6 +1046,9 @@ async def run_manual_check(
error=error,
exc_info=True,
)
# Откатываем сессию чтобы не оставлять её в грязном состоянии
if db.in_transaction():
await db.rollback()
return None
+548 -41
View File
@@ -15,7 +15,7 @@ from app.utils.promo_offer import get_user_active_promo_discount_percent
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import Subscription, User
from app.database.models import Subscription, Tariff, User
logger = structlog.get_logger(__name__)
@@ -27,8 +27,9 @@ class TariffBreakdown:
tariff_id: int
extra_devices: int
group_discount_pct: int
group_discount_pct: dict[str, int]
offer_discount_pct: int
months_in_period: int = 1
@dataclass(frozen=True)
@@ -42,9 +43,14 @@ class ClassicBreakdown:
base_traffic_gb: int
purchased_traffic_gb: int
extra_devices: int
# NB: dict[str, int] per-category (period/servers/traffic/devices), unlike TariffBreakdown's single int
# Per-category discount percents (period/servers/traffic/devices)
group_discount_pct: dict[str, int]
offer_discount_pct: int
# Original (pre-discount) prices — used by classic_pricing_to_purchase_details()
base_price_original: int = 0
traffic_price_per_month: int = 0
servers_price_per_month: int = 0
devices_price_per_month: int = 0
@dataclass(frozen=True)
@@ -68,6 +74,30 @@ class RenewalPricing:
return self.final_total + self.promo_group_discount + self.promo_offer_discount
@dataclass(frozen=True)
class TariffSwitchResult:
"""Immutable result of a tariff switch cost calculation."""
upgrade_cost: int # kopeks — amount to charge (0 if downgrade/same)
is_upgrade: bool # True if new tariff is more expensive
raw_cost: int # kopeks — cost before discounts (for UI display)
group_discount_pct: int
offer_discount_pct: int
new_period_days: int = 0 # 0 = keep current end date, >0 = set new subscription period
@property
def discount_value(self) -> int:
"""Сумма скидки в копейках."""
return self.raw_cost - self.upgrade_cost
@property
def effective_discount_pct(self) -> int:
"""Эффективный процент скидки (стекинг group + offer)."""
if self.raw_cost <= 0:
return 0
return round(self.discount_value * 100 / self.raw_cost)
class PricingEngine:
"""Unified pricing engine for all subscription renewal calculations."""
@@ -93,6 +123,286 @@ class PricingEngine:
offer_discount_value = after_group - after_offer
return after_offer, group_discount_value, offer_discount_value
@staticmethod
def resolve_promo_group(user: User | None):
"""Resolve primary promo group: get_primary_promo_group() first, fallback to user.promo_group."""
if not user:
return None
if hasattr(user, 'get_primary_promo_group'):
pg = user.get_primary_promo_group()
if pg is not None:
return pg
return getattr(user, 'promo_group', None)
@staticmethod
def get_addon_discount_percent(
user: User | None,
category: str,
period_days_hint: int | None = None,
*,
promo_group: PromoGroup | None = None,
) -> int:
"""Return addon discount percent for a given category.
Uses promo_group.get_discount_percent() which handles is_default fallback.
Checks apply_discounts_to_addons flag. Returns 0 if no discount.
If promo_group is provided explicitly, it takes precedence over
resolving from user (useful when caller already resolved the group).
"""
if promo_group is None:
if not user:
return 0
promo_group = PricingEngine.resolve_promo_group(user)
if not promo_group:
return 0
if not getattr(promo_group, 'apply_discounts_to_addons', True):
return 0
if hasattr(promo_group, 'get_discount_percent'):
return promo_group.get_discount_percent(category, period_days_hint)
# Fallback for promo groups without get_discount_percent
mapping = {
'traffic': 'traffic_discount_percent',
'servers': 'server_discount_percent',
'devices': 'device_discount_percent',
}
attr = mapping.get(category)
if attr:
return max(0, min(100, int(getattr(promo_group, attr, 0) or 0)))
return 0
@staticmethod
def calculate_traffic_discount(
base_price: int,
user: User | None,
period_days_hint: int | None = None,
) -> tuple[int, int, int]:
"""Apply traffic addon discount from user's promo group.
Checks apply_discounts_to_addons flag. Uses integer arithmetic.
Uses get_discount_percent() for correct is_default fallback.
Returns: (final_price, discount_value, discount_percent).
"""
if not user or base_price <= 0:
return base_price, 0, 0
pct = PricingEngine.get_addon_discount_percent(user, 'traffic', period_days_hint)
if pct <= 0:
return base_price, 0, 0
final = PricingEngine.apply_discount(base_price, pct)
return final, base_price - final, pct
# ------------------------------------------------------------------
# Tariff switch
# ------------------------------------------------------------------
@staticmethod
def get_tariff_daily_rate_fraction(tariff: Tariff, target_days: int) -> tuple[int, int]:
"""Дневная ставка тарифа как (price, period_days) для целочисленных вычислений.
Возвращает числитель и знаменатель дроби price/period_days,
чтобы избежать float-ошибок в финансовых расчётах.
"""
periods = tariff.get_available_periods()
if not periods:
return 0, 1
best_period = min(periods, key=lambda p: abs(p - target_days))
price = tariff.get_price_for_period(best_period)
if not price or best_period <= 0:
return 0, 1
return price, best_period
def calculate_tariff_switch_cost(
self,
current_tariff: Tariff,
new_tariff: Tariff,
remaining_days: int,
*,
user: User | None = None,
) -> TariffSwitchResult:
"""Рассчитывает стоимость переключения тарифа.
Автоматически определяет тип переключения:
- periodicdaily: оплата первого дня (daily_price_kopeks)
- dailyperiodic: оплата кратчайшего периода нового тарифа
- periodicperiodic: пропорциональная разница дневных ставок × remaining_days
Для всех типов переключений скидки (group + offer) применяются stacked.
"""
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
new_is_daily = getattr(new_tariff, 'is_daily', False)
# Daily tariff edge cases
if not current_is_daily and new_is_daily:
return self._calculate_switch_to_daily(new_tariff, remaining_days, user=user)
if current_is_daily and not new_is_daily:
return self._calculate_switch_from_daily(new_tariff, remaining_days, user=user)
if current_is_daily and new_is_daily:
# Daily → Daily: бесплатное переключение, cron начислит новую цену завтра
return TariffSwitchResult(
upgrade_cost=0,
is_upgrade=False,
raw_cost=0,
group_discount_pct=0,
offer_discount_pct=0,
new_period_days=1,
)
# --- Periodic → Periodic ---
# Early return: нечего считать при нулевом остатке
if remaining_days <= 0:
return TariffSwitchResult(
upgrade_cost=0,
is_upgrade=False,
raw_cost=0,
group_discount_pct=0,
offer_discount_pct=0,
new_period_days=0,
)
# Целочисленная арифметика (без float round-trip):
# raw_cost = (new_p/new_d - cur_p/cur_d) * remaining
# = (new_p * cur_d - cur_p * new_d) * remaining / (new_d * cur_d)
# Floor division (//) округляет дробные копейки вниз — в пользу пользователя.
cur_price, cur_period = self.get_tariff_daily_rate_fraction(current_tariff, remaining_days)
new_price, new_period = self.get_tariff_daily_rate_fraction(new_tariff, remaining_days)
numerator = (new_price * cur_period - cur_price * new_period) * remaining_days
denominator = new_period * cur_period
raw_cost = max(0, numerator // denominator)
if numerator <= 0:
return TariffSwitchResult(
upgrade_cost=0,
is_upgrade=False,
raw_cost=0,
group_discount_pct=0,
offer_discount_pct=0,
new_period_days=0,
)
# Resolve discounts via resolve_promo_group (get_primary_promo_group first)
group_pct = 0
offer_pct = 0
if user:
promo_group = self.resolve_promo_group(user)
if promo_group is not None:
best_period = min(
current_tariff.get_available_periods() or [30],
key=lambda p: abs(p - remaining_days),
)
group_pct = promo_group.get_discount_percent('period', best_period)
offer_pct = get_user_active_promo_discount_percent(user)
# Применяем stacked скидки к итоговой сумме напрямую (без float round-trip)
if group_pct > 0 or offer_pct > 0:
upgrade_cost, _, _ = self.apply_stacked_discounts(raw_cost, group_pct, offer_pct)
else:
upgrade_cost = raw_cost
return TariffSwitchResult(
upgrade_cost=upgrade_cost,
is_upgrade=True,
raw_cost=raw_cost,
group_discount_pct=group_pct,
offer_discount_pct=offer_pct,
new_period_days=0,
)
def _calculate_switch_to_daily(
self,
new_tariff: Tariff,
remaining_days: int,
*,
user: User | None = None,
) -> TariffSwitchResult:
"""Periodic → Daily: оплата первого дня с group + offer discount."""
daily_price = getattr(new_tariff, 'daily_price_kopeks', 0) or 0
if daily_price <= 0:
return TariffSwitchResult(
upgrade_cost=0,
is_upgrade=False,
raw_cost=0,
group_discount_pct=0,
offer_discount_pct=0,
new_period_days=1,
)
group_pct = 0
offer_pct = 0
if user:
promo_group = self.resolve_promo_group(user)
if promo_group:
period_hint = remaining_days if remaining_days > 0 else 30
group_pct = promo_group.get_discount_percent('period', period_hint)
offer_pct = get_user_active_promo_discount_percent(user)
if group_pct > 0 or offer_pct > 0:
upgrade_cost, _, _ = self.apply_stacked_discounts(daily_price, group_pct, offer_pct)
else:
upgrade_cost = daily_price
return TariffSwitchResult(
upgrade_cost=upgrade_cost,
is_upgrade=upgrade_cost > 0,
raw_cost=daily_price,
group_discount_pct=group_pct,
offer_discount_pct=offer_pct,
new_period_days=1,
)
def _calculate_switch_from_daily(
self,
new_tariff: Tariff,
remaining_days: int,
*,
user: User | None = None,
) -> TariffSwitchResult:
"""Daily → Periodic: оплата кратчайшего периода нового тарифа с group + offer discount."""
min_period_days = 30
min_period_price = 0
if new_tariff.period_prices:
min_period_days = min(int(k) for k in new_tariff.period_prices.keys())
min_period_price = new_tariff.period_prices.get(str(min_period_days), 0) or 0
if min_period_price <= 0:
return TariffSwitchResult(
upgrade_cost=0,
is_upgrade=False,
raw_cost=0,
group_discount_pct=0,
offer_discount_pct=0,
new_period_days=min_period_days,
)
group_pct = 0
offer_pct = 0
if user:
promo_group = self.resolve_promo_group(user)
if promo_group:
group_pct = promo_group.get_discount_percent('period', min_period_days)
offer_pct = get_user_active_promo_discount_percent(user)
if group_pct > 0 or offer_pct > 0:
upgrade_cost, _, _ = self.apply_stacked_discounts(min_period_price, group_pct, offer_pct)
else:
upgrade_cost = min_period_price
return TariffSwitchResult(
upgrade_cost=upgrade_cost,
is_upgrade=upgrade_cost > 0,
raw_cost=min_period_price,
group_discount_pct=group_pct,
offer_discount_pct=offer_pct,
new_period_days=min_period_days,
)
async def _calculate_servers_price(
self,
country_uuids: list[str],
@@ -222,37 +532,99 @@ class PricingEngine:
) -> RenewalPricing:
"""Price calculation when subscription is linked to a Tariff."""
tariff = subscription.tariff
period_prices: dict = tariff.period_prices or {}
base_price = int(period_prices.get(str(period_days), 0) or 0)
device_limit = subscription.device_limit or 0
return await self._calculate_tariff_core(
tariff,
period_days,
device_limit,
user=user,
)
# Extra devices above the tariff's included limit
async def _calculate_tariff_core(
self,
tariff: Tariff,
period_days: int,
device_limit: int,
*,
custom_traffic_gb: int | None = None,
user: User | None = None,
) -> RenewalPricing:
"""Core tariff pricing logic (raw params, no Subscription needed).
Per-category discounts:
- 'period' base tariff price
- 'devices' extra device cost
Promo-offer discount applied on the discounted subtotal.
Device cost is monthly × months_in_period.
"""
months = calculate_months_from_days(period_days)
# --- Base price ---
is_daily = getattr(tariff, 'is_daily', False)
if is_daily and period_days <= 1:
base_price = int(getattr(tariff, 'daily_price_kopeks', 0) or 0)
else:
period_prices: dict = tariff.period_prices or {}
base_price = int(period_prices.get(str(period_days), 0) or 0)
if base_price == 0 and hasattr(tariff, 'get_price_for_custom_days'):
if hasattr(tariff, 'can_purchase_custom_days') and tariff.can_purchase_custom_days():
custom_price = tariff.get_price_for_custom_days(period_days)
if custom_price is not None:
base_price = int(custom_price)
# --- Extra devices (monthly × months) ---
device_price_per_unit = (
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
)
extra_devices = max(0, (subscription.device_limit or 0) - (tariff.device_limit or 0))
devices_price = extra_devices * device_price_per_unit
tariff_device_limit = tariff.device_limit or 0
extra_devices = max(0, (device_limit or 0) - tariff_device_limit)
if is_daily and period_days <= 1:
devices_price = extra_devices * device_price_per_unit
else:
devices_price = extra_devices * device_price_per_unit * months
subtotal = base_price + devices_price
# --- Custom traffic (tariff add-on, uses addon discount path) ---
traffic_price = 0
if custom_traffic_gb is not None and hasattr(tariff, 'get_price_for_custom_traffic'):
raw_traffic = tariff.get_price_for_custom_traffic(custom_traffic_gb)
if raw_traffic and raw_traffic > 0:
traffic_price = int(raw_traffic)
# Resolve discounts
group_pct = 0
if user and getattr(user, 'promo_group', None) is not None:
group_pct = user.promo_group.get_discount_percent('period', period_days)
# --- Per-category group discounts ---
period_pct = 0
devices_pct = 0
promo_group = self.resolve_promo_group(user)
if promo_group is not None:
period_pct = promo_group.get_discount_percent('period', period_days)
devices_pct = promo_group.get_discount_percent('devices', period_days)
offer_pct = get_user_active_promo_discount_percent(user) if user else 0
final_total, group_discount, offer_discount = self.apply_stacked_discounts(
subtotal,
group_pct,
offer_pct,
)
discounted_base = self.apply_discount(base_price, period_pct)
discounted_devices = self.apply_discount(devices_price, devices_pct)
# Traffic uses addon discount (checks apply_discounts_to_addons flag)
discounted_traffic = traffic_price
if traffic_price > 0 and user:
discounted_traffic, _, _ = self.calculate_traffic_discount(traffic_price, user)
base_group_disc = base_price - discounted_base
devices_group_disc = devices_price - discounted_devices
traffic_group_disc = traffic_price - discounted_traffic
total_group_discount = base_group_disc + devices_group_disc + traffic_group_disc
subtotal = discounted_base + discounted_devices + discounted_traffic
after_offer = self.apply_discount(subtotal, offer_pct)
offer_discount = subtotal - after_offer
final_total = after_offer
breakdown = dataclasses.asdict(
TariffBreakdown(
tariff_id=tariff.id,
extra_devices=extra_devices,
group_discount_pct=group_pct,
group_discount_pct={'period': period_pct, 'devices': devices_pct},
offer_discount_pct=offer_pct,
months_in_period=months,
)
)
@@ -261,16 +633,17 @@ class PricingEngine:
'Negative final_total in tariff mode, clamping to 0',
final_total=final_total,
subtotal=subtotal,
group_pct=group_pct,
period_pct=period_pct,
devices_pct=devices_pct,
offer_pct=offer_pct,
)
return RenewalPricing(
base_price=base_price,
base_price=discounted_base,
servers_price=0,
traffic_price=0,
devices_price=devices_price,
promo_group_discount=group_discount,
traffic_price=discounted_traffic,
devices_price=discounted_devices,
promo_group_discount=total_group_discount,
promo_offer_discount=offer_discount,
final_total=max(0, final_total),
period_days=period_days,
@@ -278,19 +651,45 @@ class PricingEngine:
breakdown=breakdown,
)
async def calculate_tariff_purchase_price(
self,
tariff: Tariff,
period_days: int,
*,
device_limit: int | None = None,
custom_traffic_gb: int | None = None,
user: User | None = None,
) -> RenewalPricing:
"""Calculate price for a tariff purchase (new or renewal).
Public method that delegates to _calculate_tariff_core.
If device_limit is None, uses the tariff's included limit (no extra devices).
"""
effective_device_limit = device_limit if device_limit is not None else (tariff.device_limit or 0)
return await self._calculate_tariff_core(
tariff,
period_days,
effective_device_limit,
custom_traffic_gb=custom_traffic_gb,
user=user,
)
# ------------------------------------------------------------------
# Classic mode
# ------------------------------------------------------------------
async def _calculate_classic_mode(
async def _calculate_classic_core(
self,
db: AsyncSession,
subscription: Subscription,
period_days: int,
connected_squads: list[str],
traffic_limit_gb: int,
device_limit: int,
*,
purchased_traffic_gb: int = 0,
user: User | None = None,
) -> RenewalPricing:
"""Price calculation for legacy (non-tariff) subscriptions.
"""Core classic-mode pricing logic (raw params, no Subscription needed).
Uses CLASSIC_PERIOD_PRICES from settings, falling back to the
global PERIOD_PRICES dict during migration.
@@ -298,6 +697,7 @@ class PricingEngine:
Per-category discounts (period, servers, traffic, devices) are
applied separately to each component. Servers, traffic, and
devices are monthly prices multiplied by months_in_period.
Promo-offer discount is applied on the subtotal.
"""
months = calculate_months_from_days(period_days)
@@ -312,14 +712,13 @@ class PricingEngine:
fallback_price_kopeks=base_price_original,
)
# --- Per-category discount percents ---
# --- Per-category discount percents (resolve_promo_group: get_primary_promo_group first) ---
period_pct = 0
servers_pct = 0
traffic_pct = 0
devices_pct = 0
promo_group = None
if user and getattr(user, 'promo_group', None) is not None:
promo_group = user.promo_group
promo_group = self.resolve_promo_group(user)
if promo_group is not None:
period_pct = promo_group.get_discount_percent('period', period_days)
servers_pct = promo_group.get_discount_percent('servers', period_days)
traffic_pct = promo_group.get_discount_percent('traffic', period_days)
@@ -331,7 +730,6 @@ class PricingEngine:
base_price = self.apply_discount(base_price_original, period_pct)
# --- Servers (monthly × months, with servers discount) ---
connected_squads: list[str] = subscription.connected_squads or []
promo_group_id = getattr(user, 'promo_group_id', None) if user else None
servers_price_per_month, server_details = await self._calculate_servers_price(
connected_squads,
@@ -345,13 +743,6 @@ class PricingEngine:
if settings.is_traffic_fixed():
traffic_limit_gb = settings.get_fixed_traffic_limit()
purchased_traffic_gb = 0
else:
traffic_limit_gb = (
subscription.traffic_limit_gb
if subscription.traffic_limit_gb is not None
else settings.DEFAULT_TRAFFIC_LIMIT_GB
)
purchased_traffic_gb = subscription.purchased_traffic_gb or 0
traffic_price_per_month = self._calculate_traffic_price(traffic_limit_gb, purchased_traffic_gb)
discounted_traffic_per_month = self.apply_discount(traffic_price_per_month, traffic_pct)
traffic_price = discounted_traffic_per_month * months
@@ -359,7 +750,7 @@ class PricingEngine:
# --- Devices (monthly × months, with devices discount) ---
default_device_limit = settings.DEFAULT_DEVICE_LIMIT
device_price_per_unit = settings.PRICE_PER_DEVICE
extra_devices = max(0, (subscription.device_limit or 0) - default_device_limit)
extra_devices = max(0, (device_limit or 0) - default_device_limit)
devices_price_per_month = extra_devices * device_price_per_unit
discounted_devices_per_month = self.apply_discount(devices_price_per_month, devices_pct)
devices_price = discounted_devices_per_month * months
@@ -386,7 +777,9 @@ class PricingEngine:
ClassicBreakdown(
months_in_period=months,
servers=server_details,
servers_individual_prices=[d['price'] * months for d in valid_servers],
servers_individual_prices=[
self.apply_discount(d['price'], servers_pct) * months for d in valid_servers
],
server_ids=[d['id'] for d in valid_servers],
base_traffic_gb=max(0, traffic_limit_gb - purchased_traffic_gb),
purchased_traffic_gb=purchased_traffic_gb,
@@ -398,6 +791,10 @@ class PricingEngine:
'devices': devices_pct,
},
offer_discount_pct=offer_pct,
base_price_original=base_price_original,
traffic_price_per_month=traffic_price_per_month,
servers_price_per_month=servers_price_per_month,
devices_price_per_month=devices_price_per_month,
)
)
@@ -422,6 +819,116 @@ class PricingEngine:
breakdown=breakdown,
)
async def _calculate_classic_mode(
self,
db: AsyncSession,
subscription: Subscription,
period_days: int,
*,
user: User | None = None,
) -> RenewalPricing:
"""Price calculation for legacy (non-tariff) subscriptions.
Thin wrapper that extracts raw params from a Subscription
and delegates to _calculate_classic_core.
"""
connected_squads: list[str] = subscription.connected_squads or []
traffic_limit_gb = (
subscription.traffic_limit_gb
if subscription.traffic_limit_gb is not None
else settings.DEFAULT_TRAFFIC_LIMIT_GB
)
purchased_traffic_gb = subscription.purchased_traffic_gb or 0
device_limit = subscription.device_limit or 0
return await self._calculate_classic_core(
db,
period_days,
connected_squads,
traffic_limit_gb,
device_limit,
purchased_traffic_gb=purchased_traffic_gb,
user=user,
)
async def calculate_classic_new_subscription_price(
self,
db: AsyncSession,
period_days: int,
connected_squads: list[str],
traffic_limit_gb: int,
device_limit: int,
*,
user: User | None = None,
) -> RenewalPricing:
"""Calculate price for a NEW classic (non-tariff) subscription.
Like calculate_renewal_price but without requiring an existing
Subscription object. purchased_traffic_gb is always 0.
"""
return await self._calculate_classic_core(
db,
period_days,
connected_squads,
traffic_limit_gb,
device_limit,
purchased_traffic_gb=0,
user=user,
)
@staticmethod
def classic_pricing_to_purchase_details(pricing: RenewalPricing) -> dict[str, Any]:
"""Convert RenewalPricing to the legacy details dict format.
The returned dict is compatible with build_preview_payload
in SubscriptionPurchaseService.
"""
bd = pricing.breakdown
months = bd.get('months_in_period', 1) or 1
group_pct = bd.get('group_discount_pct', {})
base_price_original = bd.get('base_price_original', 0)
traffic_price_per_month = bd.get('traffic_price_per_month', 0)
servers_price_per_month = bd.get('servers_price_per_month', 0)
devices_price_per_month = bd.get('devices_price_per_month', 0)
period_pct = group_pct.get('period', 0)
traffic_pct = group_pct.get('traffic', 0)
servers_pct = group_pct.get('servers', 0)
devices_pct = group_pct.get('devices', 0)
base_discount_total = base_price_original - pricing.base_price
traffic_discount_total = (
traffic_price_per_month - PricingEngine.apply_discount(traffic_price_per_month, traffic_pct)
) * months
servers_discount_total = (
servers_price_per_month - PricingEngine.apply_discount(servers_price_per_month, servers_pct)
) * months
devices_discount_total = (
devices_price_per_month - PricingEngine.apply_discount(devices_price_per_month, devices_pct)
) * months
return {
'base_price': pricing.base_price,
'base_price_original': base_price_original,
'base_discount_percent': period_pct,
'base_discount_total': base_discount_total,
'traffic_price_per_month': traffic_price_per_month,
'traffic_discount_percent': traffic_pct,
'traffic_discount_total': traffic_discount_total,
'total_traffic_price': pricing.traffic_price,
'servers_price_per_month': servers_price_per_month,
'servers_discount_percent': servers_pct,
'servers_discount_total': servers_discount_total,
'total_servers_price': pricing.servers_price,
'devices_price_per_month': devices_price_per_month,
'devices_discount_percent': devices_pct,
'devices_discount_total': devices_discount_total,
'total_devices_price': pricing.devices_price,
'months_in_period': months,
'servers_individual_prices': bd.get('servers_individual_prices', []),
}
# Module-level singleton — use this instead of PricingEngine()
pricing_engine = PricingEngine()
+2 -1
View File
@@ -115,6 +115,7 @@ class PromoOfferService:
remnawave_user = await self.subscription_service.update_remnawave_user(
db,
subscription,
sync_squads=True,
)
if remnawave_user is None:
await db.rollback()
@@ -188,7 +189,7 @@ class PromoOfferService:
subscription.connected_squads = list(updated)
subscription.updated_at = now
try:
await self.subscription_service.update_remnawave_user(db, subscription)
await self.subscription_service.update_remnawave_user(db, subscription, sync_squads=True)
except Exception as exc: # pragma: no cover - defensive logging
logger.error(
'Ошибка обновления Remnawave при отзыве тестового доступа подписки',
@@ -224,8 +224,12 @@ async def _process_single_subscription(
autopay_period = 30
try:
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine
# TOCTOU: lock user row before pricing to prevent concurrent promo/balance races
user = await lock_user_for_pricing(db, user.id)
pricing = await pricing_engine.calculate_renewal_price(
db,
subscription,
+17 -5
View File
@@ -132,8 +132,8 @@ async def process_referral_registration(db: AsyncSession, new_user_id: int, refe
)
if settings.REFERRAL_INVITER_BONUS_KOPEKS > 0:
inviter_notification += (
f'вы получите минимум {settings.format_price(settings.REFERRAL_INVITER_BONUS_KOPEKS)} или '
f'{commission_percent}% от суммы (что больше).\n\n'
f'вы получите {settings.format_price(settings.REFERRAL_INVITER_BONUS_KOPEKS)} + '
f'{commission_percent}% от суммы пополнения.\n\n'
)
else:
inviter_notification += f'вы получите {commission_percent}% от суммы.\n\n'
@@ -304,7 +304,7 @@ async def process_referral_topup(db: AsyncSession, user_id: int, topup_amount_ko
)
commission_amount = int(topup_amount_kopeks * commission_percent / 100)
inviter_bonus = max(settings.REFERRAL_INVITER_BONUS_KOPEKS, commission_amount)
inviter_bonus = settings.REFERRAL_INVITER_BONUS_KOPEKS + commission_amount
if inviter_bonus > 0:
balance_ok = await add_user_balance(
@@ -332,10 +332,22 @@ async def process_referral_topup(db: AsyncSession, user_id: int, topup_amount_ko
)
if bot:
bonus_parts = []
if settings.REFERRAL_INVITER_BONUS_KOPEKS > 0:
bonus_parts.append(
f'фикс. бонус {settings.format_price(settings.REFERRAL_INVITER_BONUS_KOPEKS)}'
)
if commission_amount > 0:
bonus_parts.append(
f'комиссия {commission_percent}% = {settings.format_price(commission_amount)}'
)
bonus_breakdown = ' + '.join(bonus_parts)
inviter_bonus_notification = (
f'💰 <b>Реферальная награда!</b>\n\n'
f'Ваш реферал <b>{user.full_name}</b> сделал первое пополнение!\n\n'
f'🎁 Вы получили награду: {settings.format_price(inviter_bonus)}\n\n'
f'Ваш реферал <b>{user.full_name}</b> сделал первое пополнение '
f'на {settings.format_price(topup_amount_kopeks)}!\n\n'
f'🎁 Ваша награда: {settings.format_price(inviter_bonus)}'
f' ({bonus_breakdown})\n\n'
f'📈 Теперь с каждого его пополнения вы будете получать {commission_percent}% комиссии.'
)
await send_referral_notification(
+4 -6
View File
@@ -1961,11 +1961,10 @@ class RemnaWaveService:
if hwid_limit is not None:
create_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
# Внешний сквад: синхронизируем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if sub.tariff and sub.tariff.external_squad_uuid:
create_kwargs['external_squad_uuid'] = sub.tariff.external_squad_uuid
else:
create_kwargs['external_squad_uuid'] = None
# Определяем UUID для обновления
panel_uuid = user.remnawave_uuid
@@ -2007,11 +2006,10 @@ class RemnaWaveService:
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
# Внешний сквад: синхронизируем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if sub.tariff and sub.tariff.external_squad_uuid:
update_kwargs['external_squad_uuid'] = sub.tariff.external_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
try:
await api.update_user(**update_kwargs)
@@ -14,7 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.subscription import extend_subscription
from app.database.crud.transaction import create_transaction
from app.database.crud.user import get_user_by_id, subtract_user_balance
from app.database.crud.user import subtract_user_balance
from app.database.models import Subscription, SubscriptionStatus, TransactionType, User
from app.localization.texts import get_texts
from app.services.admin_notification_service import AdminNotificationService
@@ -83,13 +83,11 @@ async def _prepare_auto_purchase(
)
return None
# Перезагружаем user с нужными связями (user_promo_groups),
# Блокируем user с нужными связями (user_promo_groups) для защиты от TOCTOU,
# т.к. после db.refresh() в payment-сервисах связи сбрасываются
fresh_user = await get_user_by_id(db, user.id)
if not fresh_user:
logger.warning('🔁 Автопокупка: не удалось перезагрузить пользователя', format_user_id=_format_user_id(user))
return None
user = fresh_user
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
miniapp_service = MiniAppSubscriptionPurchaseService()
context = await miniapp_service.build_options(db, user)
@@ -141,11 +139,6 @@ def _safe_int(value: object | None, default: int = 0) -> int:
return default
def _apply_promo_discount_for_tariff(price: int, discount_percent: int) -> int:
"""Применяет скидку промогруппы к цене тарифа."""
return PricingEngine.apply_discount(price, discount_percent)
async def _prepare_auto_extend_context(
db: AsyncSession,
user: User,
@@ -187,7 +180,11 @@ async def _prepare_auto_extend_context(
if tariff_id:
tariff_id = _safe_int(tariff_id)
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine as _pricing_engine
from app.utils.promo_offer import get_user_active_promo_discount_percent
user = await lock_user_for_pricing(db, user.id)
try:
pricing = await _pricing_engine.calculate_renewal_price(
@@ -232,8 +229,6 @@ async def _prepare_auto_extend_context(
traffic_limit_gb = _safe_int(traffic_limit_gb, subscription.traffic_limit_gb or 0)
squad_uuid = cart_data.get('squad_uuid')
from app.utils.promo_offer import get_user_active_promo_discount_percent
consume_promo_offer = get_user_active_promo_discount_percent(user) > 0
allowed_squads = cart_data.get('allowed_squads')
@@ -465,6 +460,7 @@ async def _auto_extend_subscription(
updated_subscription,
reset_traffic=should_reset_traffic,
reset_reason='смена тарифа' if is_tariff_change else 'продление подписки',
sync_squads=is_tariff_change,
)
except Exception as error: # pragma: no cover - defensive logging
logger.error(
@@ -625,44 +621,26 @@ async def _auto_purchase_tariff(
)
return False
# Получаем актуальную цену тарифа
prices = tariff.period_prices or {}
base_price = prices.get(str(period_days))
if base_price is None:
logger.warning(
'🔁 Автопокупка тарифа: период дней недоступен для тарифа', period_days=period_days, tariff_id=tariff_id
)
return False
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
final_price = int(base_price)
# Проверяем есть ли уже подписка (нужно до расчёта цены для учёта доп. устройств)
existing_subscription = await get_subscription_by_user_id(db, user.id)
# Добавляем стоимость докупленных устройств ДО скидки (как в cabinet)
user = await lock_user_for_pricing(db, user.id)
# Calculate price via PricingEngine (single source of truth)
device_limit = None
if existing_subscription and existing_subscription.tariff_id == tariff_id:
extra_devices = max(0, (existing_subscription.device_limit or 0) - (tariff.device_limit or 0))
if extra_devices > 0:
device_price_per_unit = (
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
)
extra_devices_cost = extra_devices * device_price_per_unit
final_price += extra_devices_cost
device_limit = existing_subscription.device_limit
# Пересчитываем скидку из актуальных данных пользователя (не из stale корзины)
# Promo_group и promo_offer применяются последовательно (как в cabinet)
from app.utils.promo_offer import get_user_active_promo_discount_percent
discount_percent = 0
if hasattr(user, 'get_promo_discount'):
discount_percent = user.get_promo_discount('period', period_days)
if discount_percent > 0:
final_price = _apply_promo_discount_for_tariff(final_price, discount_percent)
promo_offer_percent = get_user_active_promo_discount_percent(user)
if promo_offer_percent > 0:
final_price = _apply_promo_discount_for_tariff(final_price, promo_offer_percent)
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
period_days,
device_limit=device_limit,
user=user,
)
final_price = result.final_total
consume_promo = result.promo_offer_discount > 0
if user.balance_kopeks < final_price:
logger.info(
@@ -674,7 +652,6 @@ async def _auto_purchase_tariff(
return False
# Save promo offer state before deduction (for restore on failure)
consume_promo = promo_offer_percent > 0
saved_promo_percent = int(getattr(user, 'promo_offer_discount_percent', 0) or 0) if consume_promo else 0
saved_promo_source = getattr(user, 'promo_offer_discount_source', None) if consume_promo else None
saved_promo_expires = getattr(user, 'promo_offer_discount_expires_at', None) if consume_promo else None
@@ -978,12 +955,25 @@ async def _auto_purchase_daily_tariff(
)
return False
if user.balance_kopeks < daily_price:
# Блокируем пользователя и применяем скидки (group + promo-offer)
from app.database.crud.user import lock_user_for_pricing
from app.utils.promo_offer import get_user_active_promo_discount_percent
user = await lock_user_for_pricing(db, user.id)
promo_group = user.get_primary_promo_group()
group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
offer_pct = get_user_active_promo_discount_percent(user)
final_price, _, _ = PricingEngine.apply_stacked_discounts(daily_price, group_pct, offer_pct)
consume_promo = offer_pct > 0
if user.balance_kopeks < final_price:
logger.info(
'🔁 Автопокупка суточного тарифа: у пользователя недостаточно средств (<)',
format_user_id=_format_user_id(user),
balance_kopeks=user.balance_kopeks,
daily_price=daily_price,
final_price=final_price,
)
return False
@@ -993,8 +983,9 @@ async def _auto_purchase_daily_tariff(
success = await subtract_user_balance(
db,
user,
daily_price,
final_price,
description,
consume_promo_offer=consume_promo,
mark_as_paid_subscription=True,
)
if not success:
@@ -1081,7 +1072,7 @@ async def _auto_purchase_daily_tariff(
await add_user_balance(
db,
user,
daily_price,
final_price,
'Возврат: ошибка автопокупки суточного тарифа',
create_transaction=True,
transaction_type=TransactionType.REFUND,
@@ -1089,13 +1080,13 @@ async def _auto_purchase_daily_tariff(
logger.info(
'💰 Автопокупка суточного тарифа: возврат средств после ошибки создания подписки',
format_user_id=_format_user_id(user),
refund_kopeks=daily_price,
refund_kopeks=final_price,
)
except Exception as refund_error:
logger.critical(
'CRITICAL: Автопокупка суточного тарифа: не удалось вернуть средства',
format_user_id=_format_user_id(user),
price_kopeks=daily_price,
price_kopeks=final_price,
refund_error=refund_error,
)
return False
@@ -1106,7 +1097,7 @@ async def _auto_purchase_daily_tariff(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=daily_price,
amount_kopeks=final_price,
description=description,
)
except Exception as error:
@@ -1167,7 +1158,7 @@ async def _auto_purchase_daily_tariff(
message = (
f'✅ <b>Суточный тариф «{tariff.name}» активирован!</b>\n\n'
f'💰 Списано: {daily_price / 100:.0f} ₽ за первый день\n'
f'💰 Списано: {final_price / 100:.0f} ₽ за первый день\n'
f'🔄 Средства будут списываться автоматически раз в сутки.\n\n'
f'ℹ️ Вы можете приостановить подписку в любой момент.'
)
@@ -1215,7 +1206,7 @@ async def _auto_purchase_daily_tariff(
await notify_user_subscription_renewed(
user_id=user.id,
new_expires_at=subscription.end_date.isoformat() if subscription.end_date else '',
amount_kopeks=daily_price,
amount_kopeks=final_price,
)
else:
# New subscription activation
@@ -1244,28 +1235,19 @@ async def _auto_add_devices(
"""Auto-purchase devices from saved cart after balance topup."""
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from app.database.crud.user import subtract_user_balance
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
from app.database.models import PaymentMethod
from app.utils.pricing_utils import apply_percentage_discount
devices_to_add = _safe_int(cart_data.get('devices_to_add'))
price_kopeks = _safe_int(cart_data.get('price_kopeks'))
cart_price_kopeks = _safe_int(cart_data.get('price_kopeks'))
if devices_to_add <= 0 or price_kopeks <= 0:
if devices_to_add <= 0 or cart_price_kopeks <= 0:
logger.warning(
'🔁 Автопокупка устройств: некорректные данные корзины для пользователя (devices price=)',
format_user_id=_format_user_id(user),
devices_to_add=devices_to_add,
price_kopeks=price_kopeks,
)
return False
# Проверяем баланс
if user.balance_kopeks < price_kopeks:
logger.info(
'🔁 Автопокупка устройств: у пользователя недостаточно средств (<)',
format_user_id=_format_user_id(user),
balance_kopeks=user.balance_kopeks,
price_kopeks=price_kopeks,
cart_price_kopeks=cart_price_kopeks,
)
return False
@@ -1330,6 +1312,44 @@ async def _auto_add_devices(
await user_cart_service.delete_user_cart(user.id)
return False
# Lock user BEFORE price computation to prevent TOCTOU on promo-offer/group discount
user = await lock_user_for_pricing(db, user.id)
# Recompute price fresh under lock (pricing config may have changed since cart was saved)
devices_price_per_month = devices_to_add * tariff_device_price
days_left = max(1, (subscription.end_date - datetime.now(UTC)).days)
devices_discount_percent = PricingEngine.get_addon_discount_percent(
user,
'devices',
days_left,
)
discounted_per_month, _ = apply_percentage_discount(
devices_price_per_month,
devices_discount_percent,
)
price_kopeks = int(discounted_per_month * days_left / 30)
price_kopeks = max(100, price_kopeks)
if price_kopeks != cart_price_kopeks:
logger.warning(
'🔁 Автопокупка устройств: пересчитанная цена отличается от корзины',
format_user_id=_format_user_id(user),
cart_price_kopeks=cart_price_kopeks,
recomputed_price_kopeks=price_kopeks,
devices_discount_percent=devices_discount_percent,
days_left=days_left,
)
# Проверяем баланс (с актуальной ценой)
if user.balance_kopeks < price_kopeks:
logger.info(
'🔁 Автопокупка устройств: у пользователя недостаточно средств (<)',
format_user_id=_format_user_id(user),
balance_kopeks=user.balance_kopeks,
price_kopeks=price_kopeks,
)
return False
# Списываем баланс
description = f'Покупка {devices_to_add} доп. устройств'
try:
@@ -1519,28 +1539,19 @@ async def _auto_add_traffic(
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from app.database.crud.subscription import add_subscription_traffic, get_subscription_by_user_id
from app.database.crud.user import subtract_user_balance
from app.database.crud.user import lock_user_for_pricing, subtract_user_balance
from app.database.models import PaymentMethod
from app.utils.pricing_utils import calculate_prorated_price
traffic_gb = _safe_int(cart_data.get('traffic_gb'))
price_kopeks = _safe_int(cart_data.get('price_kopeks'))
cart_price_kopeks = _safe_int(cart_data.get('price_kopeks'))
if traffic_gb <= 0 or price_kopeks <= 0:
if traffic_gb <= 0 or cart_price_kopeks <= 0:
logger.warning(
'🔁 Автопокупка трафика: некорректные данные корзины для пользователя (traffic_gb price=)',
format_user_id=_format_user_id(user),
traffic_gb=traffic_gb,
price_kopeks=price_kopeks,
)
return False
# Verify balance
if user.balance_kopeks < price_kopeks:
logger.info(
'🔁 Автопокупка трафика: у пользователя недостаточно средств (<)',
format_user_id=_format_user_id(user),
balance_kopeks=user.balance_kopeks,
price_kopeks=price_kopeks,
cart_price_kopeks=cart_price_kopeks,
)
return False
@@ -1572,6 +1583,72 @@ async def _auto_add_traffic(
await user_cart_service.delete_user_cart(user.id)
return False
# Lock user BEFORE price computation to prevent TOCTOU on promo-offer/group discount
user = await lock_user_for_pricing(db, user.id)
# Recompute base price from tariff/settings (config may have changed since cart was saved)
tariff = None
if settings.is_tariffs_mode() and subscription.tariff_id:
from app.database.crud.tariff import get_tariff_by_id
tariff = await get_tariff_by_id(db, subscription.tariff_id)
if tariff and tariff.can_topup_traffic():
base_price = tariff.get_traffic_topup_price(traffic_gb) or 0
else:
base_price = settings.get_traffic_topup_price(traffic_gb)
if base_price <= 0 and traffic_gb != 0:
logger.warning(
'🔁 Автопокупка трафика: цена пакета не настроена, корзина удалена',
format_user_id=_format_user_id(user),
traffic_gb=traffic_gb,
)
await user_cart_service.delete_user_cart(user.id)
return False
# Apply traffic discount from promo group
period_hint_days: int | None = None
if subscription.end_date:
days_remaining = (subscription.end_date - datetime.now(UTC)).days
period_hint_days = days_remaining if days_remaining > 0 else None
discounted_per_month, _, _ = PricingEngine.calculate_traffic_discount(
base_price,
user,
period_hint_days,
)
# Prorate for classic mode (tariff mode uses monthly price as-is)
is_tariff_mode = settings.is_tariffs_mode() and subscription.tariff_id
if is_tariff_mode:
price_kopeks = discounted_per_month
elif subscription and subscription.end_date:
price_kopeks, _ = calculate_prorated_price(discounted_per_month, subscription.end_date)
else:
price_kopeks = discounted_per_month
if cart_price_kopeks != price_kopeks:
logger.warning(
'🔁 Автопокупка трафика: пересчитанная цена отличается от корзины',
format_user_id=_format_user_id(user),
cart_price_kopeks=cart_price_kopeks,
recomputed_price_kopeks=price_kopeks,
base_price=base_price,
discounted_per_month=discounted_per_month,
period_hint_days=period_hint_days,
)
# Verify balance (with fresh price)
if user.balance_kopeks < price_kopeks:
logger.info(
'🔁 Автопокупка трафика: у пользователя недостаточно средств (<)',
format_user_id=_format_user_id(user),
balance_kopeks=user.balance_kopeks,
price_kopeks=price_kopeks,
)
return False
# Deduct balance
description = f'Докупка {traffic_gb} ГБ трафика'
try:
@@ -1801,6 +1878,11 @@ async def try_auto_extend_expired_after_topup(
else:
period_days = 30
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Calculate renewal price via PricingEngine
subscription_service = SubscriptionService()
try:
@@ -1870,10 +1952,8 @@ async def try_auto_extend_expired_after_topup(
check_error=check_error,
)
# Determine if promo offer discount was applied (for consume flag)
from app.utils.promo_offer import get_user_active_promo_discount_percent
consume_promo_offer = get_user_active_promo_discount_percent(user) > 0
# Derive consume_promo_offer from PricingEngine result (user already locked above)
consume_promo_offer = pricing.promo_offer_discount > 0
# Save promo offer state before deduction (for restore on failure)
saved_promo_percent = int(getattr(user, 'promo_offer_discount_percent', 0) or 0) if consume_promo_offer else 0
@@ -2142,11 +2222,25 @@ async def try_resume_disabled_daily_after_topup(
if not tariff:
return False
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
if daily_price <= 0:
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
if raw_daily_price <= 0:
return False
# Check balance
# Lock user row to prevent TOCTOU between discount read and balance charge
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply group discount to daily price (consistent with PricingEngine._calculate_switch_to_daily)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
# Check balance (uses locked user's balance_kopeks — safe from concurrent reads)
if user.balance_kopeks < daily_price:
logger.info(
'🔄 Авто-возобновление daily: недостаточно средств',
@@ -2455,8 +2549,8 @@ async def auto_purchase_saved_cart_after_topup(
format_user_id=_format_user_id(user),
total_seconds=(datetime.now(UTC) - last_tx.created_at).total_seconds(),
)
# Очищаем корзину чтобы не срабатывало повторно
await user_cart_service.delete_user_cart(user.id)
# Корзину не очищаем: транзакция могла быть из другого потока
# (например, фоновое автопродление), чтобы не потерять явный выбор пользователя.
return False
except Exception as check_error:
logger.warning(
+22 -55
View File
@@ -11,7 +11,6 @@ from app.config import PERIOD_PRICES, settings
from app.database.crud.server_squad import (
add_user_to_servers,
get_available_server_squads,
get_server_ids_by_uuids,
get_server_squad_by_uuid,
)
from app.database.crud.subscription import (
@@ -32,7 +31,6 @@ from app.utils.pricing_utils import (
format_period_description,
validate_pricing_calculation,
)
from app.utils.promo_offer import get_user_active_promo_discount_percent
logger = structlog.get_logger(__name__)
@@ -279,18 +277,6 @@ def _apply_discount_to_monthly_component(amount_per_month: int, percent: int, mo
}
def _get_promo_offer_discount_percent(user: User | None) -> int:
return get_user_active_promo_discount_percent(user)
def _apply_promo_offer_discount(user: User | None, amount: int) -> tuple[int, int, int]:
percent = _get_promo_offer_discount_percent(user)
if amount <= 0 or percent <= 0:
return amount, 0, 0
discounted, discount_value = apply_percentage_discount(amount, percent)
return discounted, discount_value, percent
def _build_server_option(
server: ServerSquad,
discount_percent: int,
@@ -321,11 +307,9 @@ class MiniAppSubscriptionPurchaseService:
currency = (getattr(user, 'balance_currency', None) or 'RUB').upper()
texts = get_texts(getattr(user, 'language', None))
# Exclude trial-only servers from purchase options
available_servers = await get_available_server_squads(
db,
promo_group_id=getattr(user, 'promo_group_id', None),
exclude_trial_only=True,
)
server_catalog: dict[str, ServerSquad] = {server.squad_uuid: server for server in available_servers}
@@ -711,29 +695,30 @@ class MiniAppSubscriptionPurchaseService:
get_texts(getattr(context.user, 'language', None))
months = selection.period.months
server_ids = await get_server_ids_by_uuids(db, selection.servers)
# PricingEngine — single source of truth (includes promo-offer internally).
# Server validation is done via breakdown (avoids a duplicate DB query).
from app.services.pricing_engine import PricingEngine, pricing_engine
pricing = await pricing_engine.calculate_classic_new_subscription_price(
db,
selection.period.days,
list(selection.servers),
selection.traffic_value,
selection.devices,
user=context.user,
)
# Validate all requested servers were found
server_ids = pricing.breakdown.get('server_ids', [])
if len(server_ids) != len(selection.servers):
raise PurchaseValidationError('Some selected servers are not available', code='invalid_servers')
total_without_promo, details = await self._calculate_base_total(
db,
context.user,
selection,
server_ids,
)
details = PricingEngine.classic_pricing_to_purchase_details(pricing)
base_original_total = (
details['base_price_original']
+ details['traffic_price_per_month'] * months
+ details['servers_price_per_month'] * months
+ details['devices_price_per_month'] * months
)
final_total, promo_discount_value, promo_percent = _apply_promo_offer_discount(
context.user, total_without_promo
)
discounted_total = total_without_promo
base_original_total = pricing.original_total
discounted_total = pricing.final_total + pricing.promo_offer_discount # subtotal before offer
promo_discount_value = pricing.promo_offer_discount
promo_percent = pricing.breakdown.get('offer_discount_pct', 0)
is_valid = validate_pricing_calculation(
details.get('base_price', 0),
@@ -755,30 +740,11 @@ class MiniAppSubscriptionPurchaseService:
discounted_total=discounted_total,
promo_discount_value=promo_discount_value,
promo_discount_percent=promo_percent,
final_total=final_total,
final_total=pricing.final_total,
months=months,
details=details,
)
async def _calculate_base_total(
self,
db: AsyncSession,
user: User,
selection: PurchaseSelection,
server_ids: list[int],
) -> tuple[int, dict[str, Any]]:
from app.database.crud.subscription import calculate_subscription_total_cost
total_cost, details = await calculate_subscription_total_cost(
db,
selection.period.days,
selection.traffic_value,
server_ids,
selection.devices,
user=user,
)
return total_cost, details
def build_preview_payload(
self,
context: PurchaseOptionsContext,
@@ -1125,6 +1091,7 @@ class MiniAppSubscriptionPurchaseService:
subscription,
reset_traffic=True,
reset_reason='miniapp purchase',
sync_squads=True,
)
else:
await subscription_service.create_remnawave_user(
+13 -130
View File
@@ -10,12 +10,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.server_squad import get_all_server_squads
from app.database.crud.user import get_user_by_id
from app.database.models import PromoGroup, Subscription, SubscriptionStatus, User
from app.database.models import Subscription, SubscriptionStatus, User
from app.external.remnawave_api import RemnaWaveAPI, RemnaWaveAPIError, RemnaWaveUser, TrafficLimitStrategy, UserStatus
from app.utils.pricing_utils import (
calculate_months_from_days,
resolve_discount_percent,
)
from app.utils.subscription_utils import (
resolve_hwid_device_limit_for_payload,
)
@@ -242,11 +238,10 @@ class SubscriptionService:
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: назначаем из тарифа или сбрасываем
# Внешний сквад: назначаем из тарифа (если задан)
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
updated_user = await api.update_user(**update_kwargs)
@@ -335,6 +330,7 @@ class SubscriptionService:
*,
reset_traffic: bool = False,
reset_reason: str | None = None,
sync_squads: bool = False,
) -> RemnaWaveUser | None:
try:
user = await get_user_by_id(db, subscription.user_id)
@@ -389,7 +385,10 @@ class SubscriptionService:
),
)
if subscription.connected_squads:
# Сквады отправляем только при явном sync_squads=True (propagate_squads и пр.)
# В рутинных обновлениях пропускаем — сквады уже назначены при создании подписки,
# а пересылка стейловых UUID вызывает FK violation → A039 в RemnaWave
if sync_squads and subscription.connected_squads:
update_kwargs['active_internal_squads'] = subscription.connected_squads
if user_tag is not None:
@@ -398,12 +397,11 @@ class SubscriptionService:
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Внешний сквад: синхронизируем из тарифа или сбрасываем
if ext_squad_uuid is not None:
# Внешний сквад НЕ пересылаем в рутинных обновлениях — он уже назначен
# при создании подписки. Стейловый UUID вызывает FK violation → A039.
# Синхронизация сквадов происходит только при sync_squads=True.
if sync_squads and ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
# Тариф без внешнего сквада — сбрасываем у пользователя
update_kwargs['external_squad_uuid'] = None
updated_user = await api.update_user(**update_kwargs)
@@ -775,120 +773,6 @@ class SubscriptionService:
default_prices = [0] * len(country_uuids)
return sum(default_prices), default_prices
async def calculate_subscription_price_with_months(
self,
period_days: int,
traffic_gb: int,
server_squad_ids: list[int],
devices: int,
db: AsyncSession,
*,
user: User | None = None,
promo_group: PromoGroup | None = None,
) -> tuple[int, list[int]]:
from app.config import PERIOD_PRICES
from app.database.crud.server_squad import get_server_squad_by_id
if settings.MAX_DEVICES_LIMIT > 0 and devices > settings.MAX_DEVICES_LIMIT:
raise ValueError(f'Превышен максимальный лимит устройств: {settings.MAX_DEVICES_LIMIT}')
months_in_period = calculate_months_from_days(period_days)
base_price_original = PERIOD_PRICES.get(period_days, 0)
period_discount_percent = resolve_discount_percent(
user,
promo_group,
'period',
period_days=period_days,
)
base_discount_total = base_price_original * period_discount_percent // 100
base_price = base_price_original - base_discount_total
promo_group = promo_group or (user.get_primary_promo_group() if user else None)
traffic_price_per_month = settings.get_traffic_price(traffic_gb)
traffic_discount_percent = resolve_discount_percent(
user,
promo_group,
'traffic',
period_days=period_days,
)
traffic_discount_per_month = traffic_price_per_month * traffic_discount_percent // 100
discounted_traffic_per_month = traffic_price_per_month - traffic_discount_per_month
total_traffic_price = discounted_traffic_per_month * months_in_period
server_prices = []
total_servers_price = 0
servers_discount_percent = resolve_discount_percent(
user,
promo_group,
'servers',
period_days=period_days,
)
for server_id in server_squad_ids:
server = await get_server_squad_by_id(db, server_id)
if server and server.is_available and not server.is_full:
server_price_per_month = server.price_kopeks
server_discount_per_month = server_price_per_month * servers_discount_percent // 100
discounted_server_per_month = server_price_per_month - server_discount_per_month
server_price_total = discounted_server_per_month * months_in_period
server_prices.append(server_price_total)
total_servers_price += server_price_total
log_message = f'Сервер {server.display_name}: {server_price_per_month / 100}₽/мес x {months_in_period} мес = {server_price_total / 100}'
if server_discount_per_month > 0:
log_message += (
f' (скидка {servers_discount_percent}%: -{server_discount_per_month * months_in_period / 100}₽)'
)
logger.debug(log_message)
else:
server_prices.append(0)
logger.warning('Сервер ID недоступен', server_id=server_id)
additional_devices = max(0, devices - settings.DEFAULT_DEVICE_LIMIT)
devices_price_per_month = additional_devices * settings.PRICE_PER_DEVICE
devices_discount_percent = resolve_discount_percent(
user,
promo_group,
'devices',
period_days=period_days,
)
devices_discount_per_month = devices_price_per_month * devices_discount_percent // 100
discounted_devices_per_month = devices_price_per_month - devices_discount_per_month
total_devices_price = discounted_devices_per_month * months_in_period
total_price = base_price + total_traffic_price + total_servers_price + total_devices_price
logger.debug(
'Расчет стоимости новой подписки на дней ( мес)', period_days=period_days, months_in_period=months_in_period
)
base_log = f' Период {period_days} дней: {base_price_original / 100}'
if base_discount_total > 0:
base_log += f'{base_price / 100}₽ (скидка {period_discount_percent}%: -{base_discount_total / 100}₽)'
logger.debug(base_log)
if total_traffic_price > 0:
message = f' Трафик {traffic_gb} ГБ: {traffic_price_per_month / 100}₽/мес x {months_in_period} = {total_traffic_price / 100}'
if traffic_discount_per_month > 0:
message += (
f' (скидка {traffic_discount_percent}%: -{traffic_discount_per_month * months_in_period / 100}₽)'
)
logger.debug(message)
if total_servers_price > 0:
message = f' Серверы ({len(server_squad_ids)}): {total_servers_price / 100}'
if servers_discount_percent > 0:
message += f' (скидка {servers_discount_percent}% применяется ко всем серверам)'
logger.debug(message)
if total_devices_price > 0:
message = f' Устройства ({additional_devices}): {devices_price_per_month / 100}₽/мес x {months_in_period} = {total_devices_price / 100}'
if devices_discount_per_month > 0:
message += (
f' (скидка {devices_discount_percent}%: -{devices_discount_per_month * months_in_period / 100}₽)'
)
logger.debug(message)
logger.debug('ИТОГО: ₽', total_price=total_price / 100)
return total_price, server_prices
def _gb_to_bytes(self, gb: int | None) -> int:
if not gb: # None or 0
return 0
@@ -992,10 +876,9 @@ class SubscriptionService:
if hwid_limit is not None:
update_kwargs['hwid_device_limit'] = hwid_limit
# Не отправляем null — RemnaWave API не принимает null для externalSquadUuid (A039)
if ext_squad_uuid is not None:
update_kwargs['external_squad_uuid'] = ext_squad_uuid
else:
update_kwargs['external_squad_uuid'] = None
updated_user = await api.update_user(**update_kwargs)
+4
View File
@@ -11,6 +11,7 @@ from app.config import (
ENV_OVERRIDE_KEYS,
Settings,
clear_db_period_prices,
refresh_classic_period_prices,
refresh_period_prices,
refresh_traffic_prices,
settings,
@@ -1517,6 +1518,7 @@ class BotConfigurationService:
# т.к. ensure_tariffs_synced мог загрузить тарифные цены до того как
# SALES_MODE=classic был применён из system_settings
refresh_period_prices()
refresh_classic_period_prices()
@classmethod
async def reload(cls) -> None:
@@ -1673,6 +1675,7 @@ class BotConfigurationService:
if settings.is_classic_mode():
clear_db_period_prices()
refresh_period_prices()
refresh_classic_period_prices()
elif key in {
'PRICE_14_DAYS',
'PRICE_30_DAYS',
@@ -1682,6 +1685,7 @@ class BotConfigurationService:
'PRICE_360_DAYS',
}:
refresh_period_prices()
refresh_classic_period_prices()
elif key.startswith('PRICE_TRAFFIC_') or key == 'TRAFFIC_PACKAGES_CONFIG':
refresh_traffic_prices()
elif key in {'REMNAWAVE_AUTO_SYNC_ENABLED', 'REMNAWAVE_AUTO_SYNC_TIMES'}:
+15 -4
View File
@@ -96,12 +96,14 @@ class TributeService:
user_telegram_id = payment_data['user_id']
amount_kopeks = payment_data['amount_kopeks']
payment_id = payment_data['payment_id']
trb_user_id = payment_data.get('trb_user_id')
logger.info(
'Обрабатываем успешный Tribute платеж: user_telegram_id=, amount=, payment_id',
'Обрабатываем успешный Tribute платеж: user_telegram_id=, amount=, payment_id=, trb_user_id=',
user_telegram_id=user_telegram_id,
amount_kopeks=amount_kopeks,
payment_id=payment_id,
trb_user_id=trb_user_id,
)
async for session in get_db():
@@ -166,7 +168,7 @@ class TributeService:
except Exception as e:
logger.error('Ошибка обработки реферального пополнения Tribute', error=e)
if was_first_topup and not user.has_made_first_topup:
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await session.commit()
@@ -218,6 +220,7 @@ class TributeService:
try:
user_id = payment_data['user_id']
payment_id = payment_data['payment_id']
trb_user_id = payment_data.get('trb_user_id')
async for session in get_db():
transaction = await get_transaction_by_external_id(
@@ -230,7 +233,11 @@ class TributeService:
await self._send_failure_notification(user_id)
logger.info('Обработан неудачный Tribute платеж для пользователя', user_id=user_id)
logger.info(
'Обработан неудачный Tribute платеж для пользователя',
user_id=user_id,
trb_user_id=trb_user_id,
)
break
except Exception as e:
@@ -241,6 +248,7 @@ class TributeService:
user_id = refund_data['user_id']
amount_kopeks = refund_data['amount_kopeks']
payment_id = refund_data['payment_id']
trb_user_id = refund_data.get('trb_user_id')
async for session in get_db():
await create_transaction(
@@ -269,7 +277,10 @@ class TributeService:
await self._send_refund_notification(user_id, amount_kopeks)
logger.info(
'Обработан возврат Tribute: ₽ для пользователя', amount_kopeks=amount_kopeks / 100, user_id=user_id
'Обработан возврат Tribute: ₽ для пользователя',
amount_kopeks=amount_kopeks / 100,
user_id=user_id,
trb_user_id=trb_user_id,
)
break
+108
View File
@@ -0,0 +1,108 @@
"""Web auth deep-link token service.
Allows cabinet frontend to authenticate users via Telegram bot deep link
when oauth.telegram.org is blocked/unreachable.
Flow:
1. Frontend requests token: POST /cabinet/auth/deeplink/request
2. User clicks t.me/bot?start=webauth_TOKEN
3. Bot receives /start, links token to Telegram user
4. Frontend polls: POST /cabinet/auth/deeplink/poll -> gets JWT tokens
"""
import secrets
from datetime import UTC, datetime
from typing import Any
import structlog
from app.utils.cache import cache, cache_key
logger = structlog.get_logger(__name__)
WEB_AUTH_TOKEN_TTL = 300 # 5 minutes
WEB_AUTH_LINKED_TTL = 120 # seconds — poll window after token is linked
WEB_AUTH_TOKEN_MIN_LENGTH = 16
WEB_AUTH_PREFIX = 'web_auth'
async def create_web_auth_token() -> str:
"""Generate a web auth token and store it in Redis (pending state).
Returns the raw token string (URL-safe, 24 bytes of entropy).
"""
token = secrets.token_urlsafe(24)
key = cache_key(WEB_AUTH_PREFIX, token)
value: dict[str, Any] = {
'status': 'pending',
'created_at': datetime.now(UTC).isoformat(),
}
stored = await cache.set(key, value, expire=WEB_AUTH_TOKEN_TTL)
if not stored:
logger.error('Failed to store web auth token in Redis')
raise RuntimeError('Failed to create web auth token')
logger.debug('Web auth token created', token_prefix=token[:8])
return token
async def link_web_auth_token(token: str, telegram_id: int, user_id: int) -> bool:
"""Link a web auth token to a Telegram user (called by bot on /start).
Atomically takes the token (GETDEL) so only one caller can win the race.
Returns True if token was found and linked, False if expired/invalid.
"""
key = cache_key(WEB_AUTH_PREFIX, token)
# Atomically take the token — only one concurrent caller can succeed
data: Any = await cache.getdel(key)
if not data or not isinstance(data, dict):
logger.warning('Web auth token not found or expired', token_prefix=token[:8])
return False
if data.get('status') != 'pending':
logger.warning('Web auth token already used', token_prefix=token[:8])
return False
# Update token with user info
data['status'] = 'linked'
data['telegram_id'] = telegram_id
data['user_id'] = user_id
data['linked_at'] = datetime.now(UTC).isoformat()
# Re-store with reduced TTL (only needs to survive the poll window)
await cache.set(key, data, expire=WEB_AUTH_LINKED_TTL)
logger.info('Web auth token linked', token_prefix=token[:8], telegram_id=telegram_id)
return True
async def poll_web_auth_token(token: str) -> dict[str, Any] | None:
"""Poll for web auth token status (non-destructive).
Returns:
- None if token doesn't exist or is expired
- dict with status='pending' if not yet linked
- dict with status='linked' and user_id/telegram_id if linked
"""
key = cache_key(WEB_AUTH_PREFIX, token)
data: Any = await cache.get(key)
if not data or not isinstance(data, dict):
return None
return data
async def consume_web_auth_token(token: str) -> dict[str, Any] | None:
"""Atomically get and delete a web auth token.
Used after successful poll to prevent token reuse.
Returns the token data or None.
"""
key = cache_key(WEB_AUTH_PREFIX, token)
data = await cache.getdel(key)
if not data or not isinstance(data, dict):
return None
return data
+6 -3
View File
@@ -324,10 +324,13 @@ class FortuneWheelService:
# Синхронизируем с RemnaWave
try:
subscription_service = SubscriptionService()
await subscription_service.update_remnawave_user(db, subscription)
logger.info('✅ Списание дней синхронизировано с RemnaWave для user_id', user_id=user.id)
result = await subscription_service.update_remnawave_user(db, subscription)
if result is not None:
logger.info('✅ Списание дней синхронизировано с RemnaWave для user_id', user_id=user.id)
else:
logger.error('⚠️ Не удалось синхронизировать списание дней с RemnaWave', user_id=user.id)
except Exception as e:
logger.error('⚠️ Ошибка синхронизации списания дней с RemnaWave', error=e)
logger.error('⚠️ Ошибка синхронизации списания дней с RemnaWave', error=e, user_id=user.id)
return kopeks
+16 -10
View File
@@ -133,9 +133,10 @@ class YooKassaService:
)
loop = asyncio.get_running_loop()
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
async with asyncio.timeout(30):
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
logger.info(
'Ответ YooKassa Payment.create: ID=, Status=, Paid',
@@ -241,9 +242,10 @@ class YooKassaService:
)
loop = asyncio.get_running_loop()
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
async with asyncio.timeout(30):
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
logger.info(
'Ответ YooKassa Payment.create (СБП, redirect): ID=, Status=, Paid',
@@ -288,7 +290,10 @@ class YooKassaService:
logger.info('Получение информации о платеже YooKassa ID', payment_id_in_yookassa=payment_id_in_yookassa)
loop = asyncio.get_running_loop()
payment_info_yk = await loop.run_in_executor(None, lambda: YooKassaPayment.find_one(payment_id_in_yookassa))
async with asyncio.timeout(30):
payment_info_yk = await loop.run_in_executor(
None, lambda: YooKassaPayment.find_one(payment_id_in_yookassa)
)
if payment_info_yk:
logger.info(
@@ -415,9 +420,10 @@ class YooKassaService:
)
loop = asyncio.get_running_loop()
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
async with asyncio.timeout(30):
response = await loop.run_in_executor(
None, lambda: YooKassaPayment.create(payment_request, idempotence_key)
)
logger.info(
'Ответ YooKassa автоплатёж',
+4 -6
View File
@@ -76,12 +76,10 @@ def calculate_user_price(user: User | None, base_price: int, period_days: int, c
promo_offer_discount = get_user_active_promo_discount_percent(user)
# Apply both discounts sequentially (same as cabinet)
final_price = base_price
if group_discount > 0:
final_price = final_price - (final_price * group_discount) // 100
if promo_offer_discount > 0:
final_price = final_price - (final_price * promo_offer_discount) // 100
# Apply both discounts sequentially via PricingEngine
from app.services.pricing_engine import PricingEngine
final_price, _, _ = PricingEngine.apply_stacked_discounts(base_price, group_discount, promo_offer_discount)
# Effective combined discount percent
if final_price < base_price:
+104 -120
View File
@@ -10,6 +10,7 @@ from app.config import settings
if TYPE_CHECKING: # pragma: no cover
from app.database.models import PromoGroup, User
from app.services.pricing_engine import RenewalPricing
logger = structlog.get_logger(__name__)
@@ -84,32 +85,45 @@ async def compute_simple_subscription_price(
user: Optional['User'] = None,
resolved_squad_uuids: Sequence[str] | None = None,
) -> tuple[int, dict[str, Any]]:
"""Вычисляет стоимость простой подписки с учетом всех доплат и скидок."""
"""Вычисляет стоимость простой подписки с учетом всех доплат и скидок.
Delegates to PricingEngine.calculate_classic_new_subscription_price()
and converts the RenewalPricing result to the legacy breakdown dict
expected by callers.
"""
from app.services.pricing_engine import PricingEngine
period_days = int(params.get('period_days', 30) or 30)
attr_name = f'PRICE_{period_days}_DAYS'
base_price_original = getattr(settings, attr_name, settings.BASE_SUBSCRIPTION_PRICE)
traffic_limit_raw = params.get('traffic_limit_gb')
try:
traffic_limit = int(traffic_limit_raw) if traffic_limit_raw is not None else None
traffic_limit_gb = int(traffic_limit_raw) if traffic_limit_raw is not None else 0
except (TypeError, ValueError): # pragma: no cover - defensive conversion
traffic_limit = None
if traffic_limit is None or traffic_limit <= 0:
# Default simple subscriptions already include unlimited traffic.
traffic_price_original = 0
else:
traffic_price_original = settings.get_traffic_price(traffic_limit)
traffic_limit_gb = 0
# Treat None / non-positive as unlimited (0 GB → price = 0 in PricingEngine)
traffic_limit_gb = max(traffic_limit_gb, 0)
device_limit_raw = params.get('device_limit', settings.DEFAULT_DEVICE_LIMIT)
try:
device_limit = int(device_limit_raw)
except (TypeError, ValueError): # pragma: no cover - defensive conversion
device_limit = settings.DEFAULT_DEVICE_LIMIT
additional_devices = max(0, device_limit - settings.DEFAULT_DEVICE_LIMIT)
devices_price_original = additional_devices * settings.PRICE_PER_DEVICE
# --- Resolve squad UUIDs from explicit arg or params ---
resolved_uuids: list[str] = []
if resolved_squad_uuids:
resolved_uuids.extend([uuid for uuid in resolved_squad_uuids if uuid])
else:
raw_squad = params.get('squad_uuid')
if isinstance(raw_squad, (list, tuple, set)):
resolved_uuids.extend([str(uuid) for uuid in raw_squad if uuid])
elif raw_squad:
resolved_uuids.append(str(raw_squad))
# --- Resolve promo_group from params (backward compat) ---
# Callers may pass promo_group or promo_group_id via params dict.
# PricingEngine resolves promo_group from user internally, so we only
# need this for the applied_promo_group_id field in the breakdown.
promo_group: PromoGroup | None = params.get('promo_group')
if promo_group is None:
@@ -122,131 +136,103 @@ async def compute_simple_subscription_price(
if promo_group is None and user is not None:
promo_group = user.get_primary_promo_group()
period_discount_percent = resolve_discount_percent(
user,
promo_group,
'period',
period_days=period_days,
)
base_discount = base_price_original * period_discount_percent // 100
traffic_discount_percent = resolve_discount_percent(
user,
promo_group,
'traffic',
period_days=period_days,
)
traffic_discount = traffic_price_original * traffic_discount_percent // 100
devices_discount_percent = resolve_discount_percent(
user,
promo_group,
'devices',
period_days=period_days,
)
devices_discount = devices_price_original * devices_discount_percent // 100
servers_discount_percent = resolve_discount_percent(
user,
promo_group,
'servers',
period_days=period_days,
# --- Delegate to PricingEngine ---
engine = PricingEngine()
pricing = await engine.calculate_classic_new_subscription_price(
db,
period_days,
resolved_uuids,
traffic_limit_gb,
device_limit,
user=user,
)
resolved_uuids: list[str] = []
if resolved_squad_uuids:
resolved_uuids.extend([uuid for uuid in resolved_squad_uuids if uuid])
else:
raw_squad = params.get('squad_uuid')
if isinstance(raw_squad, (list, tuple, set)):
resolved_uuids.extend([str(uuid) for uuid in raw_squad if uuid])
elif raw_squad:
resolved_uuids.append(str(raw_squad))
# --- Build legacy breakdown dict from RenewalPricing + ClassicBreakdown ---
breakdown = _build_simple_subscription_breakdown(pricing, resolved_uuids, promo_group)
from app.database.crud.server_squad import get_server_squads_by_uuids
return pricing.final_total, breakdown
server_breakdown: list[dict[str, Any]] = []
servers_price_original = 0
servers_discount_total = 0
if resolved_uuids:
servers = await get_server_squads_by_uuids(db, resolved_uuids)
server_map = {s.squad_uuid: s for s in servers}
else:
server_map = {}
def _build_simple_subscription_breakdown(
pricing: 'RenewalPricing',
resolved_uuids: list[str],
promo_group: Optional['PromoGroup'],
) -> dict[str, Any]:
"""Convert PricingEngine's RenewalPricing to the legacy breakdown dict.
for squad_uuid in resolved_uuids:
server = server_map.get(squad_uuid)
if not server:
logger.warning('SIMPLE_SUBSCRIPTION_PRICE_SERVER_NOT_FOUND | squad', squad_uuid=squad_uuid)
server_breakdown.append(
{
'uuid': squad_uuid,
'name': None,
'available': False,
'original_price': 0,
'discount': 0,
'final_price': 0,
}
)
continue
Preserves all keys that callers depend on:
base_price, base_discount, traffic_price, traffic_discount,
devices_price, devices_discount, servers_price, servers_discount,
servers_final, server_details, total_before_discount, total_discount,
resolved_squad_uuids, applied_promo_group_id, *_discount_percent.
"""
from app.services.pricing_engine import PricingEngine
if not server.is_available or server.is_full:
logger.warning(
'SIMPLE_SUBSCRIPTION_PRICE_SERVER_UNAVAILABLE | squad= | available= | full',
squad_uuid=squad_uuid,
is_available=server.is_available,
is_full=server.is_full,
)
server_breakdown.append(
{
'uuid': squad_uuid,
'name': server.display_name,
'available': False,
'original_price': 0,
'discount': 0,
'final_price': 0,
}
)
continue
bd = pricing.breakdown
months = bd.get('months_in_period', 1) or 1
group_pct: dict[str, int] = bd.get('group_discount_pct', {})
original_price = server.price_kopeks
discount_value = original_price * servers_discount_percent // 100
final_price = original_price - discount_value
# Original (pre-discount) prices from ClassicBreakdown
base_price_original: int = bd.get('base_price_original', 0)
traffic_price_per_month: int = bd.get('traffic_price_per_month', 0)
servers_price_per_month: int = bd.get('servers_price_per_month', 0)
devices_price_per_month: int = bd.get('devices_price_per_month', 0)
servers_price_original += original_price
servers_discount_total += discount_value
# Per-category discount percents
period_discount_percent: int = group_pct.get('period', 0)
traffic_discount_percent: int = group_pct.get('traffic', 0)
servers_discount_percent: int = group_pct.get('servers', 0)
devices_discount_percent: int = group_pct.get('devices', 0)
server_breakdown.append(
# Total original prices (traffic/servers/devices are monthly × months)
traffic_price_total = traffic_price_per_month * months
servers_price_total = servers_price_per_month * months
devices_price_total = devices_price_per_month * months
# Discount values
base_discount = base_price_original - pricing.base_price
traffic_discount = traffic_price_total - pricing.traffic_price
servers_discount = servers_price_total - pricing.servers_price
devices_discount = devices_price_total - pricing.devices_price
total_before_discount = base_price_original + traffic_price_total + servers_price_total + devices_price_total
# Group discounts only (promo_offer_discount is separate and already
# reflected in final_total but NOT in per-category values above).
total_discount = base_discount + traffic_discount + servers_discount + devices_discount
# Build server_details in legacy format from PricingEngine's server list
server_details: list[dict[str, Any]] = []
servers_final = 0
for srv in bd.get('servers', []):
original_price = srv.get('price', 0)
status = srv.get('status', 'available')
is_available = status == 'available'
final_price = PricingEngine.apply_discount(original_price, servers_discount_percent) if is_available else 0
discount_value = original_price - final_price if is_available else 0
servers_final += final_price
server_details.append(
{
'uuid': squad_uuid,
'name': server.display_name,
'available': True,
'original_price': original_price,
'uuid': srv.get('uuid', ''),
'name': None, # PricingEngine._calculate_servers_price doesn't return display_name
'available': is_available,
'original_price': original_price if is_available else 0,
'discount': discount_value,
'final_price': final_price,
}
)
total_before_discount = (
base_price_original + traffic_price_original + devices_price_original + servers_price_original
)
total_discount = base_discount + traffic_discount + devices_discount + servers_discount_total
total_price = max(0, total_before_discount - total_discount)
breakdown = {
return {
'base_price': base_price_original,
'base_discount': base_discount,
'traffic_price': traffic_price_original,
'traffic_price': traffic_price_total,
'traffic_discount': traffic_discount,
'devices_price': devices_price_original,
'devices_price': devices_price_total,
'devices_discount': devices_discount,
'servers_price': servers_price_original,
'servers_discount': servers_discount_total,
'servers_final': sum(item['final_price'] for item in server_breakdown),
'server_details': server_breakdown,
'servers_price': servers_price_total,
'servers_discount': servers_discount,
'servers_final': servers_final,
'server_details': server_details,
'total_before_discount': total_before_discount,
'total_discount': total_discount,
'resolved_squad_uuids': resolved_uuids,
@@ -257,8 +243,6 @@ async def compute_simple_subscription_price(
'servers_discount_percent': servers_discount_percent,
}
return total_price, breakdown
def _pluralize_days_ru(n: int) -> str:
"""Склонение слова 'день' по числу: 1 день, 2 дня, 5 дней."""
+38
View File
@@ -35,6 +35,44 @@ def get_user_active_promo_discount_percent(user: User | None) -> int:
return max(0, min(100, percent))
async def consume_user_promo_offer(db: AsyncSession, user_id: int) -> bool:
"""Consume the user's one-shot promo-offer discount (zeroes out the fields).
Used by external payment fulfillment handlers (Stars, YooKassa)
where subtract_user_balance (which normally consumes the offer) is not called.
Returns True if an offer was actually consumed.
"""
from app.database.crud.promo_offer_log import log_promo_offer_action
result = await db.execute(select(User).where(User.id == user_id).with_for_update())
user = result.scalar_one_or_none()
if not user:
return False
current_percent = int(getattr(user, 'promo_offer_discount_percent', 0) or 0)
if current_percent <= 0:
return False
offer_id = getattr(user, 'promo_offer_discount_source', None)
user.promo_offer_discount_percent = 0
user.promo_offer_discount_source = None
user.promo_offer_discount_expires_at = None
await db.flush()
try:
await log_promo_offer_action(
db,
user_id=user_id,
offer_id=offer_id,
action='consumed_external_payment',
discount_percent=current_percent,
)
except Exception:
pass # Non-critical logging
return True
def _format_time_left(seconds_left: int, language: str) -> str:
total_minutes = max(1, math.ceil(seconds_left / 60))
days, remainder_minutes = divmod(total_minutes, 60 * 24)
+222 -329
View File
@@ -58,6 +58,7 @@ from app.database.models import (
from app.services.faq_service import FaqService
from app.services.maintenance_service import maintenance_service
from app.services.payment_service import PaymentService, get_wata_payment_by_link_id
from app.services.pricing_engine import PricingEngine
from app.services.privacy_policy_service import PrivacyPolicyService
from app.services.promo_offer_service import promo_offer_service
from app.services.promocode_service import PromoCodeService
@@ -210,12 +211,11 @@ _CRYPTOBOT_FALLBACK_RATE = 95.0
def _get_tariff_monthly_price(tariff) -> int:
"""Получает месячную цену тарифа (30 дней) с fallback на пропорциональный расчёт."""
"""Получает месячную цену тарифа (30 дней) для отображения в UI."""
price = tariff.get_price_for_period(30)
if price is not None:
return price
# Fallback: пропорционально пересчитываем из первого доступного периода
periods = tariff.get_available_periods()
if periods:
first_period = periods[0]
@@ -3341,6 +3341,15 @@ async def get_subscription_details(
is_daily_paused = getattr(subscription, 'is_daily_paused', False)
daily_tariff_name = tariff.name
daily_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0)
# Применяем скидку промогруппы + promo-offer для отображения
if daily_price_kopeks > 0:
_promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
_group_pct = _promo_group.get_discount_percent('period', 1) if _promo_group else 0
_offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if _group_pct > 0 or _offer_pct > 0:
daily_price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
daily_price_kopeks, _group_pct, _offer_pct
)
daily_price_label = settings.format_price(daily_price_kopeks) + '/день' if daily_price_kopeks > 0 else None
# Оставшееся время подписки (показываем даже при паузе)
if subscription.end_date:
@@ -3510,21 +3519,10 @@ async def _get_current_tariff_model(db: AsyncSession, subscription, user=None) -
servers_count = len(tariff.allowed_squads) if tariff.allowed_squads else 0
# Получаем скидку на трафик из промогруппы
traffic_discount_percent = 0
promo_group = (
(
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
if user
else None
)
if promo_group:
apply_to_addons = getattr(promo_group, 'apply_discounts_to_addons', True)
if apply_to_addons:
traffic_discount_percent = max(0, min(100, int(getattr(promo_group, 'traffic_discount_percent', 0) or 0)))
# Скидка на трафик через PricingEngine
from app.services.pricing_engine import PricingEngine, pricing_engine
promo_group = PricingEngine.resolve_promo_group(user) if user else None
# Лимит докупки трафика
max_topup_traffic_gb = getattr(tariff, 'max_topup_traffic_gb', 0) or 0
@@ -3547,9 +3545,12 @@ async def _get_current_tariff_model(db: AsyncSession, subscription, user=None) -
continue
base_price = packages[gb]
# Применяем скидку
if traffic_discount_percent > 0:
discounted_price = int(base_price * (100 - traffic_discount_percent) / 100)
# Применяем скидку через PricingEngine
discounted_price, _discount_val, traffic_discount_pct = pricing_engine.calculate_traffic_discount(
base_price,
user,
)
if traffic_discount_pct > 0:
traffic_topup_packages.append(
MiniAppTrafficTopupPackage(
gb=gb,
@@ -3557,7 +3558,7 @@ async def _get_current_tariff_model(db: AsyncSession, subscription, user=None) -
price_label=settings.format_price(discounted_price),
original_price_kopeks=base_price,
original_price_label=settings.format_price(base_price),
discount_percent=traffic_discount_percent,
discount_percent=traffic_discount_pct,
)
)
else:
@@ -3577,15 +3578,9 @@ async def _get_current_tariff_model(db: AsyncSession, subscription, user=None) -
# Применяем скидку промогруппы для 30-дневного периода
if promo_group:
raw_discounts = getattr(promo_group, 'period_discounts', None) or {}
for k, v in raw_discounts.items():
try:
if int(k) == 30:
discount = max(0, min(100, int(v)))
monthly_price = int(monthly_price * (100 - discount) / 100)
break
except (TypeError, ValueError):
pass
discount = promo_group.get_discount_percent('period', 30)
if discount > 0:
monthly_price = PricingEngine.apply_discount(monthly_price, discount)
return MiniAppCurrentTariff(
id=tariff.id,
@@ -4613,32 +4608,6 @@ async def _prepare_subscription_renewal_options(
return periods, pricing_map, recommended_option[0].id
def _get_addon_discount_percent_for_user(
user: User | None,
category: str,
period_days_hint: int | None = None,
) -> int:
if user is None:
return 0
promo_group = getattr(user, 'promo_group', None)
if promo_group is None:
return 0
if not getattr(promo_group, 'apply_discounts_to_addons', True):
return 0
try:
percent = user.get_promo_discount(category, period_days_hint)
except AttributeError:
return 0
try:
return int(percent)
except (TypeError, ValueError):
return 0
def _get_period_hint_from_subscription(
subscription: Subscription | None,
) -> int | None:
@@ -4916,21 +4885,9 @@ async def _build_subscription_settings(
) -> MiniAppSubscriptionSettings:
period_hint_days = _get_period_hint_from_subscription(subscription)
months_remaining = max(1, math.ceil((period_hint_days or 0) / 30))
servers_discount = _get_addon_discount_percent_for_user(
user,
'servers',
period_hint_days,
)
traffic_discount = _get_addon_discount_percent_for_user(
user,
'traffic',
period_hint_days,
)
devices_discount = _get_addon_discount_percent_for_user(
user,
'devices',
period_hint_days,
)
servers_discount = PricingEngine.get_addon_discount_percent(user, 'servers', period_hint_days)
traffic_discount = PricingEngine.get_addon_discount_percent(user, 'traffic', period_hint_days)
devices_discount = PricingEngine.get_addon_discount_percent(user, 'devices', period_hint_days)
current_servers, server_options, _ = await _prepare_server_catalog(
db,
@@ -5193,6 +5150,10 @@ async def submit_subscription_renewal_endpoint(
detail={'code': 'period_unavailable', 'message': 'Selected renewal period is not available'},
)
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
try:
pricing_result = await pricing_engine.calculate_renewal_price(db, subscription, period_days, user=user)
except HTTPException:
@@ -5450,6 +5411,10 @@ async def subscription_purchase_endpoint(
db: AsyncSession = Depends(get_db_session),
) -> MiniAppSubscriptionPurchaseResponse:
user = await _authorize_miniapp_user(payload.init_data, db)
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
context = await purchase_service.build_options(db, user)
selection_payload = _merge_purchase_selection_from_request(payload)
@@ -5593,12 +5558,13 @@ async def update_subscription_servers_endpoint(
message='No changes',
)
# Lock user BEFORE price computation to prevent TOCTOU on promo discount
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
period_hint_days = _get_period_hint_from_subscription(subscription)
servers_discount = _get_addon_discount_percent_for_user(
user,
'servers',
period_hint_days,
)
servers_discount = PricingEngine.get_addon_discount_percent(user, 'servers', period_hint_days)
_, _, catalog = await _prepare_server_catalog(
db,
@@ -5607,6 +5573,30 @@ async def update_subscription_servers_endpoint(
servers_discount,
)
# Enforce promo group authorization: drop any UUID not in the user's allowed set.
# Prevents users from retaining servers removed from their promo group.
authorized_servers = await get_available_server_squads(db, promo_group_id=getattr(user, 'promo_group_id', None))
authorized_uuids = {s.squad_uuid for s in authorized_servers}
selected_order = [uuid for uuid in selected_order if uuid in authorized_uuids]
if not selected_order:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
detail={
'code': 'validation_error',
'message': 'At least one authorized server must be selected',
},
)
# Recompute added/removed after authorization filter
selected_set = set(selected_order)
added = [uuid for uuid in selected_order if uuid not in current_set]
removed = [uuid for uuid in current_squads if uuid not in selected_set]
if not added and not removed:
return MiniAppSubscriptionUpdateResponse(
success=True,
message='No changes',
)
invalid_servers = [uuid for uuid in selected_order if uuid not in catalog]
if invalid_servers:
raise HTTPException(
@@ -5725,7 +5715,7 @@ async def update_subscription_servers_endpoint(
pass
service = SubscriptionService()
await service.update_remnawave_user(db, subscription)
await service.update_remnawave_user(db, subscription, sync_squads=True)
await with_admin_notification_service(
lambda service: service.send_subscription_update_notification(
@@ -5816,23 +5806,18 @@ async def update_subscription_traffic_endpoint(
days_remaining = max(1, (subscription.end_date - datetime.now(UTC)).days)
period_hint_days = days_remaining
traffic_discount = _get_addon_discount_percent_for_user(
user,
'traffic',
period_hint_days,
)
# Lock user BEFORE discount computation to prevent TOCTOU on promo group
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
traffic_discount = PricingEngine.get_addon_discount_percent(user, 'traffic', period_hint_days)
old_price_per_month = settings.get_traffic_price(subscription.traffic_limit_gb)
new_price_per_month = settings.get_traffic_price(new_traffic)
discounted_old_per_month, _ = apply_percentage_discount(
old_price_per_month,
traffic_discount,
)
discounted_new_per_month, _ = apply_percentage_discount(
new_price_per_month,
traffic_discount,
)
discounted_old_per_month = PricingEngine.apply_discount(old_price_per_month, traffic_discount)
discounted_new_per_month = PricingEngine.apply_discount(new_price_per_month, traffic_discount)
price_difference_per_month = discounted_new_per_month - discounted_old_per_month
total_price_difference = 0
@@ -5998,16 +5983,15 @@ async def update_subscription_devices_endpoint(
price_per_month = chargeable_diff * tariff_device_price
days_remaining = max(1, (subscription.end_date - datetime.now(UTC)).days)
period_hint_days = days_remaining
devices_discount = _get_addon_discount_percent_for_user(
user,
'devices',
period_hint_days,
)
discounted_per_month, _ = apply_percentage_discount(
price_per_month,
devices_discount,
)
# Lock user BEFORE price computation to prevent TOCTOU on promo discount
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
devices_discount = PricingEngine.get_addon_discount_percent(user, 'devices', period_hint_days)
discounted_per_month = PricingEngine.apply_discount(price_per_month, devices_discount)
price_to_charge, charged_days = calculate_prorated_price(
discounted_per_month,
subscription.end_date,
@@ -6150,27 +6134,22 @@ async def _build_tariff_model(
)
)
# Получаем скидки промогруппы по периодам
period_discounts = {}
if promo_group:
raw_discounts = getattr(promo_group, 'period_discounts', None) or {}
for k, v in raw_discounts.items():
try:
period_discounts[int(k)] = max(0, min(100, int(v)))
except (TypeError, ValueError):
pass
periods: list[MiniAppTariffPeriod] = []
if tariff.period_prices:
for period_str, original_price_kopeks in sorted(tariff.period_prices.items(), key=lambda x: int(x[0])):
period_days = int(period_str)
# Применяем скидку промогруппы
discount_percent = period_discounts.get(period_days, 0)
if discount_percent > 0:
price_kopeks = int(original_price_kopeks * (100 - discount_percent) / 100)
# Применяем скидку промогруппы + promo-offer (stacked)
group_pct = promo_group.get_discount_percent('period', period_days) if promo_group else 0
offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if group_pct > 0 or offer_pct > 0:
price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(original_price_kopeks, group_pct, offer_pct)
# Комбинированный процент для отображения
remaining = (100 - group_pct) * (100 - offer_pct)
discount_percent = 100 - remaining // 100
else:
price_kopeks = original_price_kopeks
discount_percent = 0
months = max(1, period_days // 30)
per_month = price_kopeks // months if months > 0 else price_kopeks
@@ -6197,31 +6176,31 @@ async def _build_tariff_model(
is_switch_free = None
if current_tariff and current_tariff.id != tariff.id:
current_is_daily = getattr(current_tariff, 'is_daily', False)
new_is_daily = getattr(tariff, 'is_daily', False)
if current_is_daily and not new_is_daily:
# Переключение С суточного НА периодный - полная оплата нового тарифа
# Берём минимальную цену из периодов нового тарифа
min_period_price = None
if periods:
min_period_price = min(p.price_kopeks for p in periods)
if min_period_price and min_period_price > 0:
switch_cost_kopeks = min_period_price
switch_cost_label = settings.format_price(min_period_price)
is_upgrade = True # Показываем как платный переход
is_switch_free = False
elif remaining_days > 0:
# Обычный расчёт для периодных тарифов
cost, upgrade = _calculate_tariff_switch_cost(current_tariff, tariff, remaining_days, promo_group, user)
switch_cost_kopeks = cost
switch_cost_label = settings.format_price(cost) if cost > 0 else None
is_upgrade = upgrade
is_switch_free = cost == 0
# PricingEngine обрабатывает все случаи: periodic↔periodic, daily→periodic, periodic→daily
result = _calculate_tariff_switch(current_tariff, tariff, remaining_days, user=user)
switch_cost_kopeks = result.upgrade_cost
switch_cost_label = settings.format_price(result.upgrade_cost) if result.upgrade_cost > 0 else None
is_upgrade = result.is_upgrade
is_switch_free = result.upgrade_cost == 0
# Суточный тариф
is_daily = getattr(tariff, 'is_daily', False)
daily_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0) if is_daily else 0
raw_daily_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0) if is_daily else 0
daily_price_kopeks = raw_daily_price_kopeks
# Применяем скидку промогруппы + promo-offer для суточного тарифа (period_hint=1)
if is_daily and daily_price_kopeks > 0:
daily_group_pct = (
promo_group.get_discount_percent('period', 1)
if promo_group and hasattr(promo_group, 'get_discount_percent')
else 0
)
daily_offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if daily_group_pct > 0 or daily_offer_pct > 0:
daily_price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
raw_daily_price_kopeks, daily_group_pct, daily_offer_pct
)
daily_price_label = (
settings.format_price(daily_price_kopeks) + '/день' if is_daily and daily_price_kopeks > 0 else None
)
@@ -6250,26 +6229,31 @@ async def _build_tariff_model(
)
async def _build_current_tariff_model(db: AsyncSession, tariff, promo_group=None) -> MiniAppCurrentTariff:
async def _build_current_tariff_model(db: AsyncSession, tariff, promo_group=None, user=None) -> MiniAppCurrentTariff:
"""Создаёт модель текущего тарифа."""
servers_count = len(tariff.allowed_squads) if tariff.allowed_squads else 0
monthly_price = _get_tariff_monthly_price(tariff)
# Применяем скидку промогруппы для 30-дневного периода
if promo_group:
raw_discounts = getattr(promo_group, 'period_discounts', None) or {}
for k, v in raw_discounts.items():
try:
if int(k) == 30:
discount = max(0, min(100, int(v)))
monthly_price = int(monthly_price * (100 - discount) / 100)
break
except (TypeError, ValueError):
pass
# Применяем скидку промогруппы + promo-offer для 30-дневного периода
group_pct = promo_group.get_discount_percent('period', 30) if promo_group else 0
offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if group_pct > 0 or offer_pct > 0:
monthly_price, _, _ = PricingEngine.apply_stacked_discounts(monthly_price, group_pct, offer_pct)
# Суточный тариф
is_daily = getattr(tariff, 'is_daily', False)
daily_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0) if is_daily else 0
raw_daily_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0) if is_daily else 0
daily_price_kopeks = raw_daily_price_kopeks
# Применяем скидку промогруппы + promo-offer для суточного тарифа (period_hint=1)
if is_daily and daily_price_kopeks > 0:
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_offer_pct = get_user_active_promo_discount_percent(user) if user else 0
if daily_group_pct > 0 or daily_offer_pct > 0:
daily_price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
raw_daily_price_kopeks, daily_group_pct, daily_offer_pct
)
daily_price_label = (
settings.format_price(daily_price_kopeks) + '/день' if is_daily and daily_price_kopeks > 0 else None
)
@@ -6310,11 +6294,9 @@ async def get_tariffs_endpoint(
)
# Получаем промогруппу пользователя (с приоритетом)
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
promo_group_id = promo_group.id if promo_group else None
# Получаем тарифы, доступные пользователю
@@ -6335,7 +6317,7 @@ async def get_tariffs_endpoint(
if current_tariff_id:
current_tariff = await get_tariff_by_id(db, current_tariff_id)
if current_tariff:
current_tariff_model = await _build_current_tariff_model(db, current_tariff, promo_group)
current_tariff_model = await _build_current_tariff_model(db, current_tariff, promo_group, user=user)
# Формируем список тарифов
tariff_models: list[MiniAppTariff] = []
@@ -6398,12 +6380,14 @@ async def purchase_tariff_endpoint(
},
)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import PricingEngine, pricing_engine
user = await lock_user_for_pricing(db, user.id)
# Проверяем доступность тарифа для пользователя
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
promo_group = PricingEngine.resolve_promo_group(user)
promo_group_id = promo_group.id if promo_group else None
if not tariff.is_available_for_promo_group(promo_group_id):
raise HTTPException(
@@ -6414,67 +6398,28 @@ async def purchase_tariff_endpoint(
},
)
# Получаем цену
# For daily tariffs, force period_days=1 (protect against client manipulation)
is_daily_tariff = getattr(tariff, 'is_daily', False)
if is_daily_tariff:
# Для суточного тарифа принудительно 1 день (защита от манипуляций с period_days)
payload.period_days = 1
# Для суточного тарифа берём daily_price_kopeks (первый день)
base_price_kopeks = getattr(tariff, 'daily_price_kopeks', 0)
if base_price_kopeks <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
'code': 'invalid_daily_price',
'message': 'Daily tariff has no price configured',
},
)
else:
# Для обычного тарифа получаем цену за выбранный период
base_price_kopeks = tariff.get_price_for_period(payload.period_days)
if base_price_kopeks is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
'code': 'invalid_period',
'message': 'Invalid period for this tariff',
},
)
# Add extra device cost if user renews same tariff with purchased extra devices
# Calculate price via PricingEngine (single source of truth)
subscription = getattr(user, 'subscription', None)
if not is_daily_tariff and subscription and subscription.tariff_id == tariff.id:
device_price_per_unit = (
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
)
extra_devices = max(0, (subscription.device_limit or 0) - (tariff.device_limit or 0))
base_price_kopeks += extra_devices * device_price_per_unit
device_limit = None
if subscription and subscription.tariff_id == tariff.id:
device_limit = subscription.device_limit
# Применяем скидку промогруппы (только для обычных тарифов, не для суточных)
price_kopeks = base_price_kopeks
discount_percent = 0
if not is_daily_tariff and promo_group:
raw_discounts = getattr(promo_group, 'period_discounts', None) or {}
for k, v in raw_discounts.items():
try:
if int(k) == payload.period_days:
discount_percent = max(0, min(100, int(v)))
break
except (TypeError, ValueError):
pass
if discount_percent > 0:
from app.services.pricing_engine import PricingEngine
price_kopeks = PricingEngine.apply_discount(base_price_kopeks, discount_percent)
# Apply personal promo_offer discount on top of group discount
consume_promo_offer = False
if not is_daily_tariff:
promo_offer_pct = get_user_active_promo_discount_percent(user)
if promo_offer_pct > 0:
offer_discount_value = price_kopeks * promo_offer_pct // 100
price_kopeks = price_kopeks - offer_discount_value
consume_promo_offer = True
result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
payload.period_days,
device_limit=device_limit,
user=user,
)
price_kopeks = result.final_total
consume_promo_offer = result.promo_offer_discount > 0
bd = result.breakdown
group_pcts = bd.get('group_discount_pct', {})
discount_percent = group_pcts.get('period', 0)
# Проверяем баланс
if user.balance_kopeks < price_kopeks:
@@ -6579,6 +6524,7 @@ async def purchase_tariff_endpoint(
subscription,
reset_traffic=True,
reset_reason='покупка тарифа (miniapp)',
sync_squads=True,
)
# Сохраняем корзину для автопродления
@@ -6615,70 +6561,28 @@ async def purchase_tariff_endpoint(
)
def _get_user_period_discount(user, period_days: int) -> int:
"""Получает скидку пользователя на период (унифицировано с ботом)."""
promo_group = getattr(user, 'promo_group', None) if user else None
if promo_group:
discount = promo_group.get_discount_percent('period', period_days)
if discount > 0:
return discount
personal_discount = get_user_active_promo_discount_percent(user) if user else 0
return personal_discount
def _apply_promo_discount(price: int, discount_percent: int) -> int:
"""Применяет скидку к цене (через PricingEngine для единообразия)."""
from app.services.pricing_engine import PricingEngine
return PricingEngine.apply_discount(price, discount_percent)
def _calculate_tariff_switch_cost(
def _calculate_tariff_switch(
current_tariff,
new_tariff,
remaining_days: int,
promo_group=None,
user=None,
) -> tuple[int, bool]:
"""
Рассчитывает стоимость переключения тарифа.
Логика унифицирована с ботом (tariff_purchase.py).
Формула: (new_monthly - current_monthly) * remaining_days / 30
Скидка применяется к обоим тарифам одинаково.
):
"""Рассчитывает стоимость переключения тарифа.
Делегирует расчёт в PricingEngine.calculate_tariff_switch_cost().
PricingEngine автоматически определяет тип переключения
(periodicperiodic, dailyperiodic, periodicdaily).
Returns:
(cost_kopeks, is_upgrade) - стоимость доплаты и флаг апгрейда
TariffSwitchResult
"""
current_monthly = _get_tariff_monthly_price(current_tariff)
new_monthly = _get_tariff_monthly_price(new_tariff)
from app.services.pricing_engine import pricing_engine
discount_percent = _get_user_period_discount(user, 30) if user else 0
# Fallback на promo_group.period_discounts если user не передан
if discount_percent == 0 and promo_group:
raw_discounts = getattr(promo_group, 'period_discounts', None) or {}
for k, v in raw_discounts.items():
try:
if int(k) == 30:
discount_percent = max(0, min(100, int(v)))
break
except (TypeError, ValueError):
pass
if discount_percent > 0:
current_monthly = _apply_promo_discount(current_monthly, discount_percent)
new_monthly = _apply_promo_discount(new_monthly, discount_percent)
price_diff = new_monthly - current_monthly
if price_diff <= 0:
return 0, False
upgrade_cost = int(price_diff * remaining_days / 30)
return upgrade_cost, True
return pricing_engine.calculate_tariff_switch_cost(
current_tariff,
new_tariff,
remaining_days,
user=user,
)
@router.post('/subscription/tariff/switch/preview')
@@ -6725,11 +6629,9 @@ async def preview_tariff_switch_endpoint(
)
# Проверяем доступность тарифа для пользователя
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
promo_group_id = promo_group.id if promo_group else None
if not new_tariff.is_available_for_promo_group(promo_group_id):
raise HTTPException(
@@ -6743,22 +6645,10 @@ async def preview_tariff_switch_endpoint(
delta = subscription.end_date - datetime.now(UTC)
remaining_days = max(0, delta.days)
# Рассчитываем стоимость переключения
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
new_is_daily = getattr(new_tariff, 'is_daily', False)
if current_is_daily and not new_is_daily:
# Переключение С суточного НА периодный - полная оплата нового тарифа
# Берём минимальную цену из периодов нового тарифа
min_period_price = 0
if new_tariff.period_prices:
min_period_price = min(new_tariff.period_prices.values())
upgrade_cost = min_period_price
is_upgrade = min_period_price > 0
else:
upgrade_cost, is_upgrade = _calculate_tariff_switch_cost(
current_tariff, new_tariff, remaining_days, promo_group, user
)
# Рассчитываем стоимость переключения (PricingEngine обрабатывает все случаи: periodic↔periodic, daily↔periodic)
switch_result = _calculate_tariff_switch(current_tariff, new_tariff, remaining_days, user=user)
upgrade_cost = switch_result.upgrade_cost
is_upgrade = switch_result.is_upgrade
balance = user.balance_kopeks or 0
has_enough = balance >= upgrade_cost
@@ -6836,11 +6726,9 @@ async def switch_tariff_endpoint(
)
# Проверяем доступность тарифа
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
promo_group_id = promo_group.id if promo_group else None
if not new_tariff.is_available_for_promo_group(promo_group_id):
raise HTTPException(
@@ -6848,35 +6736,26 @@ async def switch_tariff_endpoint(
detail={'code': 'tariff_not_available', 'message': 'Tariff not available'},
)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Рассчитываем оставшиеся дни
remaining_days = 0
if subscription.end_date and subscription.end_date > datetime.now(UTC):
delta = subscription.end_date - datetime.now(UTC)
remaining_days = max(0, delta.days)
# Рассчитываем стоимость
# Рассчитываем стоимость (PricingEngine обрабатывает все случаи)
switch_result = _calculate_tariff_switch(current_tariff, new_tariff, remaining_days, user=user)
upgrade_cost = switch_result.upgrade_cost
new_period_days = switch_result.new_period_days
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
new_is_daily = getattr(new_tariff, 'is_daily', False)
switching_from_daily = current_is_daily and not new_is_daily
if switching_from_daily:
# Переключение С суточного НА периодный - полная оплата нового тарифа (минимальный период)
min_period_days = 30 # По умолчанию месяц
min_period_price = 0
if new_tariff.period_prices:
# Находим минимальный период и его цену
min_period_days = min(int(k) for k in new_tariff.period_prices.keys())
min_period_price = new_tariff.period_prices.get(str(min_period_days), 0)
upgrade_cost = min_period_price
is_upgrade = min_period_price > 0
# remaining_days для нового тарифа будет равен min_period_days после покупки
new_period_days = min_period_days
else:
upgrade_cost, is_upgrade = _calculate_tariff_switch_cost(
current_tariff, new_tariff, remaining_days, promo_group, user
)
new_period_days = 0 # Не меняем дату окончания
# Списываем доплату если апгрейд
if upgrade_cost > 0:
if user.balance_kopeks < upgrade_cost:
@@ -6899,6 +6778,7 @@ async def switch_tariff_endpoint(
user,
upgrade_cost,
description,
consume_promo_offer=switch_result.offer_discount_pct > 0,
mark_as_paid_subscription=True,
commit=False,
)
@@ -7018,6 +6898,7 @@ async def switch_tariff_endpoint(
subscription,
reset_traffic=should_reset_traffic,
reset_reason='смена тарифа',
sync_squads=True,
)
except Exception as e:
logger.error('Ошибка синхронизации с RemnaWave при смене тарифа', error=e)
@@ -7143,20 +7024,18 @@ async def purchase_traffic_topup_endpoint(
base_price_kopeks = packages[payload.gb]
# Применяем скидку промогруппы на трафик
traffic_discount_percent = 0
promo_group = (
user.get_primary_promo_group()
if hasattr(user, 'get_primary_promo_group')
else getattr(user, 'promo_group', None)
)
if promo_group:
apply_to_addons = getattr(promo_group, 'apply_discounts_to_addons', True)
if apply_to_addons:
traffic_discount_percent = max(0, min(100, int(getattr(promo_group, 'traffic_discount_percent', 0) or 0)))
# Lock user BEFORE price computation to prevent TOCTOU on promo discount
from app.database.crud.user import lock_user_for_pricing
if traffic_discount_percent > 0:
base_price_kopeks = int(base_price_kopeks * (100 - traffic_discount_percent) / 100)
user = await lock_user_for_pricing(db, user.id)
# Применяем скидку промогруппы на трафик через PricingEngine
from app.services.pricing_engine import pricing_engine
base_price_kopeks, _discount_val, traffic_discount_percent = pricing_engine.calculate_traffic_discount(
base_price_kopeks,
user,
)
# Пропорциональный расчет цены с учетом оставшегося времени подписки
final_price, days_charged = calculate_prorated_price(
@@ -7280,7 +7159,21 @@ async def toggle_daily_subscription_pause_endpoint(
new_paused_state = not is_currently_paused
subscription.is_daily_paused = new_paused_state
daily_price = getattr(tariff, 'daily_price_kopeks', 0)
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
# Lock user BEFORE price computation to prevent TOCTOU on promo discount
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Apply group discount to daily price (consistent with DailySubscriptionService and resume-after-topup)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
# Если снимаем с паузы, проверяем баланс и списываем оплату
if not new_paused_state:
+1 -1
View File
@@ -127,7 +127,7 @@
Функции: нет
- `app/database/crud/subscription.py` — Python-модуль
Классы: нет
Функции: `_get_discount_percent`
Функции: нет (ранее `_get_discount_percent` — удалена при консолидации в PricingEngine; см. `PricingEngine.resolve_promo_group()` и `PromoGroup.get_discount_percent()`)
- `app/database/crud/subscription_conversion.py` — Python-модуль
Классы: нет
Функции: нет
@@ -0,0 +1,29 @@
"""make riopay_payments.user_id nullable for guest purchases
Revision ID: 0039
Revises: 0038
Create Date: 2026-03-18
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = '0039'
down_revision: Union[str, None] = '0038'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.alter_column('riopay_payments', 'user_id', existing_type=sa.Integer(), nullable=True)
op.drop_constraint('riopay_payments_user_id_fkey', 'riopay_payments', type_='foreignkey')
op.create_foreign_key(None, 'riopay_payments', 'users', ['user_id'], ['id'], ondelete='SET NULL')
def downgrade() -> None:
op.drop_constraint(None, 'riopay_payments', type_='foreignkey')
op.create_foreign_key('riopay_payments_user_id_fkey', 'riopay_payments', 'users', ['user_id'], ['id'])
op.alter_column('riopay_payments', 'user_id', existing_type=sa.Integer(), nullable=False)
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = 'remnawave-bedolaga-telegram-bot'
version = "3.32.2"
version = "3.33.0"
description = 'Telegram bot for RemnaWave VPN service'
readme = 'README.md'
license = { text = 'MIT' }
+56 -2
View File
@@ -36,6 +36,7 @@ async def test_commission_accrues_before_minimum_first_topup(monkeypatch):
monkeypatch.setattr(referral_service, 'add_user_balance', add_user_balance_mock)
create_referral_earning_mock = AsyncMock()
monkeypatch.setattr(referral_service, 'create_referral_earning', create_referral_earning_mock)
monkeypatch.setattr(referral_service, 'get_user_campaign_id', AsyncMock(return_value=None))
monkeypatch.setattr(referral_service.settings, 'REFERRAL_MINIMUM_TOPUP_KOPEKS', 20000)
monkeypatch.setattr(referral_service.settings, 'REFERRAL_FIRST_TOPUP_BONUS_KOPEKS', 5000)
@@ -61,5 +62,58 @@ async def test_commission_accrues_before_minimum_first_topup(monkeypatch):
assert earning_call.kwargs['amount_kopeks'] == 3750
assert earning_call.kwargs['reason'] == 'referral_commission_topup'
db.commit.assert_not_awaited()
db.execute.assert_not_awaited()
async def test_first_topup_inviter_gets_fixed_plus_commission(monkeypatch):
"""Inviter bonus should be fixed bonus + commission, not max(fixed, commission)."""
user = SimpleNamespace(
id=1,
telegram_id=101,
full_name='Test User',
referred_by_id=2,
has_made_first_topup=False,
)
referrer = SimpleNamespace(
id=2,
telegram_id=202,
full_name='Referrer',
email=None,
)
db = SimpleNamespace(
commit=AsyncMock(),
execute=AsyncMock(),
)
get_user_mock = AsyncMock(side_effect=[user, referrer])
monkeypatch.setattr(referral_service, 'get_user_by_id', get_user_mock)
add_user_balance_mock = AsyncMock(return_value=True)
monkeypatch.setattr(referral_service, 'add_user_balance', add_user_balance_mock)
create_referral_earning_mock = AsyncMock()
monkeypatch.setattr(referral_service, 'create_referral_earning', create_referral_earning_mock)
monkeypatch.setattr(referral_service, 'get_commission_payment_count', AsyncMock(return_value=0))
monkeypatch.setattr(referral_service, 'get_user_campaign_id', AsyncMock(return_value=None))
monkeypatch.setattr(referral_service, 'get_effective_referral_commission_percent', lambda u: 15)
monkeypatch.setattr(referral_service.settings, 'REFERRAL_MINIMUM_TOPUP_KOPEKS', 10000)
monkeypatch.setattr(referral_service.settings, 'REFERRAL_FIRST_TOPUP_BONUS_KOPEKS', 5000)
monkeypatch.setattr(referral_service.settings, 'REFERRAL_INVITER_BONUS_KOPEKS', 5000) # 50 rub
monkeypatch.setattr(referral_service.settings, 'REFERRAL_COMMISSION_PERCENT', 15)
topup_amount = 50000 # 500 rub
result = await referral_service.process_referral_topup(db, user.id, topup_amount)
assert result is True
assert user.has_made_first_topup is True
# add_user_balance called twice: first for referral's own bonus, then for inviter bonus
assert add_user_balance_mock.await_count == 2
# Second call is the inviter bonus: fixed 5000 + commission 15% of 50000 = 7500 → total 12500
inviter_call = add_user_balance_mock.await_args_list[1]
expected_commission = int(50000 * 15 / 100) # 7500
expected_inviter_bonus = 5000 + expected_commission # 12500
assert inviter_call.args[2] == expected_inviter_bonus
# With old max() logic, this would have been max(5000, 7500) = 7500 — wrong!
assert expected_inviter_bonus == 12500
+23 -1
View File
@@ -265,6 +265,7 @@ class TestCalculateRenewalPriceTariffMode:
subscription.purchased_traffic_gb = 0
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_offer_discount_percent = 0
user.promo_offer_expires_at = None
with (
@@ -293,6 +294,7 @@ class TestCalculateRenewalPriceTariffMode:
subscription.purchased_traffic_gb = 0
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_offer_discount_percent = 0
user.promo_offer_expires_at = None
with (
@@ -319,6 +321,7 @@ class TestCalculateRenewalPriceTariffMode:
subscription.device_limit = 4 # 2 extra devices
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
patch('app.services.pricing_engine.settings') as ms,
@@ -344,13 +347,14 @@ class TestCalculateRenewalPriceTariffMode:
promo_group.get_discount_percent.return_value = 10
user = MagicMock()
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=5),
patch('app.services.pricing_engine.settings') as ms,
):
ms.PRICE_PER_DEVICE = 5000
result = await engine.calculate_renewal_price(db, subscription, 30, user=user)
assert result.base_price == 20000
assert result.base_price == 18000 # 20000 discounted by 10%
assert result.promo_group_discount == 2000
# After group: 18000, then 5% off 18000 = 900
assert result.promo_offer_discount == 900
@@ -367,9 +371,12 @@ class TestCalculateRenewalPriceTariffMode:
subscription.tariff.device_limit = 1
subscription.tariff.device_price_kopeks = None
subscription.tariff.id = 1
subscription.tariff.is_daily = False
subscription.tariff.can_purchase_custom_days.return_value = False
subscription.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
patch('app.services.pricing_engine.settings') as ms,
@@ -395,6 +402,7 @@ class TestCalculateRenewalPriceTariffMode:
sub.device_limit = 2 # less than tariff's 5
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
with patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0):
result = await engine.calculate_renewal_price(db, sub, 30, user=user)
@@ -441,6 +449,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 2
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
user.promo_offer_discount_percent = 0
user.promo_offer_expires_at = None
@@ -479,6 +488,7 @@ class TestCalculateRenewalPriceClassicMode:
promo_group.get_discount_percent.return_value = 20
user = MagicMock()
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
user.promo_group_id = 1
user.promo_offer_discount_percent = 10
user.promo_offer_expires_at = None
@@ -511,6 +521,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
@@ -539,6 +550,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 5
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
@@ -569,6 +581,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
s1 = _make_server(price_kopeks=5000, server_id=10, squad_uuid='uuid-found')
s3 = _make_server(price_kopeks=3000, server_id=30, squad_uuid='uuid-found2')
@@ -610,6 +623,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
@@ -640,6 +654,7 @@ class TestCalculateRenewalPriceClassicMode:
subscription.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
with (
patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=0),
@@ -669,6 +684,7 @@ class TestCalculateRenewalPriceClassicMode:
sub.device_limit = 1
user = MagicMock()
user.promo_group = None
user.get_primary_promo_group.return_value = None
user.promo_group_id = None
server = _make_server(price_kopeks=3000, squad_uuid='uuid-s1')
@@ -717,6 +733,7 @@ class TestCalculateRenewalPriceClassicMode:
promo_group.get_discount_percent = MagicMock(side_effect=discount_by_category)
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
user.promo_group_id = 1
server = _make_server(price_kopeks=6000, squad_uuid='uuid-s1')
@@ -898,6 +915,7 @@ class TestOriginalPriceIdentity:
promo_group = MagicMock()
promo_group.get_discount_percent = MagicMock(return_value=25)
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
with patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=15):
result = await engine.calculate_renewal_price(db, sub, 30, user=user)
@@ -922,6 +940,7 @@ class TestOriginalPriceIdentity:
promo_group = MagicMock()
promo_group.get_discount_percent = MagicMock(return_value=20)
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
user.promo_group_id = 1
server = _make_server(price_kopeks=4000, squad_uuid='uuid-s1')
@@ -965,6 +984,9 @@ class TestOriginalPriceIdentity:
promo_group = MagicMock()
promo_group.get_discount_percent = MagicMock(return_value=10)
user.promo_group = promo_group
user.get_primary_promo_group.return_value = promo_group
sub.tariff.is_daily = False
sub.tariff.can_purchase_custom_days.return_value = False
with patch('app.services.pricing_engine.get_user_active_promo_discount_percent', return_value=5):
result = await engine.calculate_renewal_price(db, sub, 30, user=user)
assert result.original_total == 20000 # undiscounted subtotal
Generated
+1 -2
View File
@@ -551,7 +551,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/ab/d26750f2b7242c2b90ea2ad71de70cfcd73a948a49513188a0fc0d6fc15a/greenlet-3.3.1-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:7ab327905cabb0622adca5971e488064e35115430cec2c35a50fd36e72a315b3", size = 275205, upload-time = "2026-01-23T15:30:24.556Z" },
{ url = "https://files.pythonhosted.org/packages/10/d3/be7d19e8fad7c5a78eeefb2d896a08cd4643e1e90c605c4be3b46264998f/greenlet-3.3.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65be2f026ca6a176f88fb935ee23c18333ccea97048076aef4db1ef5bc0713ac", size = 599284, upload-time = "2026-01-23T16:00:58.584Z" },
{ url = "https://files.pythonhosted.org/packages/ae/21/fe703aaa056fdb0f17e5afd4b5c80195bbdab701208918938bd15b00d39b/greenlet-3.3.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7a3ae05b3d225b4155bda56b072ceb09d05e974bc74be6c3fc15463cf69f33fd", size = 610274, upload-time = "2026-01-23T16:05:29.312Z" },
{ url = "https://files.pythonhosted.org/packages/06/00/95df0b6a935103c0452dad2203f5be8377e551b8466a29650c4c5a5af6cc/greenlet-3.3.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:12184c61e5d64268a160226fb4818af4df02cfead8379d7f8b99a56c3a54ff3e", size = 624375, upload-time = "2026-01-23T16:15:55.915Z" },
{ url = "https://files.pythonhosted.org/packages/cb/86/5c6ab23bb3c28c21ed6bebad006515cfe08b04613eb105ca0041fecca852/greenlet-3.3.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6423481193bbbe871313de5fd06a082f2649e7ce6e08015d2a76c1e9186ca5b3", size = 612904, upload-time = "2026-01-23T15:32:52.317Z" },
{ url = "https://files.pythonhosted.org/packages/c2/f3/7949994264e22639e40718c2daf6f6df5169bf48fb038c008a489ec53a50/greenlet-3.3.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:33a956fe78bbbda82bfc95e128d61129b32d66bcf0a20a1f0c08aa4839ffa951", size = 1567316, upload-time = "2026-01-23T16:04:23.316Z" },
{ url = "https://files.pythonhosted.org/packages/8d/6e/d73c94d13b6465e9f7cd6231c68abde838bb22408596c05d9059830b7872/greenlet-3.3.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4b065d3284be43728dd280f6f9a13990b56470b81be20375a207cdc814a983f2", size = 1636549, upload-time = "2026-01-23T15:33:48.643Z" },
@@ -1116,7 +1115,7 @@ wheels = [
[[package]]
name = "remnawave-bedolaga-telegram-bot"
version = "3.31.0"
version = "3.32.4"
source = { virtual = "." }
dependencies = [
{ name = "aiogram" },